editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   78    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   79    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   80    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   82    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{
  100    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  101};
  102use linked_editing_ranges::refresh_linked_ranges;
  103pub use proposed_changes_editor::{
  104    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  105};
  106use similar::{ChangeTag, TextDiff};
  107use std::iter::Peekable;
  108use task::{ResolvedTask, TaskTemplate, TaskVariables};
  109
  110use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  111pub use lsp::CompletionContext;
  112use lsp::{
  113    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  114    LanguageServerId,
  115};
  116use mouse_context_menu::MouseContextMenu;
  117use movement::TextLayoutDetails;
  118pub use multi_buffer::{
  119    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  120    ToPoint,
  121};
  122use multi_buffer::{
  123    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  124};
  125use ordered_float::OrderedFloat;
  126use parking_lot::{Mutex, RwLock};
  127use project::{
  128    lsp_store::{FormatTarget, FormatTrigger},
  129    project_settings::{GitGutterSetting, ProjectSettings},
  130    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  131    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  132};
  133use rand::prelude::*;
  134use rpc::{proto::*, ErrorExt};
  135use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  136use selections_collection::{
  137    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  138};
  139use serde::{Deserialize, Serialize};
  140use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  141use smallvec::SmallVec;
  142use snippet::Snippet;
  143use std::{
  144    any::TypeId,
  145    borrow::Cow,
  146    cell::RefCell,
  147    cmp::{self, Ordering, Reverse},
  148    mem,
  149    num::NonZeroU32,
  150    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  151    path::{Path, PathBuf},
  152    rc::Rc,
  153    sync::Arc,
  154    time::{Duration, Instant},
  155};
  156pub use sum_tree::Bias;
  157use sum_tree::TreeMap;
  158use text::{BufferId, OffsetUtf16, Rope};
  159use theme::{
  160    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  161    ThemeColors, ThemeSettings,
  162};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  165    ListItem, Popover, PopoverMenuHandle, Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::find_url;
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189#[doc(hidden)]
  190pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  191
  192pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  193pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  194
  195pub fn render_parsed_markdown(
  196    element_id: impl Into<ElementId>,
  197    parsed: &language::ParsedMarkdown,
  198    editor_style: &EditorStyle,
  199    workspace: Option<WeakView<Workspace>>,
  200    cx: &mut WindowContext,
  201) -> InteractiveText {
  202    let code_span_background_color = cx
  203        .theme()
  204        .colors()
  205        .editor_document_highlight_read_background;
  206
  207    let highlights = gpui::combine_highlights(
  208        parsed.highlights.iter().filter_map(|(range, highlight)| {
  209            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  210            Some((range.clone(), highlight))
  211        }),
  212        parsed
  213            .regions
  214            .iter()
  215            .zip(&parsed.region_ranges)
  216            .filter_map(|(region, range)| {
  217                if region.code {
  218                    Some((
  219                        range.clone(),
  220                        HighlightStyle {
  221                            background_color: Some(code_span_background_color),
  222                            ..Default::default()
  223                        },
  224                    ))
  225                } else {
  226                    None
  227                }
  228            }),
  229    );
  230
  231    let mut links = Vec::new();
  232    let mut link_ranges = Vec::new();
  233    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  234        if let Some(link) = region.link.clone() {
  235            links.push(link);
  236            link_ranges.push(range.clone());
  237        }
  238    }
  239
  240    InteractiveText::new(
  241        element_id,
  242        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  243    )
  244    .on_click(link_ranges, move |clicked_range_ix, cx| {
  245        match &links[clicked_range_ix] {
  246            markdown::Link::Web { url } => cx.open_url(url),
  247            markdown::Link::Path { path } => {
  248                if let Some(workspace) = &workspace {
  249                    _ = workspace.update(cx, |workspace, cx| {
  250                        workspace.open_abs_path(path.clone(), false, cx).detach();
  251                    });
  252                }
  253            }
  254        }
  255    })
  256}
  257
  258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  259pub(crate) enum InlayId {
  260    Suggestion(usize),
  261    Hint(usize),
  262}
  263
  264impl InlayId {
  265    fn id(&self) -> usize {
  266        match self {
  267            Self::Suggestion(id) => *id,
  268            Self::Hint(id) => *id,
  269        }
  270    }
  271}
  272
  273enum DiffRowHighlight {}
  274enum DocumentHighlightRead {}
  275enum DocumentHighlightWrite {}
  276enum InputComposition {}
  277
  278#[derive(Copy, Clone, PartialEq, Eq)]
  279pub enum Direction {
  280    Prev,
  281    Next,
  282}
  283
  284#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  285pub enum Navigated {
  286    Yes,
  287    No,
  288}
  289
  290impl Navigated {
  291    pub fn from_bool(yes: bool) -> Navigated {
  292        if yes {
  293            Navigated::Yes
  294        } else {
  295            Navigated::No
  296        }
  297    }
  298}
  299
  300pub fn init_settings(cx: &mut AppContext) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut AppContext) {
  305    init_settings(cx);
  306
  307    workspace::register_project_item::<Editor>(cx);
  308    workspace::FollowableViewRegistry::register::<Editor>(cx);
  309    workspace::register_serializable_item::<Editor>(cx);
  310
  311    cx.observe_new_views(
  312        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  313            workspace.register_action(Editor::new_file);
  314            workspace.register_action(Editor::new_file_vertical);
  315            workspace.register_action(Editor::new_file_horizontal);
  316        },
  317    )
  318    .detach();
  319
  320    cx.on_action(move |_: &workspace::NewFile, cx| {
  321        let app_state = workspace::AppState::global(cx);
  322        if let Some(app_state) = app_state.upgrade() {
  323            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  324                Editor::new_file(workspace, &Default::default(), cx)
  325            })
  326            .detach();
  327        }
  328    });
  329    cx.on_action(move |_: &workspace::NewWindow, cx| {
  330        let app_state = workspace::AppState::global(cx);
  331        if let Some(app_state) = app_state.upgrade() {
  332            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  333                Editor::new_file(workspace, &Default::default(), cx)
  334            })
  335            .detach();
  336        }
  337    });
  338}
  339
  340pub struct SearchWithinRange;
  341
  342trait InvalidationRegion {
  343    fn ranges(&self) -> &[Range<Anchor>];
  344}
  345
  346#[derive(Clone, Debug, PartialEq)]
  347pub enum SelectPhase {
  348    Begin {
  349        position: DisplayPoint,
  350        add: bool,
  351        click_count: usize,
  352    },
  353    BeginColumnar {
  354        position: DisplayPoint,
  355        reset: bool,
  356        goal_column: u32,
  357    },
  358    Extend {
  359        position: DisplayPoint,
  360        click_count: usize,
  361    },
  362    Update {
  363        position: DisplayPoint,
  364        goal_column: u32,
  365        scroll_delta: gpui::Point<f32>,
  366    },
  367    End,
  368}
  369
  370#[derive(Clone, Debug)]
  371pub enum SelectMode {
  372    Character,
  373    Word(Range<Anchor>),
  374    Line(Range<Anchor>),
  375    All,
  376}
  377
  378#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  379pub enum EditorMode {
  380    SingleLine { auto_width: bool },
  381    AutoHeight { max_lines: usize },
  382    Full,
  383}
  384
  385#[derive(Copy, Clone, Debug)]
  386pub enum SoftWrap {
  387    /// Prefer not to wrap at all.
  388    ///
  389    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  390    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  391    GitDiff,
  392    /// Prefer a single line generally, unless an overly long line is encountered.
  393    None,
  394    /// Soft wrap lines that exceed the editor width.
  395    EditorWidth,
  396    /// Soft wrap lines at the preferred line length.
  397    Column(u32),
  398    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  399    Bounded(u32),
  400}
  401
  402#[derive(Clone)]
  403pub struct EditorStyle {
  404    pub background: Hsla,
  405    pub local_player: PlayerColor,
  406    pub text: TextStyle,
  407    pub scrollbar_width: Pixels,
  408    pub syntax: Arc<SyntaxTheme>,
  409    pub status: StatusColors,
  410    pub inlay_hints_style: HighlightStyle,
  411    pub suggestions_style: HighlightStyle,
  412    pub unnecessary_code_fade: f32,
  413}
  414
  415impl Default for EditorStyle {
  416    fn default() -> Self {
  417        Self {
  418            background: Hsla::default(),
  419            local_player: PlayerColor::default(),
  420            text: TextStyle::default(),
  421            scrollbar_width: Pixels::default(),
  422            syntax: Default::default(),
  423            // HACK: Status colors don't have a real default.
  424            // We should look into removing the status colors from the editor
  425            // style and retrieve them directly from the theme.
  426            status: StatusColors::dark(),
  427            inlay_hints_style: HighlightStyle::default(),
  428            suggestions_style: HighlightStyle::default(),
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446type CompletionId = usize;
  447
  448#[derive(Clone, Debug)]
  449struct CompletionState {
  450    // render_inlay_ids represents the inlay hints that are inserted
  451    // for rendering the inline completions. They may be discontinuous
  452    // in the event that the completion provider returns some intersection
  453    // with the existing content.
  454    render_inlay_ids: Vec<InlayId>,
  455    // text is the resulting rope that is inserted when the user accepts a completion.
  456    text: Rope,
  457    // position is the position of the cursor when the completion was triggered.
  458    position: multi_buffer::Anchor,
  459    // delete_range is the range of text that this completion state covers.
  460    // if the completion is accepted, this range should be deleted.
  461    delete_range: Option<Range<multi_buffer::Anchor>>,
  462}
  463
  464#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  465struct EditorActionId(usize);
  466
  467impl EditorActionId {
  468    pub fn post_inc(&mut self) -> Self {
  469        let answer = self.0;
  470
  471        *self = Self(answer + 1);
  472
  473        Self(answer)
  474    }
  475}
  476
  477// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  478// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  479
  480type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  481type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  482
  483#[derive(Default)]
  484struct ScrollbarMarkerState {
  485    scrollbar_size: Size<Pixels>,
  486    dirty: bool,
  487    markers: Arc<[PaintQuad]>,
  488    pending_refresh: Option<Task<Result<()>>>,
  489}
  490
  491impl ScrollbarMarkerState {
  492    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  493        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  494    }
  495}
  496
  497#[derive(Clone, Debug)]
  498struct RunnableTasks {
  499    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  500    offset: MultiBufferOffset,
  501    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  502    column: u32,
  503    // Values of all named captures, including those starting with '_'
  504    extra_variables: HashMap<String, String>,
  505    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  506    context_range: Range<BufferOffset>,
  507}
  508
  509impl RunnableTasks {
  510    fn resolve<'a>(
  511        &'a self,
  512        cx: &'a task::TaskContext,
  513    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  514        self.templates.iter().filter_map(|(kind, template)| {
  515            template
  516                .resolve_task(&kind.to_id_base(), cx)
  517                .map(|task| (kind.clone(), task))
  518        })
  519    }
  520}
  521
  522#[derive(Clone)]
  523struct ResolvedTasks {
  524    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  525    position: Anchor,
  526}
  527#[derive(Copy, Clone, Debug)]
  528struct MultiBufferOffset(usize);
  529#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  530struct BufferOffset(usize);
  531
  532// Addons allow storing per-editor state in other crates (e.g. Vim)
  533pub trait Addon: 'static {
  534    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  535
  536    fn to_any(&self) -> &dyn std::any::Any;
  537}
  538
  539/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  540///
  541/// See the [module level documentation](self) for more information.
  542pub struct Editor {
  543    focus_handle: FocusHandle,
  544    last_focused_descendant: Option<WeakFocusHandle>,
  545    /// The text buffer being edited
  546    buffer: Model<MultiBuffer>,
  547    /// Map of how text in the buffer should be displayed.
  548    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  549    pub display_map: Model<DisplayMap>,
  550    pub selections: SelectionsCollection,
  551    pub scroll_manager: ScrollManager,
  552    /// When inline assist editors are linked, they all render cursors because
  553    /// typing enters text into each of them, even the ones that aren't focused.
  554    pub(crate) show_cursor_when_unfocused: bool,
  555    columnar_selection_tail: Option<Anchor>,
  556    add_selections_state: Option<AddSelectionsState>,
  557    select_next_state: Option<SelectNextState>,
  558    select_prev_state: Option<SelectNextState>,
  559    selection_history: SelectionHistory,
  560    autoclose_regions: Vec<AutocloseRegion>,
  561    snippet_stack: InvalidationStack<SnippetState>,
  562    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  563    ime_transaction: Option<TransactionId>,
  564    active_diagnostics: Option<ActiveDiagnosticGroup>,
  565    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  566
  567    project: Option<Model<Project>>,
  568    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  569    completion_provider: Option<Box<dyn CompletionProvider>>,
  570    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  571    blink_manager: Model<BlinkManager>,
  572    show_cursor_names: bool,
  573    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  574    pub show_local_selections: bool,
  575    mode: EditorMode,
  576    show_breadcrumbs: bool,
  577    show_gutter: bool,
  578    show_line_numbers: Option<bool>,
  579    use_relative_line_numbers: Option<bool>,
  580    show_git_diff_gutter: Option<bool>,
  581    show_code_actions: Option<bool>,
  582    show_runnables: Option<bool>,
  583    show_wrap_guides: Option<bool>,
  584    show_indent_guides: Option<bool>,
  585    placeholder_text: Option<Arc<str>>,
  586    highlight_order: usize,
  587    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  588    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  589    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  590    scrollbar_marker_state: ScrollbarMarkerState,
  591    active_indent_guides_state: ActiveIndentGuidesState,
  592    nav_history: Option<ItemNavHistory>,
  593    context_menu: RwLock<Option<ContextMenu>>,
  594    mouse_context_menu: Option<MouseContextMenu>,
  595    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  596    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  597    signature_help_state: SignatureHelpState,
  598    auto_signature_help: Option<bool>,
  599    find_all_references_task_sources: Vec<Anchor>,
  600    next_completion_id: CompletionId,
  601    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  602    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  603    code_actions_task: Option<Task<Result<()>>>,
  604    document_highlights_task: Option<Task<()>>,
  605    linked_editing_range_task: Option<Task<Option<()>>>,
  606    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  607    pending_rename: Option<RenameState>,
  608    searchable: bool,
  609    cursor_shape: CursorShape,
  610    current_line_highlight: Option<CurrentLineHighlight>,
  611    collapse_matches: bool,
  612    autoindent_mode: Option<AutoindentMode>,
  613    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  614    input_enabled: bool,
  615    use_modal_editing: bool,
  616    read_only: bool,
  617    leader_peer_id: Option<PeerId>,
  618    remote_id: Option<ViewId>,
  619    hover_state: HoverState,
  620    gutter_hovered: bool,
  621    hovered_link_state: Option<HoveredLinkState>,
  622    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  623    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  624    active_inline_completion: Option<CompletionState>,
  625    // enable_inline_completions is a switch that Vim can use to disable
  626    // inline completions based on its mode.
  627    enable_inline_completions: bool,
  628    show_inline_completions_override: Option<bool>,
  629    inlay_hint_cache: InlayHintCache,
  630    expanded_hunks: ExpandedHunks,
  631    next_inlay_id: usize,
  632    _subscriptions: Vec<Subscription>,
  633    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  634    gutter_dimensions: GutterDimensions,
  635    style: Option<EditorStyle>,
  636    text_style_refinement: Option<TextStyleRefinement>,
  637    next_editor_action_id: EditorActionId,
  638    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  639    use_autoclose: bool,
  640    use_auto_surround: bool,
  641    auto_replace_emoji_shortcode: bool,
  642    show_git_blame_gutter: bool,
  643    show_git_blame_inline: bool,
  644    show_git_blame_inline_delay_task: Option<Task<()>>,
  645    git_blame_inline_enabled: bool,
  646    serialize_dirty_buffers: bool,
  647    show_selection_menu: Option<bool>,
  648    blame: Option<Model<GitBlame>>,
  649    blame_subscription: Option<Subscription>,
  650    custom_context_menu: Option<
  651        Box<
  652            dyn 'static
  653                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  654        >,
  655    >,
  656    last_bounds: Option<Bounds<Pixels>>,
  657    expect_bounds_change: Option<Bounds<Pixels>>,
  658    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  659    tasks_update_task: Option<Task<()>>,
  660    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  661    breadcrumb_header: Option<String>,
  662    focused_block: Option<FocusedBlock>,
  663    next_scroll_position: NextScrollCursorCenterTopBottom,
  664    addons: HashMap<TypeId, Box<dyn Addon>>,
  665    _scroll_cursor_center_top_bottom_task: Task<()>,
  666}
  667
  668#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  669enum NextScrollCursorCenterTopBottom {
  670    #[default]
  671    Center,
  672    Top,
  673    Bottom,
  674}
  675
  676impl NextScrollCursorCenterTopBottom {
  677    fn next(&self) -> Self {
  678        match self {
  679            Self::Center => Self::Top,
  680            Self::Top => Self::Bottom,
  681            Self::Bottom => Self::Center,
  682        }
  683    }
  684}
  685
  686#[derive(Clone)]
  687pub struct EditorSnapshot {
  688    pub mode: EditorMode,
  689    show_gutter: bool,
  690    show_line_numbers: Option<bool>,
  691    show_git_diff_gutter: Option<bool>,
  692    show_code_actions: Option<bool>,
  693    show_runnables: Option<bool>,
  694    git_blame_gutter_max_author_length: Option<usize>,
  695    pub display_snapshot: DisplaySnapshot,
  696    pub placeholder_text: Option<Arc<str>>,
  697    is_focused: bool,
  698    scroll_anchor: ScrollAnchor,
  699    ongoing_scroll: OngoingScroll,
  700    current_line_highlight: CurrentLineHighlight,
  701    gutter_hovered: bool,
  702}
  703
  704const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  705
  706#[derive(Default, Debug, Clone, Copy)]
  707pub struct GutterDimensions {
  708    pub left_padding: Pixels,
  709    pub right_padding: Pixels,
  710    pub width: Pixels,
  711    pub margin: Pixels,
  712    pub git_blame_entries_width: Option<Pixels>,
  713}
  714
  715impl GutterDimensions {
  716    /// The full width of the space taken up by the gutter.
  717    pub fn full_width(&self) -> Pixels {
  718        self.margin + self.width
  719    }
  720
  721    /// The width of the space reserved for the fold indicators,
  722    /// use alongside 'justify_end' and `gutter_width` to
  723    /// right align content with the line numbers
  724    pub fn fold_area_width(&self) -> Pixels {
  725        self.margin + self.right_padding
  726    }
  727}
  728
  729#[derive(Debug)]
  730pub struct RemoteSelection {
  731    pub replica_id: ReplicaId,
  732    pub selection: Selection<Anchor>,
  733    pub cursor_shape: CursorShape,
  734    pub peer_id: PeerId,
  735    pub line_mode: bool,
  736    pub participant_index: Option<ParticipantIndex>,
  737    pub user_name: Option<SharedString>,
  738}
  739
  740#[derive(Clone, Debug)]
  741struct SelectionHistoryEntry {
  742    selections: Arc<[Selection<Anchor>]>,
  743    select_next_state: Option<SelectNextState>,
  744    select_prev_state: Option<SelectNextState>,
  745    add_selections_state: Option<AddSelectionsState>,
  746}
  747
  748enum SelectionHistoryMode {
  749    Normal,
  750    Undoing,
  751    Redoing,
  752}
  753
  754#[derive(Clone, PartialEq, Eq, Hash)]
  755struct HoveredCursor {
  756    replica_id: u16,
  757    selection_id: usize,
  758}
  759
  760impl Default for SelectionHistoryMode {
  761    fn default() -> Self {
  762        Self::Normal
  763    }
  764}
  765
  766#[derive(Default)]
  767struct SelectionHistory {
  768    #[allow(clippy::type_complexity)]
  769    selections_by_transaction:
  770        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  771    mode: SelectionHistoryMode,
  772    undo_stack: VecDeque<SelectionHistoryEntry>,
  773    redo_stack: VecDeque<SelectionHistoryEntry>,
  774}
  775
  776impl SelectionHistory {
  777    fn insert_transaction(
  778        &mut self,
  779        transaction_id: TransactionId,
  780        selections: Arc<[Selection<Anchor>]>,
  781    ) {
  782        self.selections_by_transaction
  783            .insert(transaction_id, (selections, None));
  784    }
  785
  786    #[allow(clippy::type_complexity)]
  787    fn transaction(
  788        &self,
  789        transaction_id: TransactionId,
  790    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  791        self.selections_by_transaction.get(&transaction_id)
  792    }
  793
  794    #[allow(clippy::type_complexity)]
  795    fn transaction_mut(
  796        &mut self,
  797        transaction_id: TransactionId,
  798    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  799        self.selections_by_transaction.get_mut(&transaction_id)
  800    }
  801
  802    fn push(&mut self, entry: SelectionHistoryEntry) {
  803        if !entry.selections.is_empty() {
  804            match self.mode {
  805                SelectionHistoryMode::Normal => {
  806                    self.push_undo(entry);
  807                    self.redo_stack.clear();
  808                }
  809                SelectionHistoryMode::Undoing => self.push_redo(entry),
  810                SelectionHistoryMode::Redoing => self.push_undo(entry),
  811            }
  812        }
  813    }
  814
  815    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  816        if self
  817            .undo_stack
  818            .back()
  819            .map_or(true, |e| e.selections != entry.selections)
  820        {
  821            self.undo_stack.push_back(entry);
  822            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  823                self.undo_stack.pop_front();
  824            }
  825        }
  826    }
  827
  828    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  829        if self
  830            .redo_stack
  831            .back()
  832            .map_or(true, |e| e.selections != entry.selections)
  833        {
  834            self.redo_stack.push_back(entry);
  835            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  836                self.redo_stack.pop_front();
  837            }
  838        }
  839    }
  840}
  841
  842struct RowHighlight {
  843    index: usize,
  844    range: Range<Anchor>,
  845    color: Hsla,
  846    should_autoscroll: bool,
  847}
  848
  849#[derive(Clone, Debug)]
  850struct AddSelectionsState {
  851    above: bool,
  852    stack: Vec<usize>,
  853}
  854
  855#[derive(Clone)]
  856struct SelectNextState {
  857    query: AhoCorasick,
  858    wordwise: bool,
  859    done: bool,
  860}
  861
  862impl std::fmt::Debug for SelectNextState {
  863    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  864        f.debug_struct(std::any::type_name::<Self>())
  865            .field("wordwise", &self.wordwise)
  866            .field("done", &self.done)
  867            .finish()
  868    }
  869}
  870
  871#[derive(Debug)]
  872struct AutocloseRegion {
  873    selection_id: usize,
  874    range: Range<Anchor>,
  875    pair: BracketPair,
  876}
  877
  878#[derive(Debug)]
  879struct SnippetState {
  880    ranges: Vec<Vec<Range<Anchor>>>,
  881    active_index: usize,
  882}
  883
  884#[doc(hidden)]
  885pub struct RenameState {
  886    pub range: Range<Anchor>,
  887    pub old_name: Arc<str>,
  888    pub editor: View<Editor>,
  889    block_id: CustomBlockId,
  890}
  891
  892struct InvalidationStack<T>(Vec<T>);
  893
  894struct RegisteredInlineCompletionProvider {
  895    provider: Arc<dyn InlineCompletionProviderHandle>,
  896    _subscription: Subscription,
  897}
  898
  899enum ContextMenu {
  900    Completions(CompletionsMenu),
  901    CodeActions(CodeActionsMenu),
  902}
  903
  904impl ContextMenu {
  905    fn select_first(
  906        &mut self,
  907        provider: Option<&dyn CompletionProvider>,
  908        cx: &mut ViewContext<Editor>,
  909    ) -> bool {
  910        if self.visible() {
  911            match self {
  912                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  913                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  914            }
  915            true
  916        } else {
  917            false
  918        }
  919    }
  920
  921    fn select_prev(
  922        &mut self,
  923        provider: Option<&dyn CompletionProvider>,
  924        cx: &mut ViewContext<Editor>,
  925    ) -> bool {
  926        if self.visible() {
  927            match self {
  928                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  929                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  930            }
  931            true
  932        } else {
  933            false
  934        }
  935    }
  936
  937    fn select_next(
  938        &mut self,
  939        provider: Option<&dyn CompletionProvider>,
  940        cx: &mut ViewContext<Editor>,
  941    ) -> bool {
  942        if self.visible() {
  943            match self {
  944                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  945                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  946            }
  947            true
  948        } else {
  949            false
  950        }
  951    }
  952
  953    fn select_last(
  954        &mut self,
  955        provider: Option<&dyn CompletionProvider>,
  956        cx: &mut ViewContext<Editor>,
  957    ) -> bool {
  958        if self.visible() {
  959            match self {
  960                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  961                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  962            }
  963            true
  964        } else {
  965            false
  966        }
  967    }
  968
  969    fn visible(&self) -> bool {
  970        match self {
  971            ContextMenu::Completions(menu) => menu.visible(),
  972            ContextMenu::CodeActions(menu) => menu.visible(),
  973        }
  974    }
  975
  976    fn render(
  977        &self,
  978        cursor_position: DisplayPoint,
  979        style: &EditorStyle,
  980        max_height: Pixels,
  981        workspace: Option<WeakView<Workspace>>,
  982        cx: &mut ViewContext<Editor>,
  983    ) -> (ContextMenuOrigin, AnyElement) {
  984        match self {
  985            ContextMenu::Completions(menu) => (
  986                ContextMenuOrigin::EditorPoint(cursor_position),
  987                menu.render(style, max_height, workspace, cx),
  988            ),
  989            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  990        }
  991    }
  992}
  993
  994enum ContextMenuOrigin {
  995    EditorPoint(DisplayPoint),
  996    GutterIndicator(DisplayRow),
  997}
  998
  999#[derive(Clone)]
 1000struct CompletionsMenu {
 1001    id: CompletionId,
 1002    sort_completions: bool,
 1003    initial_position: Anchor,
 1004    buffer: Model<Buffer>,
 1005    completions: Arc<RwLock<Box<[Completion]>>>,
 1006    match_candidates: Arc<[StringMatchCandidate]>,
 1007    matches: Arc<[StringMatch]>,
 1008    selected_item: usize,
 1009    scroll_handle: UniformListScrollHandle,
 1010    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
 1011}
 1012
 1013impl CompletionsMenu {
 1014    fn select_first(
 1015        &mut self,
 1016        provider: Option<&dyn CompletionProvider>,
 1017        cx: &mut ViewContext<Editor>,
 1018    ) {
 1019        self.selected_item = 0;
 1020        self.scroll_handle.scroll_to_item(self.selected_item);
 1021        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1022        cx.notify();
 1023    }
 1024
 1025    fn select_prev(
 1026        &mut self,
 1027        provider: Option<&dyn CompletionProvider>,
 1028        cx: &mut ViewContext<Editor>,
 1029    ) {
 1030        if self.selected_item > 0 {
 1031            self.selected_item -= 1;
 1032        } else {
 1033            self.selected_item = self.matches.len() - 1;
 1034        }
 1035        self.scroll_handle.scroll_to_item(self.selected_item);
 1036        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1037        cx.notify();
 1038    }
 1039
 1040    fn select_next(
 1041        &mut self,
 1042        provider: Option<&dyn CompletionProvider>,
 1043        cx: &mut ViewContext<Editor>,
 1044    ) {
 1045        if self.selected_item + 1 < self.matches.len() {
 1046            self.selected_item += 1;
 1047        } else {
 1048            self.selected_item = 0;
 1049        }
 1050        self.scroll_handle.scroll_to_item(self.selected_item);
 1051        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1052        cx.notify();
 1053    }
 1054
 1055    fn select_last(
 1056        &mut self,
 1057        provider: Option<&dyn CompletionProvider>,
 1058        cx: &mut ViewContext<Editor>,
 1059    ) {
 1060        self.selected_item = self.matches.len() - 1;
 1061        self.scroll_handle.scroll_to_item(self.selected_item);
 1062        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1063        cx.notify();
 1064    }
 1065
 1066    fn pre_resolve_completion_documentation(
 1067        buffer: Model<Buffer>,
 1068        completions: Arc<RwLock<Box<[Completion]>>>,
 1069        matches: Arc<[StringMatch]>,
 1070        editor: &Editor,
 1071        cx: &mut ViewContext<Editor>,
 1072    ) -> Task<()> {
 1073        let settings = EditorSettings::get_global(cx);
 1074        if !settings.show_completion_documentation {
 1075            return Task::ready(());
 1076        }
 1077
 1078        let Some(provider) = editor.completion_provider.as_ref() else {
 1079            return Task::ready(());
 1080        };
 1081
 1082        let resolve_task = provider.resolve_completions(
 1083            buffer,
 1084            matches.iter().map(|m| m.candidate_id).collect(),
 1085            completions.clone(),
 1086            cx,
 1087        );
 1088
 1089        cx.spawn(move |this, mut cx| async move {
 1090            if let Some(true) = resolve_task.await.log_err() {
 1091                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1092            }
 1093        })
 1094    }
 1095
 1096    fn attempt_resolve_selected_completion_documentation(
 1097        &mut self,
 1098        provider: Option<&dyn CompletionProvider>,
 1099        cx: &mut ViewContext<Editor>,
 1100    ) {
 1101        let settings = EditorSettings::get_global(cx);
 1102        if !settings.show_completion_documentation {
 1103            return;
 1104        }
 1105
 1106        let completion_index = self.matches[self.selected_item].candidate_id;
 1107        let Some(provider) = provider else {
 1108            return;
 1109        };
 1110
 1111        let resolve_task = provider.resolve_completions(
 1112            self.buffer.clone(),
 1113            vec![completion_index],
 1114            self.completions.clone(),
 1115            cx,
 1116        );
 1117
 1118        let delay_ms =
 1119            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1120        let delay = Duration::from_millis(delay_ms);
 1121
 1122        self.selected_completion_documentation_resolve_debounce
 1123            .lock()
 1124            .fire_new(delay, cx, |_, cx| {
 1125                cx.spawn(move |this, mut cx| async move {
 1126                    if let Some(true) = resolve_task.await.log_err() {
 1127                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1128                    }
 1129                })
 1130            });
 1131    }
 1132
 1133    fn visible(&self) -> bool {
 1134        !self.matches.is_empty()
 1135    }
 1136
 1137    fn render(
 1138        &self,
 1139        style: &EditorStyle,
 1140        max_height: Pixels,
 1141        workspace: Option<WeakView<Workspace>>,
 1142        cx: &mut ViewContext<Editor>,
 1143    ) -> AnyElement {
 1144        let settings = EditorSettings::get_global(cx);
 1145        let show_completion_documentation = settings.show_completion_documentation;
 1146
 1147        let widest_completion_ix = self
 1148            .matches
 1149            .iter()
 1150            .enumerate()
 1151            .max_by_key(|(_, mat)| {
 1152                let completions = self.completions.read();
 1153                let completion = &completions[mat.candidate_id];
 1154                let documentation = &completion.documentation;
 1155
 1156                let mut len = completion.label.text.chars().count();
 1157                if let Some(Documentation::SingleLine(text)) = documentation {
 1158                    if show_completion_documentation {
 1159                        len += text.chars().count();
 1160                    }
 1161                }
 1162
 1163                len
 1164            })
 1165            .map(|(ix, _)| ix);
 1166
 1167        let completions = self.completions.clone();
 1168        let matches = self.matches.clone();
 1169        let selected_item = self.selected_item;
 1170        let style = style.clone();
 1171
 1172        let multiline_docs = if show_completion_documentation {
 1173            let mat = &self.matches[selected_item];
 1174            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1175                Some(Documentation::MultiLinePlainText(text)) => {
 1176                    Some(div().child(SharedString::from(text.clone())))
 1177                }
 1178                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1179                    Some(div().child(render_parsed_markdown(
 1180                        "completions_markdown",
 1181                        parsed,
 1182                        &style,
 1183                        workspace,
 1184                        cx,
 1185                    )))
 1186                }
 1187                _ => None,
 1188            };
 1189            multiline_docs.map(|div| {
 1190                div.id("multiline_docs")
 1191                    .max_h(max_height)
 1192                    .flex_1()
 1193                    .px_1p5()
 1194                    .py_1()
 1195                    .min_w(px(260.))
 1196                    .max_w(px(640.))
 1197                    .w(px(500.))
 1198                    .overflow_y_scroll()
 1199                    .occlude()
 1200            })
 1201        } else {
 1202            None
 1203        };
 1204
 1205        let list = uniform_list(
 1206            cx.view().clone(),
 1207            "completions",
 1208            matches.len(),
 1209            move |_editor, range, cx| {
 1210                let start_ix = range.start;
 1211                let completions_guard = completions.read();
 1212
 1213                matches[range]
 1214                    .iter()
 1215                    .enumerate()
 1216                    .map(|(ix, mat)| {
 1217                        let item_ix = start_ix + ix;
 1218                        let candidate_id = mat.candidate_id;
 1219                        let completion = &completions_guard[candidate_id];
 1220
 1221                        let documentation = if show_completion_documentation {
 1222                            &completion.documentation
 1223                        } else {
 1224                            &None
 1225                        };
 1226
 1227                        let highlights = gpui::combine_highlights(
 1228                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1229                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1230                                |(range, mut highlight)| {
 1231                                    // Ignore font weight for syntax highlighting, as we'll use it
 1232                                    // for fuzzy matches.
 1233                                    highlight.font_weight = None;
 1234
 1235                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1236                                        highlight.strikethrough = Some(StrikethroughStyle {
 1237                                            thickness: 1.0.into(),
 1238                                            ..Default::default()
 1239                                        });
 1240                                        highlight.color = Some(cx.theme().colors().text_muted);
 1241                                    }
 1242
 1243                                    (range, highlight)
 1244                                },
 1245                            ),
 1246                        );
 1247                        let completion_label = StyledText::new(completion.label.text.clone())
 1248                            .with_highlights(&style.text, highlights);
 1249                        let documentation_label =
 1250                            if let Some(Documentation::SingleLine(text)) = documentation {
 1251                                if text.trim().is_empty() {
 1252                                    None
 1253                                } else {
 1254                                    Some(
 1255                                        Label::new(text.clone())
 1256                                            .ml_4()
 1257                                            .size(LabelSize::Small)
 1258                                            .color(Color::Muted),
 1259                                    )
 1260                                }
 1261                            } else {
 1262                                None
 1263                            };
 1264
 1265                        let color_swatch = completion
 1266                            .color()
 1267                            .map(|color| div().size_4().bg(color).rounded_sm());
 1268
 1269                        div().min_w(px(220.)).max_w(px(540.)).child(
 1270                            ListItem::new(mat.candidate_id)
 1271                                .inset(true)
 1272                                .selected(item_ix == selected_item)
 1273                                .on_click(cx.listener(move |editor, _event, cx| {
 1274                                    cx.stop_propagation();
 1275                                    if let Some(task) = editor.confirm_completion(
 1276                                        &ConfirmCompletion {
 1277                                            item_ix: Some(item_ix),
 1278                                        },
 1279                                        cx,
 1280                                    ) {
 1281                                        task.detach_and_log_err(cx)
 1282                                    }
 1283                                }))
 1284                                .start_slot::<Div>(color_swatch)
 1285                                .child(h_flex().overflow_hidden().child(completion_label))
 1286                                .end_slot::<Label>(documentation_label),
 1287                        )
 1288                    })
 1289                    .collect()
 1290            },
 1291        )
 1292        .occlude()
 1293        .max_h(max_height)
 1294        .track_scroll(self.scroll_handle.clone())
 1295        .with_width_from_item(widest_completion_ix)
 1296        .with_sizing_behavior(ListSizingBehavior::Infer);
 1297
 1298        Popover::new()
 1299            .child(list)
 1300            .when_some(multiline_docs, |popover, multiline_docs| {
 1301                popover.aside(multiline_docs)
 1302            })
 1303            .into_any_element()
 1304    }
 1305
 1306    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1307        let mut matches = if let Some(query) = query {
 1308            fuzzy::match_strings(
 1309                &self.match_candidates,
 1310                query,
 1311                query.chars().any(|c| c.is_uppercase()),
 1312                100,
 1313                &Default::default(),
 1314                executor,
 1315            )
 1316            .await
 1317        } else {
 1318            self.match_candidates
 1319                .iter()
 1320                .enumerate()
 1321                .map(|(candidate_id, candidate)| StringMatch {
 1322                    candidate_id,
 1323                    score: Default::default(),
 1324                    positions: Default::default(),
 1325                    string: candidate.string.clone(),
 1326                })
 1327                .collect()
 1328        };
 1329
 1330        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1331        if let Some(query) = query {
 1332            if let Some(query_start) = query.chars().next() {
 1333                matches.retain(|string_match| {
 1334                    split_words(&string_match.string).any(|word| {
 1335                        // Check that the first codepoint of the word as lowercase matches the first
 1336                        // codepoint of the query as lowercase
 1337                        word.chars()
 1338                            .flat_map(|codepoint| codepoint.to_lowercase())
 1339                            .zip(query_start.to_lowercase())
 1340                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1341                    })
 1342                });
 1343            }
 1344        }
 1345
 1346        let completions = self.completions.read();
 1347        if self.sort_completions {
 1348            matches.sort_unstable_by_key(|mat| {
 1349                // We do want to strike a balance here between what the language server tells us
 1350                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1351                // `Creat` and there is a local variable called `CreateComponent`).
 1352                // So what we do is: we bucket all matches into two buckets
 1353                // - Strong matches
 1354                // - Weak matches
 1355                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1356                // and the Weak matches are the rest.
 1357                //
 1358                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1359                // matches, we prefer language-server sort_text first.
 1360                //
 1361                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1362                // Rest of the matches(weak) can be sorted as language-server expects.
 1363
 1364                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1365                enum MatchScore<'a> {
 1366                    Strong {
 1367                        score: Reverse<OrderedFloat<f64>>,
 1368                        sort_text: Option<&'a str>,
 1369                        sort_key: (usize, &'a str),
 1370                    },
 1371                    Weak {
 1372                        sort_text: Option<&'a str>,
 1373                        score: Reverse<OrderedFloat<f64>>,
 1374                        sort_key: (usize, &'a str),
 1375                    },
 1376                }
 1377
 1378                let completion = &completions[mat.candidate_id];
 1379                let sort_key = completion.sort_key();
 1380                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1381                let score = Reverse(OrderedFloat(mat.score));
 1382
 1383                if mat.score >= 0.2 {
 1384                    MatchScore::Strong {
 1385                        score,
 1386                        sort_text,
 1387                        sort_key,
 1388                    }
 1389                } else {
 1390                    MatchScore::Weak {
 1391                        sort_text,
 1392                        score,
 1393                        sort_key,
 1394                    }
 1395                }
 1396            });
 1397        }
 1398
 1399        for mat in &mut matches {
 1400            let completion = &completions[mat.candidate_id];
 1401            mat.string.clone_from(&completion.label.text);
 1402            for position in &mut mat.positions {
 1403                *position += completion.label.filter_range.start;
 1404            }
 1405        }
 1406        drop(completions);
 1407
 1408        self.matches = matches.into();
 1409        self.selected_item = 0;
 1410    }
 1411}
 1412
 1413struct AvailableCodeAction {
 1414    excerpt_id: ExcerptId,
 1415    action: CodeAction,
 1416    provider: Arc<dyn CodeActionProvider>,
 1417}
 1418
 1419#[derive(Clone)]
 1420struct CodeActionContents {
 1421    tasks: Option<Arc<ResolvedTasks>>,
 1422    actions: Option<Arc<[AvailableCodeAction]>>,
 1423}
 1424
 1425impl CodeActionContents {
 1426    fn len(&self) -> usize {
 1427        match (&self.tasks, &self.actions) {
 1428            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1429            (Some(tasks), None) => tasks.templates.len(),
 1430            (None, Some(actions)) => actions.len(),
 1431            (None, None) => 0,
 1432        }
 1433    }
 1434
 1435    fn is_empty(&self) -> bool {
 1436        match (&self.tasks, &self.actions) {
 1437            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1438            (Some(tasks), None) => tasks.templates.is_empty(),
 1439            (None, Some(actions)) => actions.is_empty(),
 1440            (None, None) => true,
 1441        }
 1442    }
 1443
 1444    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1445        self.tasks
 1446            .iter()
 1447            .flat_map(|tasks| {
 1448                tasks
 1449                    .templates
 1450                    .iter()
 1451                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1452            })
 1453            .chain(self.actions.iter().flat_map(|actions| {
 1454                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1455                    excerpt_id: available.excerpt_id,
 1456                    action: available.action.clone(),
 1457                    provider: available.provider.clone(),
 1458                })
 1459            }))
 1460    }
 1461    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1462        match (&self.tasks, &self.actions) {
 1463            (Some(tasks), Some(actions)) => {
 1464                if index < tasks.templates.len() {
 1465                    tasks
 1466                        .templates
 1467                        .get(index)
 1468                        .cloned()
 1469                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1470                } else {
 1471                    actions.get(index - tasks.templates.len()).map(|available| {
 1472                        CodeActionsItem::CodeAction {
 1473                            excerpt_id: available.excerpt_id,
 1474                            action: available.action.clone(),
 1475                            provider: available.provider.clone(),
 1476                        }
 1477                    })
 1478                }
 1479            }
 1480            (Some(tasks), None) => tasks
 1481                .templates
 1482                .get(index)
 1483                .cloned()
 1484                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1485            (None, Some(actions)) => {
 1486                actions
 1487                    .get(index)
 1488                    .map(|available| CodeActionsItem::CodeAction {
 1489                        excerpt_id: available.excerpt_id,
 1490                        action: available.action.clone(),
 1491                        provider: available.provider.clone(),
 1492                    })
 1493            }
 1494            (None, None) => None,
 1495        }
 1496    }
 1497}
 1498
 1499#[allow(clippy::large_enum_variant)]
 1500#[derive(Clone)]
 1501enum CodeActionsItem {
 1502    Task(TaskSourceKind, ResolvedTask),
 1503    CodeAction {
 1504        excerpt_id: ExcerptId,
 1505        action: CodeAction,
 1506        provider: Arc<dyn CodeActionProvider>,
 1507    },
 1508}
 1509
 1510impl CodeActionsItem {
 1511    fn as_task(&self) -> Option<&ResolvedTask> {
 1512        let Self::Task(_, task) = self else {
 1513            return None;
 1514        };
 1515        Some(task)
 1516    }
 1517    fn as_code_action(&self) -> Option<&CodeAction> {
 1518        let Self::CodeAction { action, .. } = self else {
 1519            return None;
 1520        };
 1521        Some(action)
 1522    }
 1523    fn label(&self) -> String {
 1524        match self {
 1525            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1526            Self::Task(_, task) => task.resolved_label.clone(),
 1527        }
 1528    }
 1529}
 1530
 1531struct CodeActionsMenu {
 1532    actions: CodeActionContents,
 1533    buffer: Model<Buffer>,
 1534    selected_item: usize,
 1535    scroll_handle: UniformListScrollHandle,
 1536    deployed_from_indicator: Option<DisplayRow>,
 1537}
 1538
 1539impl CodeActionsMenu {
 1540    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1541        self.selected_item = 0;
 1542        self.scroll_handle.scroll_to_item(self.selected_item);
 1543        cx.notify()
 1544    }
 1545
 1546    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1547        if self.selected_item > 0 {
 1548            self.selected_item -= 1;
 1549        } else {
 1550            self.selected_item = self.actions.len() - 1;
 1551        }
 1552        self.scroll_handle.scroll_to_item(self.selected_item);
 1553        cx.notify();
 1554    }
 1555
 1556    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1557        if self.selected_item + 1 < self.actions.len() {
 1558            self.selected_item += 1;
 1559        } else {
 1560            self.selected_item = 0;
 1561        }
 1562        self.scroll_handle.scroll_to_item(self.selected_item);
 1563        cx.notify();
 1564    }
 1565
 1566    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1567        self.selected_item = self.actions.len() - 1;
 1568        self.scroll_handle.scroll_to_item(self.selected_item);
 1569        cx.notify()
 1570    }
 1571
 1572    fn visible(&self) -> bool {
 1573        !self.actions.is_empty()
 1574    }
 1575
 1576    fn render(
 1577        &self,
 1578        cursor_position: DisplayPoint,
 1579        _style: &EditorStyle,
 1580        max_height: Pixels,
 1581        cx: &mut ViewContext<Editor>,
 1582    ) -> (ContextMenuOrigin, AnyElement) {
 1583        let actions = self.actions.clone();
 1584        let selected_item = self.selected_item;
 1585        let element = uniform_list(
 1586            cx.view().clone(),
 1587            "code_actions_menu",
 1588            self.actions.len(),
 1589            move |_this, range, cx| {
 1590                actions
 1591                    .iter()
 1592                    .skip(range.start)
 1593                    .take(range.end - range.start)
 1594                    .enumerate()
 1595                    .map(|(ix, action)| {
 1596                        let item_ix = range.start + ix;
 1597                        let selected = selected_item == item_ix;
 1598                        let colors = cx.theme().colors();
 1599                        div()
 1600                            .px_1()
 1601                            .rounded_md()
 1602                            .text_color(colors.text)
 1603                            .when(selected, |style| {
 1604                                style
 1605                                    .bg(colors.element_active)
 1606                                    .text_color(colors.text_accent)
 1607                            })
 1608                            .hover(|style| {
 1609                                style
 1610                                    .bg(colors.element_hover)
 1611                                    .text_color(colors.text_accent)
 1612                            })
 1613                            .whitespace_nowrap()
 1614                            .when_some(action.as_code_action(), |this, action| {
 1615                                this.on_mouse_down(
 1616                                    MouseButton::Left,
 1617                                    cx.listener(move |editor, _, cx| {
 1618                                        cx.stop_propagation();
 1619                                        if let Some(task) = editor.confirm_code_action(
 1620                                            &ConfirmCodeAction {
 1621                                                item_ix: Some(item_ix),
 1622                                            },
 1623                                            cx,
 1624                                        ) {
 1625                                            task.detach_and_log_err(cx)
 1626                                        }
 1627                                    }),
 1628                                )
 1629                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1630                                .child(SharedString::from(action.lsp_action.title.clone()))
 1631                            })
 1632                            .when_some(action.as_task(), |this, task| {
 1633                                this.on_mouse_down(
 1634                                    MouseButton::Left,
 1635                                    cx.listener(move |editor, _, cx| {
 1636                                        cx.stop_propagation();
 1637                                        if let Some(task) = editor.confirm_code_action(
 1638                                            &ConfirmCodeAction {
 1639                                                item_ix: Some(item_ix),
 1640                                            },
 1641                                            cx,
 1642                                        ) {
 1643                                            task.detach_and_log_err(cx)
 1644                                        }
 1645                                    }),
 1646                                )
 1647                                .child(SharedString::from(task.resolved_label.clone()))
 1648                            })
 1649                    })
 1650                    .collect()
 1651            },
 1652        )
 1653        .elevation_1(cx)
 1654        .p_1()
 1655        .max_h(max_height)
 1656        .occlude()
 1657        .track_scroll(self.scroll_handle.clone())
 1658        .with_width_from_item(
 1659            self.actions
 1660                .iter()
 1661                .enumerate()
 1662                .max_by_key(|(_, action)| match action {
 1663                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1664                    CodeActionsItem::CodeAction { action, .. } => {
 1665                        action.lsp_action.title.chars().count()
 1666                    }
 1667                })
 1668                .map(|(ix, _)| ix),
 1669        )
 1670        .with_sizing_behavior(ListSizingBehavior::Infer)
 1671        .into_any_element();
 1672
 1673        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1674            ContextMenuOrigin::GutterIndicator(row)
 1675        } else {
 1676            ContextMenuOrigin::EditorPoint(cursor_position)
 1677        };
 1678
 1679        (cursor_position, element)
 1680    }
 1681}
 1682
 1683#[derive(Debug)]
 1684struct ActiveDiagnosticGroup {
 1685    primary_range: Range<Anchor>,
 1686    primary_message: String,
 1687    group_id: usize,
 1688    blocks: HashMap<CustomBlockId, Diagnostic>,
 1689    is_valid: bool,
 1690}
 1691
 1692#[derive(Serialize, Deserialize, Clone, Debug)]
 1693pub struct ClipboardSelection {
 1694    pub len: usize,
 1695    pub is_entire_line: bool,
 1696    pub first_line_indent: u32,
 1697}
 1698
 1699#[derive(Debug)]
 1700pub(crate) struct NavigationData {
 1701    cursor_anchor: Anchor,
 1702    cursor_position: Point,
 1703    scroll_anchor: ScrollAnchor,
 1704    scroll_top_row: u32,
 1705}
 1706
 1707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1708pub enum GotoDefinitionKind {
 1709    Symbol,
 1710    Declaration,
 1711    Type,
 1712    Implementation,
 1713}
 1714
 1715#[derive(Debug, Clone)]
 1716enum InlayHintRefreshReason {
 1717    Toggle(bool),
 1718    SettingsChange(InlayHintSettings),
 1719    NewLinesShown,
 1720    BufferEdited(HashSet<Arc<Language>>),
 1721    RefreshRequested,
 1722    ExcerptsRemoved(Vec<ExcerptId>),
 1723}
 1724
 1725impl InlayHintRefreshReason {
 1726    fn description(&self) -> &'static str {
 1727        match self {
 1728            Self::Toggle(_) => "toggle",
 1729            Self::SettingsChange(_) => "settings change",
 1730            Self::NewLinesShown => "new lines shown",
 1731            Self::BufferEdited(_) => "buffer edited",
 1732            Self::RefreshRequested => "refresh requested",
 1733            Self::ExcerptsRemoved(_) => "excerpts removed",
 1734        }
 1735    }
 1736}
 1737
 1738pub(crate) struct FocusedBlock {
 1739    id: BlockId,
 1740    focus_handle: WeakFocusHandle,
 1741}
 1742
 1743impl Editor {
 1744    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1745        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1746        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1747        Self::new(
 1748            EditorMode::SingleLine { auto_width: false },
 1749            buffer,
 1750            None,
 1751            false,
 1752            cx,
 1753        )
 1754    }
 1755
 1756    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1757        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1758        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1759        Self::new(EditorMode::Full, buffer, None, false, cx)
 1760    }
 1761
 1762    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1763        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1764        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1765        Self::new(
 1766            EditorMode::SingleLine { auto_width: true },
 1767            buffer,
 1768            None,
 1769            false,
 1770            cx,
 1771        )
 1772    }
 1773
 1774    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1775        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1776        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1777        Self::new(
 1778            EditorMode::AutoHeight { max_lines },
 1779            buffer,
 1780            None,
 1781            false,
 1782            cx,
 1783        )
 1784    }
 1785
 1786    pub fn for_buffer(
 1787        buffer: Model<Buffer>,
 1788        project: Option<Model<Project>>,
 1789        cx: &mut ViewContext<Self>,
 1790    ) -> Self {
 1791        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1792        Self::new(EditorMode::Full, buffer, project, false, cx)
 1793    }
 1794
 1795    pub fn for_multibuffer(
 1796        buffer: Model<MultiBuffer>,
 1797        project: Option<Model<Project>>,
 1798        show_excerpt_controls: bool,
 1799        cx: &mut ViewContext<Self>,
 1800    ) -> Self {
 1801        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1802    }
 1803
 1804    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1805        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1806        let mut clone = Self::new(
 1807            self.mode,
 1808            self.buffer.clone(),
 1809            self.project.clone(),
 1810            show_excerpt_controls,
 1811            cx,
 1812        );
 1813        self.display_map.update(cx, |display_map, cx| {
 1814            let snapshot = display_map.snapshot(cx);
 1815            clone.display_map.update(cx, |display_map, cx| {
 1816                display_map.set_state(&snapshot, cx);
 1817            });
 1818        });
 1819        clone.selections.clone_state(&self.selections);
 1820        clone.scroll_manager.clone_state(&self.scroll_manager);
 1821        clone.searchable = self.searchable;
 1822        clone
 1823    }
 1824
 1825    pub fn new(
 1826        mode: EditorMode,
 1827        buffer: Model<MultiBuffer>,
 1828        project: Option<Model<Project>>,
 1829        show_excerpt_controls: bool,
 1830        cx: &mut ViewContext<Self>,
 1831    ) -> Self {
 1832        let style = cx.text_style();
 1833        let font_size = style.font_size.to_pixels(cx.rem_size());
 1834        let editor = cx.view().downgrade();
 1835        let fold_placeholder = FoldPlaceholder {
 1836            constrain_width: true,
 1837            render: Arc::new(move |fold_id, fold_range, cx| {
 1838                let editor = editor.clone();
 1839                div()
 1840                    .id(fold_id)
 1841                    .bg(cx.theme().colors().ghost_element_background)
 1842                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1843                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1844                    .rounded_sm()
 1845                    .size_full()
 1846                    .cursor_pointer()
 1847                    .child("")
 1848                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1849                    .on_click(move |_, cx| {
 1850                        editor
 1851                            .update(cx, |editor, cx| {
 1852                                editor.unfold_ranges(
 1853                                    [fold_range.start..fold_range.end],
 1854                                    true,
 1855                                    false,
 1856                                    cx,
 1857                                );
 1858                                cx.stop_propagation();
 1859                            })
 1860                            .ok();
 1861                    })
 1862                    .into_any()
 1863            }),
 1864            merge_adjacent: true,
 1865        };
 1866        let display_map = cx.new_model(|cx| {
 1867            DisplayMap::new(
 1868                buffer.clone(),
 1869                style.font(),
 1870                font_size,
 1871                None,
 1872                show_excerpt_controls,
 1873                FILE_HEADER_HEIGHT,
 1874                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1875                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1876                fold_placeholder,
 1877                cx,
 1878            )
 1879        });
 1880
 1881        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1882
 1883        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1884
 1885        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1886            .then(|| language_settings::SoftWrap::None);
 1887
 1888        let mut project_subscriptions = Vec::new();
 1889        if mode == EditorMode::Full {
 1890            if let Some(project) = project.as_ref() {
 1891                if buffer.read(cx).is_singleton() {
 1892                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1893                        cx.emit(EditorEvent::TitleChanged);
 1894                    }));
 1895                }
 1896                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1897                    if let project::Event::RefreshInlayHints = event {
 1898                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1899                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1900                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1901                            let focus_handle = editor.focus_handle(cx);
 1902                            if focus_handle.is_focused(cx) {
 1903                                let snapshot = buffer.read(cx).snapshot();
 1904                                for (range, snippet) in snippet_edits {
 1905                                    let editor_range =
 1906                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1907                                    editor
 1908                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1909                                        .ok();
 1910                                }
 1911                            }
 1912                        }
 1913                    }
 1914                }));
 1915                if let Some(task_inventory) = project
 1916                    .read(cx)
 1917                    .task_store()
 1918                    .read(cx)
 1919                    .task_inventory()
 1920                    .cloned()
 1921                {
 1922                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1923                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1924                    }));
 1925                }
 1926            }
 1927        }
 1928
 1929        let inlay_hint_settings = inlay_hint_settings(
 1930            selections.newest_anchor().head(),
 1931            &buffer.read(cx).snapshot(cx),
 1932            cx,
 1933        );
 1934        let focus_handle = cx.focus_handle();
 1935        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1936        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1937            .detach();
 1938        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1939            .detach();
 1940        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1941
 1942        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1943            Some(false)
 1944        } else {
 1945            None
 1946        };
 1947
 1948        let mut code_action_providers = Vec::new();
 1949        if let Some(project) = project.clone() {
 1950            code_action_providers.push(Arc::new(project) as Arc<_>);
 1951        }
 1952
 1953        let mut this = Self {
 1954            focus_handle,
 1955            show_cursor_when_unfocused: false,
 1956            last_focused_descendant: None,
 1957            buffer: buffer.clone(),
 1958            display_map: display_map.clone(),
 1959            selections,
 1960            scroll_manager: ScrollManager::new(cx),
 1961            columnar_selection_tail: None,
 1962            add_selections_state: None,
 1963            select_next_state: None,
 1964            select_prev_state: None,
 1965            selection_history: Default::default(),
 1966            autoclose_regions: Default::default(),
 1967            snippet_stack: Default::default(),
 1968            select_larger_syntax_node_stack: Vec::new(),
 1969            ime_transaction: Default::default(),
 1970            active_diagnostics: None,
 1971            soft_wrap_mode_override,
 1972            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1973            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1974            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1975            project,
 1976            blink_manager: blink_manager.clone(),
 1977            show_local_selections: true,
 1978            mode,
 1979            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1980            show_gutter: mode == EditorMode::Full,
 1981            show_line_numbers: None,
 1982            use_relative_line_numbers: None,
 1983            show_git_diff_gutter: None,
 1984            show_code_actions: None,
 1985            show_runnables: None,
 1986            show_wrap_guides: None,
 1987            show_indent_guides,
 1988            placeholder_text: None,
 1989            highlight_order: 0,
 1990            highlighted_rows: HashMap::default(),
 1991            background_highlights: Default::default(),
 1992            gutter_highlights: TreeMap::default(),
 1993            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1994            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1995            nav_history: None,
 1996            context_menu: RwLock::new(None),
 1997            mouse_context_menu: None,
 1998            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1999            completion_tasks: Default::default(),
 2000            signature_help_state: SignatureHelpState::default(),
 2001            auto_signature_help: None,
 2002            find_all_references_task_sources: Vec::new(),
 2003            next_completion_id: 0,
 2004            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2005            next_inlay_id: 0,
 2006            code_action_providers,
 2007            available_code_actions: Default::default(),
 2008            code_actions_task: Default::default(),
 2009            document_highlights_task: Default::default(),
 2010            linked_editing_range_task: Default::default(),
 2011            pending_rename: Default::default(),
 2012            searchable: true,
 2013            cursor_shape: EditorSettings::get_global(cx)
 2014                .cursor_shape
 2015                .unwrap_or_default(),
 2016            current_line_highlight: None,
 2017            autoindent_mode: Some(AutoindentMode::EachLine),
 2018            collapse_matches: false,
 2019            workspace: None,
 2020            input_enabled: true,
 2021            use_modal_editing: mode == EditorMode::Full,
 2022            read_only: false,
 2023            use_autoclose: true,
 2024            use_auto_surround: true,
 2025            auto_replace_emoji_shortcode: false,
 2026            leader_peer_id: None,
 2027            remote_id: None,
 2028            hover_state: Default::default(),
 2029            hovered_link_state: Default::default(),
 2030            inline_completion_provider: None,
 2031            active_inline_completion: None,
 2032            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2033            expanded_hunks: ExpandedHunks::default(),
 2034            gutter_hovered: false,
 2035            pixel_position_of_newest_cursor: None,
 2036            last_bounds: None,
 2037            expect_bounds_change: None,
 2038            gutter_dimensions: GutterDimensions::default(),
 2039            style: None,
 2040            show_cursor_names: false,
 2041            hovered_cursors: Default::default(),
 2042            next_editor_action_id: EditorActionId::default(),
 2043            editor_actions: Rc::default(),
 2044            show_inline_completions_override: None,
 2045            enable_inline_completions: true,
 2046            custom_context_menu: None,
 2047            show_git_blame_gutter: false,
 2048            show_git_blame_inline: false,
 2049            show_selection_menu: None,
 2050            show_git_blame_inline_delay_task: None,
 2051            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2052            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2053                .session
 2054                .restore_unsaved_buffers,
 2055            blame: None,
 2056            blame_subscription: None,
 2057            tasks: Default::default(),
 2058            _subscriptions: vec![
 2059                cx.observe(&buffer, Self::on_buffer_changed),
 2060                cx.subscribe(&buffer, Self::on_buffer_event),
 2061                cx.observe(&display_map, Self::on_display_map_changed),
 2062                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2063                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2064                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2065                cx.observe_window_activation(|editor, cx| {
 2066                    let active = cx.is_window_active();
 2067                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2068                        if active {
 2069                            blink_manager.enable(cx);
 2070                        } else {
 2071                            blink_manager.disable(cx);
 2072                        }
 2073                    });
 2074                }),
 2075            ],
 2076            tasks_update_task: None,
 2077            linked_edit_ranges: Default::default(),
 2078            previous_search_ranges: None,
 2079            breadcrumb_header: None,
 2080            focused_block: None,
 2081            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2082            addons: HashMap::default(),
 2083            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2084            text_style_refinement: None,
 2085        };
 2086        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2087        this._subscriptions.extend(project_subscriptions);
 2088
 2089        this.end_selection(cx);
 2090        this.scroll_manager.show_scrollbar(cx);
 2091
 2092        if mode == EditorMode::Full {
 2093            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2094            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2095
 2096            if this.git_blame_inline_enabled {
 2097                this.git_blame_inline_enabled = true;
 2098                this.start_git_blame_inline(false, cx);
 2099            }
 2100        }
 2101
 2102        this.report_editor_event("open", None, cx);
 2103        this
 2104    }
 2105
 2106    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2107        self.mouse_context_menu
 2108            .as_ref()
 2109            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2110    }
 2111
 2112    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2113        let mut key_context = KeyContext::new_with_defaults();
 2114        key_context.add("Editor");
 2115        let mode = match self.mode {
 2116            EditorMode::SingleLine { .. } => "single_line",
 2117            EditorMode::AutoHeight { .. } => "auto_height",
 2118            EditorMode::Full => "full",
 2119        };
 2120
 2121        if EditorSettings::jupyter_enabled(cx) {
 2122            key_context.add("jupyter");
 2123        }
 2124
 2125        key_context.set("mode", mode);
 2126        if self.pending_rename.is_some() {
 2127            key_context.add("renaming");
 2128        }
 2129        if self.context_menu_visible() {
 2130            match self.context_menu.read().as_ref() {
 2131                Some(ContextMenu::Completions(_)) => {
 2132                    key_context.add("menu");
 2133                    key_context.add("showing_completions")
 2134                }
 2135                Some(ContextMenu::CodeActions(_)) => {
 2136                    key_context.add("menu");
 2137                    key_context.add("showing_code_actions")
 2138                }
 2139                None => {}
 2140            }
 2141        }
 2142
 2143        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2144        if !self.focus_handle(cx).contains_focused(cx)
 2145            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2146        {
 2147            for addon in self.addons.values() {
 2148                addon.extend_key_context(&mut key_context, cx)
 2149            }
 2150        }
 2151
 2152        if let Some(extension) = self
 2153            .buffer
 2154            .read(cx)
 2155            .as_singleton()
 2156            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2157        {
 2158            key_context.set("extension", extension.to_string());
 2159        }
 2160
 2161        if self.has_active_inline_completion(cx) {
 2162            key_context.add("copilot_suggestion");
 2163            key_context.add("inline_completion");
 2164        }
 2165
 2166        key_context
 2167    }
 2168
 2169    pub fn new_file(
 2170        workspace: &mut Workspace,
 2171        _: &workspace::NewFile,
 2172        cx: &mut ViewContext<Workspace>,
 2173    ) {
 2174        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2175            "Failed to create buffer",
 2176            cx,
 2177            |e, _| match e.error_code() {
 2178                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2179                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2180                e.error_tag("required").unwrap_or("the latest version")
 2181            )),
 2182                _ => None,
 2183            },
 2184        );
 2185    }
 2186
 2187    pub fn new_in_workspace(
 2188        workspace: &mut Workspace,
 2189        cx: &mut ViewContext<Workspace>,
 2190    ) -> Task<Result<View<Editor>>> {
 2191        let project = workspace.project().clone();
 2192        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2193
 2194        cx.spawn(|workspace, mut cx| async move {
 2195            let buffer = create.await?;
 2196            workspace.update(&mut cx, |workspace, cx| {
 2197                let editor =
 2198                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2199                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2200                editor
 2201            })
 2202        })
 2203    }
 2204
 2205    fn new_file_vertical(
 2206        workspace: &mut Workspace,
 2207        _: &workspace::NewFileSplitVertical,
 2208        cx: &mut ViewContext<Workspace>,
 2209    ) {
 2210        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2211    }
 2212
 2213    fn new_file_horizontal(
 2214        workspace: &mut Workspace,
 2215        _: &workspace::NewFileSplitHorizontal,
 2216        cx: &mut ViewContext<Workspace>,
 2217    ) {
 2218        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2219    }
 2220
 2221    fn new_file_in_direction(
 2222        workspace: &mut Workspace,
 2223        direction: SplitDirection,
 2224        cx: &mut ViewContext<Workspace>,
 2225    ) {
 2226        let project = workspace.project().clone();
 2227        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2228
 2229        cx.spawn(|workspace, mut cx| async move {
 2230            let buffer = create.await?;
 2231            workspace.update(&mut cx, move |workspace, cx| {
 2232                workspace.split_item(
 2233                    direction,
 2234                    Box::new(
 2235                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2236                    ),
 2237                    cx,
 2238                )
 2239            })?;
 2240            anyhow::Ok(())
 2241        })
 2242        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2243            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2244                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2245                e.error_tag("required").unwrap_or("the latest version")
 2246            )),
 2247            _ => None,
 2248        });
 2249    }
 2250
 2251    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2252        self.leader_peer_id
 2253    }
 2254
 2255    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2256        &self.buffer
 2257    }
 2258
 2259    pub fn workspace(&self) -> Option<View<Workspace>> {
 2260        self.workspace.as_ref()?.0.upgrade()
 2261    }
 2262
 2263    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2264        self.buffer().read(cx).title(cx)
 2265    }
 2266
 2267    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2268        let git_blame_gutter_max_author_length = self
 2269            .render_git_blame_gutter(cx)
 2270            .then(|| {
 2271                if let Some(blame) = self.blame.as_ref() {
 2272                    let max_author_length =
 2273                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2274                    Some(max_author_length)
 2275                } else {
 2276                    None
 2277                }
 2278            })
 2279            .flatten();
 2280
 2281        EditorSnapshot {
 2282            mode: self.mode,
 2283            show_gutter: self.show_gutter,
 2284            show_line_numbers: self.show_line_numbers,
 2285            show_git_diff_gutter: self.show_git_diff_gutter,
 2286            show_code_actions: self.show_code_actions,
 2287            show_runnables: self.show_runnables,
 2288            git_blame_gutter_max_author_length,
 2289            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2290            scroll_anchor: self.scroll_manager.anchor(),
 2291            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2292            placeholder_text: self.placeholder_text.clone(),
 2293            is_focused: self.focus_handle.is_focused(cx),
 2294            current_line_highlight: self
 2295                .current_line_highlight
 2296                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2297            gutter_hovered: self.gutter_hovered,
 2298        }
 2299    }
 2300
 2301    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2302        self.buffer.read(cx).language_at(point, cx)
 2303    }
 2304
 2305    pub fn file_at<T: ToOffset>(
 2306        &self,
 2307        point: T,
 2308        cx: &AppContext,
 2309    ) -> Option<Arc<dyn language::File>> {
 2310        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2311    }
 2312
 2313    pub fn active_excerpt(
 2314        &self,
 2315        cx: &AppContext,
 2316    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2317        self.buffer
 2318            .read(cx)
 2319            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2320    }
 2321
 2322    pub fn mode(&self) -> EditorMode {
 2323        self.mode
 2324    }
 2325
 2326    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2327        self.collaboration_hub.as_deref()
 2328    }
 2329
 2330    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2331        self.collaboration_hub = Some(hub);
 2332    }
 2333
 2334    pub fn set_custom_context_menu(
 2335        &mut self,
 2336        f: impl 'static
 2337            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2338    ) {
 2339        self.custom_context_menu = Some(Box::new(f))
 2340    }
 2341
 2342    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2343        self.completion_provider = provider;
 2344    }
 2345
 2346    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2347        self.semantics_provider.clone()
 2348    }
 2349
 2350    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2351        self.semantics_provider = provider;
 2352    }
 2353
 2354    pub fn set_inline_completion_provider<T>(
 2355        &mut self,
 2356        provider: Option<Model<T>>,
 2357        cx: &mut ViewContext<Self>,
 2358    ) where
 2359        T: InlineCompletionProvider,
 2360    {
 2361        self.inline_completion_provider =
 2362            provider.map(|provider| RegisteredInlineCompletionProvider {
 2363                _subscription: cx.observe(&provider, |this, _, cx| {
 2364                    if this.focus_handle.is_focused(cx) {
 2365                        this.update_visible_inline_completion(cx);
 2366                    }
 2367                }),
 2368                provider: Arc::new(provider),
 2369            });
 2370        self.refresh_inline_completion(false, false, cx);
 2371    }
 2372
 2373    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2374        self.placeholder_text.as_deref()
 2375    }
 2376
 2377    pub fn set_placeholder_text(
 2378        &mut self,
 2379        placeholder_text: impl Into<Arc<str>>,
 2380        cx: &mut ViewContext<Self>,
 2381    ) {
 2382        let placeholder_text = Some(placeholder_text.into());
 2383        if self.placeholder_text != placeholder_text {
 2384            self.placeholder_text = placeholder_text;
 2385            cx.notify();
 2386        }
 2387    }
 2388
 2389    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2390        self.cursor_shape = cursor_shape;
 2391
 2392        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2393        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2394
 2395        cx.notify();
 2396    }
 2397
 2398    pub fn set_current_line_highlight(
 2399        &mut self,
 2400        current_line_highlight: Option<CurrentLineHighlight>,
 2401    ) {
 2402        self.current_line_highlight = current_line_highlight;
 2403    }
 2404
 2405    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2406        self.collapse_matches = collapse_matches;
 2407    }
 2408
 2409    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2410        if self.collapse_matches {
 2411            return range.start..range.start;
 2412        }
 2413        range.clone()
 2414    }
 2415
 2416    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2417        if self.display_map.read(cx).clip_at_line_ends != clip {
 2418            self.display_map
 2419                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2420        }
 2421    }
 2422
 2423    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2424        self.input_enabled = input_enabled;
 2425    }
 2426
 2427    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2428        self.enable_inline_completions = enabled;
 2429    }
 2430
 2431    pub fn set_autoindent(&mut self, autoindent: bool) {
 2432        if autoindent {
 2433            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2434        } else {
 2435            self.autoindent_mode = None;
 2436        }
 2437    }
 2438
 2439    pub fn read_only(&self, cx: &AppContext) -> bool {
 2440        self.read_only || self.buffer.read(cx).read_only()
 2441    }
 2442
 2443    pub fn set_read_only(&mut self, read_only: bool) {
 2444        self.read_only = read_only;
 2445    }
 2446
 2447    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2448        self.use_autoclose = autoclose;
 2449    }
 2450
 2451    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2452        self.use_auto_surround = auto_surround;
 2453    }
 2454
 2455    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2456        self.auto_replace_emoji_shortcode = auto_replace;
 2457    }
 2458
 2459    pub fn toggle_inline_completions(
 2460        &mut self,
 2461        _: &ToggleInlineCompletions,
 2462        cx: &mut ViewContext<Self>,
 2463    ) {
 2464        if self.show_inline_completions_override.is_some() {
 2465            self.set_show_inline_completions(None, cx);
 2466        } else {
 2467            let cursor = self.selections.newest_anchor().head();
 2468            if let Some((buffer, cursor_buffer_position)) =
 2469                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2470            {
 2471                let show_inline_completions =
 2472                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2473                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2474            }
 2475        }
 2476    }
 2477
 2478    pub fn set_show_inline_completions(
 2479        &mut self,
 2480        show_inline_completions: Option<bool>,
 2481        cx: &mut ViewContext<Self>,
 2482    ) {
 2483        self.show_inline_completions_override = show_inline_completions;
 2484        self.refresh_inline_completion(false, true, cx);
 2485    }
 2486
 2487    fn should_show_inline_completions(
 2488        &self,
 2489        buffer: &Model<Buffer>,
 2490        buffer_position: language::Anchor,
 2491        cx: &AppContext,
 2492    ) -> bool {
 2493        if let Some(provider) = self.inline_completion_provider() {
 2494            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2495                show_inline_completions
 2496            } else {
 2497                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2498            }
 2499        } else {
 2500            false
 2501        }
 2502    }
 2503
 2504    pub fn set_use_modal_editing(&mut self, to: bool) {
 2505        self.use_modal_editing = to;
 2506    }
 2507
 2508    pub fn use_modal_editing(&self) -> bool {
 2509        self.use_modal_editing
 2510    }
 2511
 2512    fn selections_did_change(
 2513        &mut self,
 2514        local: bool,
 2515        old_cursor_position: &Anchor,
 2516        show_completions: bool,
 2517        cx: &mut ViewContext<Self>,
 2518    ) {
 2519        cx.invalidate_character_coordinates();
 2520
 2521        // Copy selections to primary selection buffer
 2522        #[cfg(target_os = "linux")]
 2523        if local {
 2524            let selections = self.selections.all::<usize>(cx);
 2525            let buffer_handle = self.buffer.read(cx).read(cx);
 2526
 2527            let mut text = String::new();
 2528            for (index, selection) in selections.iter().enumerate() {
 2529                let text_for_selection = buffer_handle
 2530                    .text_for_range(selection.start..selection.end)
 2531                    .collect::<String>();
 2532
 2533                text.push_str(&text_for_selection);
 2534                if index != selections.len() - 1 {
 2535                    text.push('\n');
 2536                }
 2537            }
 2538
 2539            if !text.is_empty() {
 2540                cx.write_to_primary(ClipboardItem::new_string(text));
 2541            }
 2542        }
 2543
 2544        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2545            self.buffer.update(cx, |buffer, cx| {
 2546                buffer.set_active_selections(
 2547                    &self.selections.disjoint_anchors(),
 2548                    self.selections.line_mode,
 2549                    self.cursor_shape,
 2550                    cx,
 2551                )
 2552            });
 2553        }
 2554        let display_map = self
 2555            .display_map
 2556            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2557        let buffer = &display_map.buffer_snapshot;
 2558        self.add_selections_state = None;
 2559        self.select_next_state = None;
 2560        self.select_prev_state = None;
 2561        self.select_larger_syntax_node_stack.clear();
 2562        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2563        self.snippet_stack
 2564            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2565        self.take_rename(false, cx);
 2566
 2567        let new_cursor_position = self.selections.newest_anchor().head();
 2568
 2569        self.push_to_nav_history(
 2570            *old_cursor_position,
 2571            Some(new_cursor_position.to_point(buffer)),
 2572            cx,
 2573        );
 2574
 2575        if local {
 2576            let new_cursor_position = self.selections.newest_anchor().head();
 2577            let mut context_menu = self.context_menu.write();
 2578            let completion_menu = match context_menu.as_ref() {
 2579                Some(ContextMenu::Completions(menu)) => Some(menu),
 2580
 2581                _ => {
 2582                    *context_menu = None;
 2583                    None
 2584                }
 2585            };
 2586
 2587            if let Some(completion_menu) = completion_menu {
 2588                let cursor_position = new_cursor_position.to_offset(buffer);
 2589                let (word_range, kind) =
 2590                    buffer.surrounding_word(completion_menu.initial_position, true);
 2591                if kind == Some(CharKind::Word)
 2592                    && word_range.to_inclusive().contains(&cursor_position)
 2593                {
 2594                    let mut completion_menu = completion_menu.clone();
 2595                    drop(context_menu);
 2596
 2597                    let query = Self::completion_query(buffer, cursor_position);
 2598                    cx.spawn(move |this, mut cx| async move {
 2599                        completion_menu
 2600                            .filter(query.as_deref(), cx.background_executor().clone())
 2601                            .await;
 2602
 2603                        this.update(&mut cx, |this, cx| {
 2604                            let mut context_menu = this.context_menu.write();
 2605                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2606                                return;
 2607                            };
 2608
 2609                            if menu.id > completion_menu.id {
 2610                                return;
 2611                            }
 2612
 2613                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2614                            drop(context_menu);
 2615                            cx.notify();
 2616                        })
 2617                    })
 2618                    .detach();
 2619
 2620                    if show_completions {
 2621                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2622                    }
 2623                } else {
 2624                    drop(context_menu);
 2625                    self.hide_context_menu(cx);
 2626                }
 2627            } else {
 2628                drop(context_menu);
 2629            }
 2630
 2631            hide_hover(self, cx);
 2632
 2633            if old_cursor_position.to_display_point(&display_map).row()
 2634                != new_cursor_position.to_display_point(&display_map).row()
 2635            {
 2636                self.available_code_actions.take();
 2637            }
 2638            self.refresh_code_actions(cx);
 2639            self.refresh_document_highlights(cx);
 2640            refresh_matching_bracket_highlights(self, cx);
 2641            self.discard_inline_completion(false, cx);
 2642            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2643            if self.git_blame_inline_enabled {
 2644                self.start_inline_blame_timer(cx);
 2645            }
 2646        }
 2647
 2648        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2649        cx.emit(EditorEvent::SelectionsChanged { local });
 2650
 2651        if self.selections.disjoint_anchors().len() == 1 {
 2652            cx.emit(SearchEvent::ActiveMatchChanged)
 2653        }
 2654        cx.notify();
 2655    }
 2656
 2657    pub fn change_selections<R>(
 2658        &mut self,
 2659        autoscroll: Option<Autoscroll>,
 2660        cx: &mut ViewContext<Self>,
 2661        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2662    ) -> R {
 2663        self.change_selections_inner(autoscroll, true, cx, change)
 2664    }
 2665
 2666    pub fn change_selections_inner<R>(
 2667        &mut self,
 2668        autoscroll: Option<Autoscroll>,
 2669        request_completions: bool,
 2670        cx: &mut ViewContext<Self>,
 2671        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2672    ) -> R {
 2673        let old_cursor_position = self.selections.newest_anchor().head();
 2674        self.push_to_selection_history();
 2675
 2676        let (changed, result) = self.selections.change_with(cx, change);
 2677
 2678        if changed {
 2679            if let Some(autoscroll) = autoscroll {
 2680                self.request_autoscroll(autoscroll, cx);
 2681            }
 2682            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2683
 2684            if self.should_open_signature_help_automatically(
 2685                &old_cursor_position,
 2686                self.signature_help_state.backspace_pressed(),
 2687                cx,
 2688            ) {
 2689                self.show_signature_help(&ShowSignatureHelp, cx);
 2690            }
 2691            self.signature_help_state.set_backspace_pressed(false);
 2692        }
 2693
 2694        result
 2695    }
 2696
 2697    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2698    where
 2699        I: IntoIterator<Item = (Range<S>, T)>,
 2700        S: ToOffset,
 2701        T: Into<Arc<str>>,
 2702    {
 2703        if self.read_only(cx) {
 2704            return;
 2705        }
 2706
 2707        self.buffer
 2708            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2709    }
 2710
 2711    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2712    where
 2713        I: IntoIterator<Item = (Range<S>, T)>,
 2714        S: ToOffset,
 2715        T: Into<Arc<str>>,
 2716    {
 2717        if self.read_only(cx) {
 2718            return;
 2719        }
 2720
 2721        self.buffer.update(cx, |buffer, cx| {
 2722            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2723        });
 2724    }
 2725
 2726    pub fn edit_with_block_indent<I, S, T>(
 2727        &mut self,
 2728        edits: I,
 2729        original_indent_columns: Vec<u32>,
 2730        cx: &mut ViewContext<Self>,
 2731    ) where
 2732        I: IntoIterator<Item = (Range<S>, T)>,
 2733        S: ToOffset,
 2734        T: Into<Arc<str>>,
 2735    {
 2736        if self.read_only(cx) {
 2737            return;
 2738        }
 2739
 2740        self.buffer.update(cx, |buffer, cx| {
 2741            buffer.edit(
 2742                edits,
 2743                Some(AutoindentMode::Block {
 2744                    original_indent_columns,
 2745                }),
 2746                cx,
 2747            )
 2748        });
 2749    }
 2750
 2751    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2752        self.hide_context_menu(cx);
 2753
 2754        match phase {
 2755            SelectPhase::Begin {
 2756                position,
 2757                add,
 2758                click_count,
 2759            } => self.begin_selection(position, add, click_count, cx),
 2760            SelectPhase::BeginColumnar {
 2761                position,
 2762                goal_column,
 2763                reset,
 2764            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2765            SelectPhase::Extend {
 2766                position,
 2767                click_count,
 2768            } => self.extend_selection(position, click_count, cx),
 2769            SelectPhase::Update {
 2770                position,
 2771                goal_column,
 2772                scroll_delta,
 2773            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2774            SelectPhase::End => self.end_selection(cx),
 2775        }
 2776    }
 2777
 2778    fn extend_selection(
 2779        &mut self,
 2780        position: DisplayPoint,
 2781        click_count: usize,
 2782        cx: &mut ViewContext<Self>,
 2783    ) {
 2784        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2785        let tail = self.selections.newest::<usize>(cx).tail();
 2786        self.begin_selection(position, false, click_count, cx);
 2787
 2788        let position = position.to_offset(&display_map, Bias::Left);
 2789        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2790
 2791        let mut pending_selection = self
 2792            .selections
 2793            .pending_anchor()
 2794            .expect("extend_selection not called with pending selection");
 2795        if position >= tail {
 2796            pending_selection.start = tail_anchor;
 2797        } else {
 2798            pending_selection.end = tail_anchor;
 2799            pending_selection.reversed = true;
 2800        }
 2801
 2802        let mut pending_mode = self.selections.pending_mode().unwrap();
 2803        match &mut pending_mode {
 2804            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2805            _ => {}
 2806        }
 2807
 2808        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2809            s.set_pending(pending_selection, pending_mode)
 2810        });
 2811    }
 2812
 2813    fn begin_selection(
 2814        &mut self,
 2815        position: DisplayPoint,
 2816        add: bool,
 2817        click_count: usize,
 2818        cx: &mut ViewContext<Self>,
 2819    ) {
 2820        if !self.focus_handle.is_focused(cx) {
 2821            self.last_focused_descendant = None;
 2822            cx.focus(&self.focus_handle);
 2823        }
 2824
 2825        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2826        let buffer = &display_map.buffer_snapshot;
 2827        let newest_selection = self.selections.newest_anchor().clone();
 2828        let position = display_map.clip_point(position, Bias::Left);
 2829
 2830        let start;
 2831        let end;
 2832        let mode;
 2833        let auto_scroll;
 2834        match click_count {
 2835            1 => {
 2836                start = buffer.anchor_before(position.to_point(&display_map));
 2837                end = start;
 2838                mode = SelectMode::Character;
 2839                auto_scroll = true;
 2840            }
 2841            2 => {
 2842                let range = movement::surrounding_word(&display_map, position);
 2843                start = buffer.anchor_before(range.start.to_point(&display_map));
 2844                end = buffer.anchor_before(range.end.to_point(&display_map));
 2845                mode = SelectMode::Word(start..end);
 2846                auto_scroll = true;
 2847            }
 2848            3 => {
 2849                let position = display_map
 2850                    .clip_point(position, Bias::Left)
 2851                    .to_point(&display_map);
 2852                let line_start = display_map.prev_line_boundary(position).0;
 2853                let next_line_start = buffer.clip_point(
 2854                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2855                    Bias::Left,
 2856                );
 2857                start = buffer.anchor_before(line_start);
 2858                end = buffer.anchor_before(next_line_start);
 2859                mode = SelectMode::Line(start..end);
 2860                auto_scroll = true;
 2861            }
 2862            _ => {
 2863                start = buffer.anchor_before(0);
 2864                end = buffer.anchor_before(buffer.len());
 2865                mode = SelectMode::All;
 2866                auto_scroll = false;
 2867            }
 2868        }
 2869
 2870        let point_to_delete: Option<usize> = {
 2871            let selected_points: Vec<Selection<Point>> =
 2872                self.selections.disjoint_in_range(start..end, cx);
 2873
 2874            if !add || click_count > 1 {
 2875                None
 2876            } else if !selected_points.is_empty() {
 2877                Some(selected_points[0].id)
 2878            } else {
 2879                let clicked_point_already_selected =
 2880                    self.selections.disjoint.iter().find(|selection| {
 2881                        selection.start.to_point(buffer) == start.to_point(buffer)
 2882                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2883                    });
 2884
 2885                clicked_point_already_selected.map(|selection| selection.id)
 2886            }
 2887        };
 2888
 2889        let selections_count = self.selections.count();
 2890
 2891        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2892            if let Some(point_to_delete) = point_to_delete {
 2893                s.delete(point_to_delete);
 2894
 2895                if selections_count == 1 {
 2896                    s.set_pending_anchor_range(start..end, mode);
 2897                }
 2898            } else {
 2899                if !add {
 2900                    s.clear_disjoint();
 2901                } else if click_count > 1 {
 2902                    s.delete(newest_selection.id)
 2903                }
 2904
 2905                s.set_pending_anchor_range(start..end, mode);
 2906            }
 2907        });
 2908    }
 2909
 2910    fn begin_columnar_selection(
 2911        &mut self,
 2912        position: DisplayPoint,
 2913        goal_column: u32,
 2914        reset: bool,
 2915        cx: &mut ViewContext<Self>,
 2916    ) {
 2917        if !self.focus_handle.is_focused(cx) {
 2918            self.last_focused_descendant = None;
 2919            cx.focus(&self.focus_handle);
 2920        }
 2921
 2922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2923
 2924        if reset {
 2925            let pointer_position = display_map
 2926                .buffer_snapshot
 2927                .anchor_before(position.to_point(&display_map));
 2928
 2929            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2930                s.clear_disjoint();
 2931                s.set_pending_anchor_range(
 2932                    pointer_position..pointer_position,
 2933                    SelectMode::Character,
 2934                );
 2935            });
 2936        }
 2937
 2938        let tail = self.selections.newest::<Point>(cx).tail();
 2939        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2940
 2941        if !reset {
 2942            self.select_columns(
 2943                tail.to_display_point(&display_map),
 2944                position,
 2945                goal_column,
 2946                &display_map,
 2947                cx,
 2948            );
 2949        }
 2950    }
 2951
 2952    fn update_selection(
 2953        &mut self,
 2954        position: DisplayPoint,
 2955        goal_column: u32,
 2956        scroll_delta: gpui::Point<f32>,
 2957        cx: &mut ViewContext<Self>,
 2958    ) {
 2959        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2960
 2961        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2962            let tail = tail.to_display_point(&display_map);
 2963            self.select_columns(tail, position, goal_column, &display_map, cx);
 2964        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2965            let buffer = self.buffer.read(cx).snapshot(cx);
 2966            let head;
 2967            let tail;
 2968            let mode = self.selections.pending_mode().unwrap();
 2969            match &mode {
 2970                SelectMode::Character => {
 2971                    head = position.to_point(&display_map);
 2972                    tail = pending.tail().to_point(&buffer);
 2973                }
 2974                SelectMode::Word(original_range) => {
 2975                    let original_display_range = original_range.start.to_display_point(&display_map)
 2976                        ..original_range.end.to_display_point(&display_map);
 2977                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2978                        ..original_display_range.end.to_point(&display_map);
 2979                    if movement::is_inside_word(&display_map, position)
 2980                        || original_display_range.contains(&position)
 2981                    {
 2982                        let word_range = movement::surrounding_word(&display_map, position);
 2983                        if word_range.start < original_display_range.start {
 2984                            head = word_range.start.to_point(&display_map);
 2985                        } else {
 2986                            head = word_range.end.to_point(&display_map);
 2987                        }
 2988                    } else {
 2989                        head = position.to_point(&display_map);
 2990                    }
 2991
 2992                    if head <= original_buffer_range.start {
 2993                        tail = original_buffer_range.end;
 2994                    } else {
 2995                        tail = original_buffer_range.start;
 2996                    }
 2997                }
 2998                SelectMode::Line(original_range) => {
 2999                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3000
 3001                    let position = display_map
 3002                        .clip_point(position, Bias::Left)
 3003                        .to_point(&display_map);
 3004                    let line_start = display_map.prev_line_boundary(position).0;
 3005                    let next_line_start = buffer.clip_point(
 3006                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3007                        Bias::Left,
 3008                    );
 3009
 3010                    if line_start < original_range.start {
 3011                        head = line_start
 3012                    } else {
 3013                        head = next_line_start
 3014                    }
 3015
 3016                    if head <= original_range.start {
 3017                        tail = original_range.end;
 3018                    } else {
 3019                        tail = original_range.start;
 3020                    }
 3021                }
 3022                SelectMode::All => {
 3023                    return;
 3024                }
 3025            };
 3026
 3027            if head < tail {
 3028                pending.start = buffer.anchor_before(head);
 3029                pending.end = buffer.anchor_before(tail);
 3030                pending.reversed = true;
 3031            } else {
 3032                pending.start = buffer.anchor_before(tail);
 3033                pending.end = buffer.anchor_before(head);
 3034                pending.reversed = false;
 3035            }
 3036
 3037            self.change_selections(None, cx, |s| {
 3038                s.set_pending(pending, mode);
 3039            });
 3040        } else {
 3041            log::error!("update_selection dispatched with no pending selection");
 3042            return;
 3043        }
 3044
 3045        self.apply_scroll_delta(scroll_delta, cx);
 3046        cx.notify();
 3047    }
 3048
 3049    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3050        self.columnar_selection_tail.take();
 3051        if self.selections.pending_anchor().is_some() {
 3052            let selections = self.selections.all::<usize>(cx);
 3053            self.change_selections(None, cx, |s| {
 3054                s.select(selections);
 3055                s.clear_pending();
 3056            });
 3057        }
 3058    }
 3059
 3060    fn select_columns(
 3061        &mut self,
 3062        tail: DisplayPoint,
 3063        head: DisplayPoint,
 3064        goal_column: u32,
 3065        display_map: &DisplaySnapshot,
 3066        cx: &mut ViewContext<Self>,
 3067    ) {
 3068        let start_row = cmp::min(tail.row(), head.row());
 3069        let end_row = cmp::max(tail.row(), head.row());
 3070        let start_column = cmp::min(tail.column(), goal_column);
 3071        let end_column = cmp::max(tail.column(), goal_column);
 3072        let reversed = start_column < tail.column();
 3073
 3074        let selection_ranges = (start_row.0..=end_row.0)
 3075            .map(DisplayRow)
 3076            .filter_map(|row| {
 3077                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3078                    let start = display_map
 3079                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3080                        .to_point(display_map);
 3081                    let end = display_map
 3082                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3083                        .to_point(display_map);
 3084                    if reversed {
 3085                        Some(end..start)
 3086                    } else {
 3087                        Some(start..end)
 3088                    }
 3089                } else {
 3090                    None
 3091                }
 3092            })
 3093            .collect::<Vec<_>>();
 3094
 3095        self.change_selections(None, cx, |s| {
 3096            s.select_ranges(selection_ranges);
 3097        });
 3098        cx.notify();
 3099    }
 3100
 3101    pub fn has_pending_nonempty_selection(&self) -> bool {
 3102        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3103            Some(Selection { start, end, .. }) => start != end,
 3104            None => false,
 3105        };
 3106
 3107        pending_nonempty_selection
 3108            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3109    }
 3110
 3111    pub fn has_pending_selection(&self) -> bool {
 3112        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3113    }
 3114
 3115    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3116        if self.clear_expanded_diff_hunks(cx) {
 3117            cx.notify();
 3118            return;
 3119        }
 3120        if self.dismiss_menus_and_popups(true, cx) {
 3121            return;
 3122        }
 3123
 3124        if self.mode == EditorMode::Full
 3125            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3126        {
 3127            return;
 3128        }
 3129
 3130        cx.propagate();
 3131    }
 3132
 3133    pub fn dismiss_menus_and_popups(
 3134        &mut self,
 3135        should_report_inline_completion_event: bool,
 3136        cx: &mut ViewContext<Self>,
 3137    ) -> bool {
 3138        if self.take_rename(false, cx).is_some() {
 3139            return true;
 3140        }
 3141
 3142        if hide_hover(self, cx) {
 3143            return true;
 3144        }
 3145
 3146        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3147            return true;
 3148        }
 3149
 3150        if self.hide_context_menu(cx).is_some() {
 3151            return true;
 3152        }
 3153
 3154        if self.mouse_context_menu.take().is_some() {
 3155            return true;
 3156        }
 3157
 3158        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3159            return true;
 3160        }
 3161
 3162        if self.snippet_stack.pop().is_some() {
 3163            return true;
 3164        }
 3165
 3166        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3167            self.dismiss_diagnostics(cx);
 3168            return true;
 3169        }
 3170
 3171        false
 3172    }
 3173
 3174    fn linked_editing_ranges_for(
 3175        &self,
 3176        selection: Range<text::Anchor>,
 3177        cx: &AppContext,
 3178    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3179        if self.linked_edit_ranges.is_empty() {
 3180            return None;
 3181        }
 3182        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3183            selection.end.buffer_id.and_then(|end_buffer_id| {
 3184                if selection.start.buffer_id != Some(end_buffer_id) {
 3185                    return None;
 3186                }
 3187                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3188                let snapshot = buffer.read(cx).snapshot();
 3189                self.linked_edit_ranges
 3190                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3191                    .map(|ranges| (ranges, snapshot, buffer))
 3192            })?;
 3193        use text::ToOffset as TO;
 3194        // find offset from the start of current range to current cursor position
 3195        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3196
 3197        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3198        let start_difference = start_offset - start_byte_offset;
 3199        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3200        let end_difference = end_offset - start_byte_offset;
 3201        // Current range has associated linked ranges.
 3202        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3203        for range in linked_ranges.iter() {
 3204            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3205            let end_offset = start_offset + end_difference;
 3206            let start_offset = start_offset + start_difference;
 3207            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3208                continue;
 3209            }
 3210            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3211                if s.start.buffer_id != selection.start.buffer_id
 3212                    || s.end.buffer_id != selection.end.buffer_id
 3213                {
 3214                    return false;
 3215                }
 3216                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3217                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3218            }) {
 3219                continue;
 3220            }
 3221            let start = buffer_snapshot.anchor_after(start_offset);
 3222            let end = buffer_snapshot.anchor_after(end_offset);
 3223            linked_edits
 3224                .entry(buffer.clone())
 3225                .or_default()
 3226                .push(start..end);
 3227        }
 3228        Some(linked_edits)
 3229    }
 3230
 3231    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3232        let text: Arc<str> = text.into();
 3233
 3234        if self.read_only(cx) {
 3235            return;
 3236        }
 3237
 3238        let selections = self.selections.all_adjusted(cx);
 3239        let mut bracket_inserted = false;
 3240        let mut edits = Vec::new();
 3241        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3242        let mut new_selections = Vec::with_capacity(selections.len());
 3243        let mut new_autoclose_regions = Vec::new();
 3244        let snapshot = self.buffer.read(cx).read(cx);
 3245
 3246        for (selection, autoclose_region) in
 3247            self.selections_with_autoclose_regions(selections, &snapshot)
 3248        {
 3249            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3250                // Determine if the inserted text matches the opening or closing
 3251                // bracket of any of this language's bracket pairs.
 3252                let mut bracket_pair = None;
 3253                let mut is_bracket_pair_start = false;
 3254                let mut is_bracket_pair_end = false;
 3255                if !text.is_empty() {
 3256                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3257                    //  and they are removing the character that triggered IME popup.
 3258                    for (pair, enabled) in scope.brackets() {
 3259                        if !pair.close && !pair.surround {
 3260                            continue;
 3261                        }
 3262
 3263                        if enabled && pair.start.ends_with(text.as_ref()) {
 3264                            let prefix_len = pair.start.len() - text.len();
 3265                            let preceding_text_matches_prefix = prefix_len == 0
 3266                                || (selection.start.column >= (prefix_len as u32)
 3267                                    && snapshot.contains_str_at(
 3268                                        Point::new(
 3269                                            selection.start.row,
 3270                                            selection.start.column - (prefix_len as u32),
 3271                                        ),
 3272                                        &pair.start[..prefix_len],
 3273                                    ));
 3274                            if preceding_text_matches_prefix {
 3275                                bracket_pair = Some(pair.clone());
 3276                                is_bracket_pair_start = true;
 3277                                break;
 3278                            }
 3279                        }
 3280                        if pair.end.as_str() == text.as_ref() {
 3281                            bracket_pair = Some(pair.clone());
 3282                            is_bracket_pair_end = true;
 3283                            break;
 3284                        }
 3285                    }
 3286                }
 3287
 3288                if let Some(bracket_pair) = bracket_pair {
 3289                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3290                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3291                    let auto_surround =
 3292                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3293                    if selection.is_empty() {
 3294                        if is_bracket_pair_start {
 3295                            // If the inserted text is a suffix of an opening bracket and the
 3296                            // selection is preceded by the rest of the opening bracket, then
 3297                            // insert the closing bracket.
 3298                            let following_text_allows_autoclose = snapshot
 3299                                .chars_at(selection.start)
 3300                                .next()
 3301                                .map_or(true, |c| scope.should_autoclose_before(c));
 3302
 3303                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3304                                && bracket_pair.start.len() == 1
 3305                            {
 3306                                let target = bracket_pair.start.chars().next().unwrap();
 3307                                let current_line_count = snapshot
 3308                                    .reversed_chars_at(selection.start)
 3309                                    .take_while(|&c| c != '\n')
 3310                                    .filter(|&c| c == target)
 3311                                    .count();
 3312                                current_line_count % 2 == 1
 3313                            } else {
 3314                                false
 3315                            };
 3316
 3317                            if autoclose
 3318                                && bracket_pair.close
 3319                                && following_text_allows_autoclose
 3320                                && !is_closing_quote
 3321                            {
 3322                                let anchor = snapshot.anchor_before(selection.end);
 3323                                new_selections.push((selection.map(|_| anchor), text.len()));
 3324                                new_autoclose_regions.push((
 3325                                    anchor,
 3326                                    text.len(),
 3327                                    selection.id,
 3328                                    bracket_pair.clone(),
 3329                                ));
 3330                                edits.push((
 3331                                    selection.range(),
 3332                                    format!("{}{}", text, bracket_pair.end).into(),
 3333                                ));
 3334                                bracket_inserted = true;
 3335                                continue;
 3336                            }
 3337                        }
 3338
 3339                        if let Some(region) = autoclose_region {
 3340                            // If the selection is followed by an auto-inserted closing bracket,
 3341                            // then don't insert that closing bracket again; just move the selection
 3342                            // past the closing bracket.
 3343                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3344                                && text.as_ref() == region.pair.end.as_str();
 3345                            if should_skip {
 3346                                let anchor = snapshot.anchor_after(selection.end);
 3347                                new_selections
 3348                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3349                                continue;
 3350                            }
 3351                        }
 3352
 3353                        let always_treat_brackets_as_autoclosed = snapshot
 3354                            .settings_at(selection.start, cx)
 3355                            .always_treat_brackets_as_autoclosed;
 3356                        if always_treat_brackets_as_autoclosed
 3357                            && is_bracket_pair_end
 3358                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3359                        {
 3360                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3361                            // and the inserted text is a closing bracket and the selection is followed
 3362                            // by the closing bracket then move the selection past the closing bracket.
 3363                            let anchor = snapshot.anchor_after(selection.end);
 3364                            new_selections.push((selection.map(|_| anchor), text.len()));
 3365                            continue;
 3366                        }
 3367                    }
 3368                    // If an opening bracket is 1 character long and is typed while
 3369                    // text is selected, then surround that text with the bracket pair.
 3370                    else if auto_surround
 3371                        && bracket_pair.surround
 3372                        && is_bracket_pair_start
 3373                        && bracket_pair.start.chars().count() == 1
 3374                    {
 3375                        edits.push((selection.start..selection.start, text.clone()));
 3376                        edits.push((
 3377                            selection.end..selection.end,
 3378                            bracket_pair.end.as_str().into(),
 3379                        ));
 3380                        bracket_inserted = true;
 3381                        new_selections.push((
 3382                            Selection {
 3383                                id: selection.id,
 3384                                start: snapshot.anchor_after(selection.start),
 3385                                end: snapshot.anchor_before(selection.end),
 3386                                reversed: selection.reversed,
 3387                                goal: selection.goal,
 3388                            },
 3389                            0,
 3390                        ));
 3391                        continue;
 3392                    }
 3393                }
 3394            }
 3395
 3396            if self.auto_replace_emoji_shortcode
 3397                && selection.is_empty()
 3398                && text.as_ref().ends_with(':')
 3399            {
 3400                if let Some(possible_emoji_short_code) =
 3401                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3402                {
 3403                    if !possible_emoji_short_code.is_empty() {
 3404                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3405                            let emoji_shortcode_start = Point::new(
 3406                                selection.start.row,
 3407                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3408                            );
 3409
 3410                            // Remove shortcode from buffer
 3411                            edits.push((
 3412                                emoji_shortcode_start..selection.start,
 3413                                "".to_string().into(),
 3414                            ));
 3415                            new_selections.push((
 3416                                Selection {
 3417                                    id: selection.id,
 3418                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3419                                    end: snapshot.anchor_before(selection.start),
 3420                                    reversed: selection.reversed,
 3421                                    goal: selection.goal,
 3422                                },
 3423                                0,
 3424                            ));
 3425
 3426                            // Insert emoji
 3427                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3428                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3429                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3430
 3431                            continue;
 3432                        }
 3433                    }
 3434                }
 3435            }
 3436
 3437            // If not handling any auto-close operation, then just replace the selected
 3438            // text with the given input and move the selection to the end of the
 3439            // newly inserted text.
 3440            let anchor = snapshot.anchor_after(selection.end);
 3441            if !self.linked_edit_ranges.is_empty() {
 3442                let start_anchor = snapshot.anchor_before(selection.start);
 3443
 3444                let is_word_char = text.chars().next().map_or(true, |char| {
 3445                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3446                    classifier.is_word(char)
 3447                });
 3448
 3449                if is_word_char {
 3450                    if let Some(ranges) = self
 3451                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3452                    {
 3453                        for (buffer, edits) in ranges {
 3454                            linked_edits
 3455                                .entry(buffer.clone())
 3456                                .or_default()
 3457                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3458                        }
 3459                    }
 3460                }
 3461            }
 3462
 3463            new_selections.push((selection.map(|_| anchor), 0));
 3464            edits.push((selection.start..selection.end, text.clone()));
 3465        }
 3466
 3467        drop(snapshot);
 3468
 3469        self.transact(cx, |this, cx| {
 3470            this.buffer.update(cx, |buffer, cx| {
 3471                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3472            });
 3473            for (buffer, edits) in linked_edits {
 3474                buffer.update(cx, |buffer, cx| {
 3475                    let snapshot = buffer.snapshot();
 3476                    let edits = edits
 3477                        .into_iter()
 3478                        .map(|(range, text)| {
 3479                            use text::ToPoint as TP;
 3480                            let end_point = TP::to_point(&range.end, &snapshot);
 3481                            let start_point = TP::to_point(&range.start, &snapshot);
 3482                            (start_point..end_point, text)
 3483                        })
 3484                        .sorted_by_key(|(range, _)| range.start)
 3485                        .collect::<Vec<_>>();
 3486                    buffer.edit(edits, None, cx);
 3487                })
 3488            }
 3489            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3490            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3491            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3492            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3493                .zip(new_selection_deltas)
 3494                .map(|(selection, delta)| Selection {
 3495                    id: selection.id,
 3496                    start: selection.start + delta,
 3497                    end: selection.end + delta,
 3498                    reversed: selection.reversed,
 3499                    goal: SelectionGoal::None,
 3500                })
 3501                .collect::<Vec<_>>();
 3502
 3503            let mut i = 0;
 3504            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3505                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3506                let start = map.buffer_snapshot.anchor_before(position);
 3507                let end = map.buffer_snapshot.anchor_after(position);
 3508                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3509                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3510                        Ordering::Less => i += 1,
 3511                        Ordering::Greater => break,
 3512                        Ordering::Equal => {
 3513                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3514                                Ordering::Less => i += 1,
 3515                                Ordering::Equal => break,
 3516                                Ordering::Greater => break,
 3517                            }
 3518                        }
 3519                    }
 3520                }
 3521                this.autoclose_regions.insert(
 3522                    i,
 3523                    AutocloseRegion {
 3524                        selection_id,
 3525                        range: start..end,
 3526                        pair,
 3527                    },
 3528                );
 3529            }
 3530
 3531            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3532            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3533                s.select(new_selections)
 3534            });
 3535
 3536            if !bracket_inserted {
 3537                if let Some(on_type_format_task) =
 3538                    this.trigger_on_type_formatting(text.to_string(), cx)
 3539                {
 3540                    on_type_format_task.detach_and_log_err(cx);
 3541                }
 3542            }
 3543
 3544            let editor_settings = EditorSettings::get_global(cx);
 3545            if bracket_inserted
 3546                && (editor_settings.auto_signature_help
 3547                    || editor_settings.show_signature_help_after_edits)
 3548            {
 3549                this.show_signature_help(&ShowSignatureHelp, cx);
 3550            }
 3551
 3552            let trigger_in_words = !had_active_inline_completion;
 3553            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3554            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3555            this.refresh_inline_completion(true, false, cx);
 3556        });
 3557    }
 3558
 3559    fn find_possible_emoji_shortcode_at_position(
 3560        snapshot: &MultiBufferSnapshot,
 3561        position: Point,
 3562    ) -> Option<String> {
 3563        let mut chars = Vec::new();
 3564        let mut found_colon = false;
 3565        for char in snapshot.reversed_chars_at(position).take(100) {
 3566            // Found a possible emoji shortcode in the middle of the buffer
 3567            if found_colon {
 3568                if char.is_whitespace() {
 3569                    chars.reverse();
 3570                    return Some(chars.iter().collect());
 3571                }
 3572                // If the previous character is not a whitespace, we are in the middle of a word
 3573                // and we only want to complete the shortcode if the word is made up of other emojis
 3574                let mut containing_word = String::new();
 3575                for ch in snapshot
 3576                    .reversed_chars_at(position)
 3577                    .skip(chars.len() + 1)
 3578                    .take(100)
 3579                {
 3580                    if ch.is_whitespace() {
 3581                        break;
 3582                    }
 3583                    containing_word.push(ch);
 3584                }
 3585                let containing_word = containing_word.chars().rev().collect::<String>();
 3586                if util::word_consists_of_emojis(containing_word.as_str()) {
 3587                    chars.reverse();
 3588                    return Some(chars.iter().collect());
 3589                }
 3590            }
 3591
 3592            if char.is_whitespace() || !char.is_ascii() {
 3593                return None;
 3594            }
 3595            if char == ':' {
 3596                found_colon = true;
 3597            } else {
 3598                chars.push(char);
 3599            }
 3600        }
 3601        // Found a possible emoji shortcode at the beginning of the buffer
 3602        chars.reverse();
 3603        Some(chars.iter().collect())
 3604    }
 3605
 3606    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3607        self.transact(cx, |this, cx| {
 3608            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3609                let selections = this.selections.all::<usize>(cx);
 3610                let multi_buffer = this.buffer.read(cx);
 3611                let buffer = multi_buffer.snapshot(cx);
 3612                selections
 3613                    .iter()
 3614                    .map(|selection| {
 3615                        let start_point = selection.start.to_point(&buffer);
 3616                        let mut indent =
 3617                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3618                        indent.len = cmp::min(indent.len, start_point.column);
 3619                        let start = selection.start;
 3620                        let end = selection.end;
 3621                        let selection_is_empty = start == end;
 3622                        let language_scope = buffer.language_scope_at(start);
 3623                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3624                            &language_scope
 3625                        {
 3626                            let leading_whitespace_len = buffer
 3627                                .reversed_chars_at(start)
 3628                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3629                                .map(|c| c.len_utf8())
 3630                                .sum::<usize>();
 3631
 3632                            let trailing_whitespace_len = buffer
 3633                                .chars_at(end)
 3634                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3635                                .map(|c| c.len_utf8())
 3636                                .sum::<usize>();
 3637
 3638                            let insert_extra_newline =
 3639                                language.brackets().any(|(pair, enabled)| {
 3640                                    let pair_start = pair.start.trim_end();
 3641                                    let pair_end = pair.end.trim_start();
 3642
 3643                                    enabled
 3644                                        && pair.newline
 3645                                        && buffer.contains_str_at(
 3646                                            end + trailing_whitespace_len,
 3647                                            pair_end,
 3648                                        )
 3649                                        && buffer.contains_str_at(
 3650                                            (start - leading_whitespace_len)
 3651                                                .saturating_sub(pair_start.len()),
 3652                                            pair_start,
 3653                                        )
 3654                                });
 3655
 3656                            // Comment extension on newline is allowed only for cursor selections
 3657                            let comment_delimiter = maybe!({
 3658                                if !selection_is_empty {
 3659                                    return None;
 3660                                }
 3661
 3662                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3663                                    return None;
 3664                                }
 3665
 3666                                let delimiters = language.line_comment_prefixes();
 3667                                let max_len_of_delimiter =
 3668                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3669                                let (snapshot, range) =
 3670                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3671
 3672                                let mut index_of_first_non_whitespace = 0;
 3673                                let comment_candidate = snapshot
 3674                                    .chars_for_range(range)
 3675                                    .skip_while(|c| {
 3676                                        let should_skip = c.is_whitespace();
 3677                                        if should_skip {
 3678                                            index_of_first_non_whitespace += 1;
 3679                                        }
 3680                                        should_skip
 3681                                    })
 3682                                    .take(max_len_of_delimiter)
 3683                                    .collect::<String>();
 3684                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3685                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3686                                })?;
 3687                                let cursor_is_placed_after_comment_marker =
 3688                                    index_of_first_non_whitespace + comment_prefix.len()
 3689                                        <= start_point.column as usize;
 3690                                if cursor_is_placed_after_comment_marker {
 3691                                    Some(comment_prefix.clone())
 3692                                } else {
 3693                                    None
 3694                                }
 3695                            });
 3696                            (comment_delimiter, insert_extra_newline)
 3697                        } else {
 3698                            (None, false)
 3699                        };
 3700
 3701                        let capacity_for_delimiter = comment_delimiter
 3702                            .as_deref()
 3703                            .map(str::len)
 3704                            .unwrap_or_default();
 3705                        let mut new_text =
 3706                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3707                        new_text.push('\n');
 3708                        new_text.extend(indent.chars());
 3709                        if let Some(delimiter) = &comment_delimiter {
 3710                            new_text.push_str(delimiter);
 3711                        }
 3712                        if insert_extra_newline {
 3713                            new_text = new_text.repeat(2);
 3714                        }
 3715
 3716                        let anchor = buffer.anchor_after(end);
 3717                        let new_selection = selection.map(|_| anchor);
 3718                        (
 3719                            (start..end, new_text),
 3720                            (insert_extra_newline, new_selection),
 3721                        )
 3722                    })
 3723                    .unzip()
 3724            };
 3725
 3726            this.edit_with_autoindent(edits, cx);
 3727            let buffer = this.buffer.read(cx).snapshot(cx);
 3728            let new_selections = selection_fixup_info
 3729                .into_iter()
 3730                .map(|(extra_newline_inserted, new_selection)| {
 3731                    let mut cursor = new_selection.end.to_point(&buffer);
 3732                    if extra_newline_inserted {
 3733                        cursor.row -= 1;
 3734                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3735                    }
 3736                    new_selection.map(|_| cursor)
 3737                })
 3738                .collect();
 3739
 3740            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3741            this.refresh_inline_completion(true, false, cx);
 3742        });
 3743    }
 3744
 3745    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3746        let buffer = self.buffer.read(cx);
 3747        let snapshot = buffer.snapshot(cx);
 3748
 3749        let mut edits = Vec::new();
 3750        let mut rows = Vec::new();
 3751
 3752        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3753            let cursor = selection.head();
 3754            let row = cursor.row;
 3755
 3756            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3757
 3758            let newline = "\n".to_string();
 3759            edits.push((start_of_line..start_of_line, newline));
 3760
 3761            rows.push(row + rows_inserted as u32);
 3762        }
 3763
 3764        self.transact(cx, |editor, cx| {
 3765            editor.edit(edits, cx);
 3766
 3767            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3768                let mut index = 0;
 3769                s.move_cursors_with(|map, _, _| {
 3770                    let row = rows[index];
 3771                    index += 1;
 3772
 3773                    let point = Point::new(row, 0);
 3774                    let boundary = map.next_line_boundary(point).1;
 3775                    let clipped = map.clip_point(boundary, Bias::Left);
 3776
 3777                    (clipped, SelectionGoal::None)
 3778                });
 3779            });
 3780
 3781            let mut indent_edits = Vec::new();
 3782            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3783            for row in rows {
 3784                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3785                for (row, indent) in indents {
 3786                    if indent.len == 0 {
 3787                        continue;
 3788                    }
 3789
 3790                    let text = match indent.kind {
 3791                        IndentKind::Space => " ".repeat(indent.len as usize),
 3792                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3793                    };
 3794                    let point = Point::new(row.0, 0);
 3795                    indent_edits.push((point..point, text));
 3796                }
 3797            }
 3798            editor.edit(indent_edits, cx);
 3799        });
 3800    }
 3801
 3802    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3803        let buffer = self.buffer.read(cx);
 3804        let snapshot = buffer.snapshot(cx);
 3805
 3806        let mut edits = Vec::new();
 3807        let mut rows = Vec::new();
 3808        let mut rows_inserted = 0;
 3809
 3810        for selection in self.selections.all_adjusted(cx) {
 3811            let cursor = selection.head();
 3812            let row = cursor.row;
 3813
 3814            let point = Point::new(row + 1, 0);
 3815            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3816
 3817            let newline = "\n".to_string();
 3818            edits.push((start_of_line..start_of_line, newline));
 3819
 3820            rows_inserted += 1;
 3821            rows.push(row + rows_inserted);
 3822        }
 3823
 3824        self.transact(cx, |editor, cx| {
 3825            editor.edit(edits, cx);
 3826
 3827            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3828                let mut index = 0;
 3829                s.move_cursors_with(|map, _, _| {
 3830                    let row = rows[index];
 3831                    index += 1;
 3832
 3833                    let point = Point::new(row, 0);
 3834                    let boundary = map.next_line_boundary(point).1;
 3835                    let clipped = map.clip_point(boundary, Bias::Left);
 3836
 3837                    (clipped, SelectionGoal::None)
 3838                });
 3839            });
 3840
 3841            let mut indent_edits = Vec::new();
 3842            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3843            for row in rows {
 3844                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3845                for (row, indent) in indents {
 3846                    if indent.len == 0 {
 3847                        continue;
 3848                    }
 3849
 3850                    let text = match indent.kind {
 3851                        IndentKind::Space => " ".repeat(indent.len as usize),
 3852                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3853                    };
 3854                    let point = Point::new(row.0, 0);
 3855                    indent_edits.push((point..point, text));
 3856                }
 3857            }
 3858            editor.edit(indent_edits, cx);
 3859        });
 3860    }
 3861
 3862    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3863        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3864            original_indent_columns: Vec::new(),
 3865        });
 3866        self.insert_with_autoindent_mode(text, autoindent, cx);
 3867    }
 3868
 3869    fn insert_with_autoindent_mode(
 3870        &mut self,
 3871        text: &str,
 3872        autoindent_mode: Option<AutoindentMode>,
 3873        cx: &mut ViewContext<Self>,
 3874    ) {
 3875        if self.read_only(cx) {
 3876            return;
 3877        }
 3878
 3879        let text: Arc<str> = text.into();
 3880        self.transact(cx, |this, cx| {
 3881            let old_selections = this.selections.all_adjusted(cx);
 3882            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3883                let anchors = {
 3884                    let snapshot = buffer.read(cx);
 3885                    old_selections
 3886                        .iter()
 3887                        .map(|s| {
 3888                            let anchor = snapshot.anchor_after(s.head());
 3889                            s.map(|_| anchor)
 3890                        })
 3891                        .collect::<Vec<_>>()
 3892                };
 3893                buffer.edit(
 3894                    old_selections
 3895                        .iter()
 3896                        .map(|s| (s.start..s.end, text.clone())),
 3897                    autoindent_mode,
 3898                    cx,
 3899                );
 3900                anchors
 3901            });
 3902
 3903            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3904                s.select_anchors(selection_anchors);
 3905            })
 3906        });
 3907    }
 3908
 3909    fn trigger_completion_on_input(
 3910        &mut self,
 3911        text: &str,
 3912        trigger_in_words: bool,
 3913        cx: &mut ViewContext<Self>,
 3914    ) {
 3915        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3916            self.show_completions(
 3917                &ShowCompletions {
 3918                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3919                },
 3920                cx,
 3921            );
 3922        } else {
 3923            self.hide_context_menu(cx);
 3924        }
 3925    }
 3926
 3927    fn is_completion_trigger(
 3928        &self,
 3929        text: &str,
 3930        trigger_in_words: bool,
 3931        cx: &mut ViewContext<Self>,
 3932    ) -> bool {
 3933        let position = self.selections.newest_anchor().head();
 3934        let multibuffer = self.buffer.read(cx);
 3935        let Some(buffer) = position
 3936            .buffer_id
 3937            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3938        else {
 3939            return false;
 3940        };
 3941
 3942        if let Some(completion_provider) = &self.completion_provider {
 3943            completion_provider.is_completion_trigger(
 3944                &buffer,
 3945                position.text_anchor,
 3946                text,
 3947                trigger_in_words,
 3948                cx,
 3949            )
 3950        } else {
 3951            false
 3952        }
 3953    }
 3954
 3955    /// If any empty selections is touching the start of its innermost containing autoclose
 3956    /// region, expand it to select the brackets.
 3957    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3958        let selections = self.selections.all::<usize>(cx);
 3959        let buffer = self.buffer.read(cx).read(cx);
 3960        let new_selections = self
 3961            .selections_with_autoclose_regions(selections, &buffer)
 3962            .map(|(mut selection, region)| {
 3963                if !selection.is_empty() {
 3964                    return selection;
 3965                }
 3966
 3967                if let Some(region) = region {
 3968                    let mut range = region.range.to_offset(&buffer);
 3969                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3970                        range.start -= region.pair.start.len();
 3971                        if buffer.contains_str_at(range.start, &region.pair.start)
 3972                            && buffer.contains_str_at(range.end, &region.pair.end)
 3973                        {
 3974                            range.end += region.pair.end.len();
 3975                            selection.start = range.start;
 3976                            selection.end = range.end;
 3977
 3978                            return selection;
 3979                        }
 3980                    }
 3981                }
 3982
 3983                let always_treat_brackets_as_autoclosed = buffer
 3984                    .settings_at(selection.start, cx)
 3985                    .always_treat_brackets_as_autoclosed;
 3986
 3987                if !always_treat_brackets_as_autoclosed {
 3988                    return selection;
 3989                }
 3990
 3991                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3992                    for (pair, enabled) in scope.brackets() {
 3993                        if !enabled || !pair.close {
 3994                            continue;
 3995                        }
 3996
 3997                        if buffer.contains_str_at(selection.start, &pair.end) {
 3998                            let pair_start_len = pair.start.len();
 3999                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4000                            {
 4001                                selection.start -= pair_start_len;
 4002                                selection.end += pair.end.len();
 4003
 4004                                return selection;
 4005                            }
 4006                        }
 4007                    }
 4008                }
 4009
 4010                selection
 4011            })
 4012            .collect();
 4013
 4014        drop(buffer);
 4015        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4016    }
 4017
 4018    /// Iterate the given selections, and for each one, find the smallest surrounding
 4019    /// autoclose region. This uses the ordering of the selections and the autoclose
 4020    /// regions to avoid repeated comparisons.
 4021    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4022        &'a self,
 4023        selections: impl IntoIterator<Item = Selection<D>>,
 4024        buffer: &'a MultiBufferSnapshot,
 4025    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4026        let mut i = 0;
 4027        let mut regions = self.autoclose_regions.as_slice();
 4028        selections.into_iter().map(move |selection| {
 4029            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4030
 4031            let mut enclosing = None;
 4032            while let Some(pair_state) = regions.get(i) {
 4033                if pair_state.range.end.to_offset(buffer) < range.start {
 4034                    regions = &regions[i + 1..];
 4035                    i = 0;
 4036                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4037                    break;
 4038                } else {
 4039                    if pair_state.selection_id == selection.id {
 4040                        enclosing = Some(pair_state);
 4041                    }
 4042                    i += 1;
 4043                }
 4044            }
 4045
 4046            (selection, enclosing)
 4047        })
 4048    }
 4049
 4050    /// Remove any autoclose regions that no longer contain their selection.
 4051    fn invalidate_autoclose_regions(
 4052        &mut self,
 4053        mut selections: &[Selection<Anchor>],
 4054        buffer: &MultiBufferSnapshot,
 4055    ) {
 4056        self.autoclose_regions.retain(|state| {
 4057            let mut i = 0;
 4058            while let Some(selection) = selections.get(i) {
 4059                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4060                    selections = &selections[1..];
 4061                    continue;
 4062                }
 4063                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4064                    break;
 4065                }
 4066                if selection.id == state.selection_id {
 4067                    return true;
 4068                } else {
 4069                    i += 1;
 4070                }
 4071            }
 4072            false
 4073        });
 4074    }
 4075
 4076    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4077        let offset = position.to_offset(buffer);
 4078        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4079        if offset > word_range.start && kind == Some(CharKind::Word) {
 4080            Some(
 4081                buffer
 4082                    .text_for_range(word_range.start..offset)
 4083                    .collect::<String>(),
 4084            )
 4085        } else {
 4086            None
 4087        }
 4088    }
 4089
 4090    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4091        self.refresh_inlay_hints(
 4092            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4093            cx,
 4094        );
 4095    }
 4096
 4097    pub fn inlay_hints_enabled(&self) -> bool {
 4098        self.inlay_hint_cache.enabled
 4099    }
 4100
 4101    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4102        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4103            return;
 4104        }
 4105
 4106        let reason_description = reason.description();
 4107        let ignore_debounce = matches!(
 4108            reason,
 4109            InlayHintRefreshReason::SettingsChange(_)
 4110                | InlayHintRefreshReason::Toggle(_)
 4111                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4112        );
 4113        let (invalidate_cache, required_languages) = match reason {
 4114            InlayHintRefreshReason::Toggle(enabled) => {
 4115                self.inlay_hint_cache.enabled = enabled;
 4116                if enabled {
 4117                    (InvalidationStrategy::RefreshRequested, None)
 4118                } else {
 4119                    self.inlay_hint_cache.clear();
 4120                    self.splice_inlays(
 4121                        self.visible_inlay_hints(cx)
 4122                            .iter()
 4123                            .map(|inlay| inlay.id)
 4124                            .collect(),
 4125                        Vec::new(),
 4126                        cx,
 4127                    );
 4128                    return;
 4129                }
 4130            }
 4131            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4132                match self.inlay_hint_cache.update_settings(
 4133                    &self.buffer,
 4134                    new_settings,
 4135                    self.visible_inlay_hints(cx),
 4136                    cx,
 4137                ) {
 4138                    ControlFlow::Break(Some(InlaySplice {
 4139                        to_remove,
 4140                        to_insert,
 4141                    })) => {
 4142                        self.splice_inlays(to_remove, to_insert, cx);
 4143                        return;
 4144                    }
 4145                    ControlFlow::Break(None) => return,
 4146                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4147                }
 4148            }
 4149            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4150                if let Some(InlaySplice {
 4151                    to_remove,
 4152                    to_insert,
 4153                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4154                {
 4155                    self.splice_inlays(to_remove, to_insert, cx);
 4156                }
 4157                return;
 4158            }
 4159            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4160            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4161                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4162            }
 4163            InlayHintRefreshReason::RefreshRequested => {
 4164                (InvalidationStrategy::RefreshRequested, None)
 4165            }
 4166        };
 4167
 4168        if let Some(InlaySplice {
 4169            to_remove,
 4170            to_insert,
 4171        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4172            reason_description,
 4173            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4174            invalidate_cache,
 4175            ignore_debounce,
 4176            cx,
 4177        ) {
 4178            self.splice_inlays(to_remove, to_insert, cx);
 4179        }
 4180    }
 4181
 4182    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4183        self.display_map
 4184            .read(cx)
 4185            .current_inlays()
 4186            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4187            .cloned()
 4188            .collect()
 4189    }
 4190
 4191    pub fn excerpts_for_inlay_hints_query(
 4192        &self,
 4193        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4194        cx: &mut ViewContext<Editor>,
 4195    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4196        let Some(project) = self.project.as_ref() else {
 4197            return HashMap::default();
 4198        };
 4199        let project = project.read(cx);
 4200        let multi_buffer = self.buffer().read(cx);
 4201        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4202        let multi_buffer_visible_start = self
 4203            .scroll_manager
 4204            .anchor()
 4205            .anchor
 4206            .to_point(&multi_buffer_snapshot);
 4207        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4208            multi_buffer_visible_start
 4209                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4210            Bias::Left,
 4211        );
 4212        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4213        multi_buffer
 4214            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4215            .into_iter()
 4216            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4217            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4218                let buffer = buffer_handle.read(cx);
 4219                let buffer_file = project::File::from_dyn(buffer.file())?;
 4220                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4221                let worktree_entry = buffer_worktree
 4222                    .read(cx)
 4223                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4224                if worktree_entry.is_ignored {
 4225                    return None;
 4226                }
 4227
 4228                let language = buffer.language()?;
 4229                if let Some(restrict_to_languages) = restrict_to_languages {
 4230                    if !restrict_to_languages.contains(language) {
 4231                        return None;
 4232                    }
 4233                }
 4234                Some((
 4235                    excerpt_id,
 4236                    (
 4237                        buffer_handle,
 4238                        buffer.version().clone(),
 4239                        excerpt_visible_range,
 4240                    ),
 4241                ))
 4242            })
 4243            .collect()
 4244    }
 4245
 4246    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4247        TextLayoutDetails {
 4248            text_system: cx.text_system().clone(),
 4249            editor_style: self.style.clone().unwrap(),
 4250            rem_size: cx.rem_size(),
 4251            scroll_anchor: self.scroll_manager.anchor(),
 4252            visible_rows: self.visible_line_count(),
 4253            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4254        }
 4255    }
 4256
 4257    fn splice_inlays(
 4258        &self,
 4259        to_remove: Vec<InlayId>,
 4260        to_insert: Vec<Inlay>,
 4261        cx: &mut ViewContext<Self>,
 4262    ) {
 4263        self.display_map.update(cx, |display_map, cx| {
 4264            display_map.splice_inlays(to_remove, to_insert, cx);
 4265        });
 4266        cx.notify();
 4267    }
 4268
 4269    fn trigger_on_type_formatting(
 4270        &self,
 4271        input: String,
 4272        cx: &mut ViewContext<Self>,
 4273    ) -> Option<Task<Result<()>>> {
 4274        if input.len() != 1 {
 4275            return None;
 4276        }
 4277
 4278        let project = self.project.as_ref()?;
 4279        let position = self.selections.newest_anchor().head();
 4280        let (buffer, buffer_position) = self
 4281            .buffer
 4282            .read(cx)
 4283            .text_anchor_for_position(position, cx)?;
 4284
 4285        let settings = language_settings::language_settings(
 4286            buffer
 4287                .read(cx)
 4288                .language_at(buffer_position)
 4289                .map(|l| l.name()),
 4290            buffer.read(cx).file(),
 4291            cx,
 4292        );
 4293        if !settings.use_on_type_format {
 4294            return None;
 4295        }
 4296
 4297        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4298        // hence we do LSP request & edit on host side only — add formats to host's history.
 4299        let push_to_lsp_host_history = true;
 4300        // If this is not the host, append its history with new edits.
 4301        let push_to_client_history = project.read(cx).is_via_collab();
 4302
 4303        let on_type_formatting = project.update(cx, |project, cx| {
 4304            project.on_type_format(
 4305                buffer.clone(),
 4306                buffer_position,
 4307                input,
 4308                push_to_lsp_host_history,
 4309                cx,
 4310            )
 4311        });
 4312        Some(cx.spawn(|editor, mut cx| async move {
 4313            if let Some(transaction) = on_type_formatting.await? {
 4314                if push_to_client_history {
 4315                    buffer
 4316                        .update(&mut cx, |buffer, _| {
 4317                            buffer.push_transaction(transaction, Instant::now());
 4318                        })
 4319                        .ok();
 4320                }
 4321                editor.update(&mut cx, |editor, cx| {
 4322                    editor.refresh_document_highlights(cx);
 4323                })?;
 4324            }
 4325            Ok(())
 4326        }))
 4327    }
 4328
 4329    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4330        if self.pending_rename.is_some() {
 4331            return;
 4332        }
 4333
 4334        let Some(provider) = self.completion_provider.as_ref() else {
 4335            return;
 4336        };
 4337
 4338        let position = self.selections.newest_anchor().head();
 4339        let (buffer, buffer_position) =
 4340            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4341                output
 4342            } else {
 4343                return;
 4344            };
 4345
 4346        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4347        let is_followup_invoke = {
 4348            let context_menu_state = self.context_menu.read();
 4349            matches!(
 4350                context_menu_state.deref(),
 4351                Some(ContextMenu::Completions(_))
 4352            )
 4353        };
 4354        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4355            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4356            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4357                CompletionTriggerKind::TRIGGER_CHARACTER
 4358            }
 4359
 4360            _ => CompletionTriggerKind::INVOKED,
 4361        };
 4362        let completion_context = CompletionContext {
 4363            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4364                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4365                    Some(String::from(trigger))
 4366                } else {
 4367                    None
 4368                }
 4369            }),
 4370            trigger_kind,
 4371        };
 4372        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4373        let sort_completions = provider.sort_completions();
 4374
 4375        let id = post_inc(&mut self.next_completion_id);
 4376        let task = cx.spawn(|this, mut cx| {
 4377            async move {
 4378                this.update(&mut cx, |this, _| {
 4379                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4380                })?;
 4381                let completions = completions.await.log_err();
 4382                let menu = if let Some(completions) = completions {
 4383                    let mut menu = CompletionsMenu {
 4384                        id,
 4385                        sort_completions,
 4386                        initial_position: position,
 4387                        match_candidates: completions
 4388                            .iter()
 4389                            .enumerate()
 4390                            .map(|(id, completion)| {
 4391                                StringMatchCandidate::new(
 4392                                    id,
 4393                                    completion.label.text[completion.label.filter_range.clone()]
 4394                                        .into(),
 4395                                )
 4396                            })
 4397                            .collect(),
 4398                        buffer: buffer.clone(),
 4399                        completions: Arc::new(RwLock::new(completions.into())),
 4400                        matches: Vec::new().into(),
 4401                        selected_item: 0,
 4402                        scroll_handle: UniformListScrollHandle::new(),
 4403                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4404                            DebouncedDelay::new(),
 4405                        )),
 4406                    };
 4407                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4408                        .await;
 4409
 4410                    if menu.matches.is_empty() {
 4411                        None
 4412                    } else {
 4413                        this.update(&mut cx, |editor, cx| {
 4414                            let completions = menu.completions.clone();
 4415                            let matches = menu.matches.clone();
 4416
 4417                            let delay_ms = EditorSettings::get_global(cx)
 4418                                .completion_documentation_secondary_query_debounce;
 4419                            let delay = Duration::from_millis(delay_ms);
 4420                            editor
 4421                                .completion_documentation_pre_resolve_debounce
 4422                                .fire_new(delay, cx, |editor, cx| {
 4423                                    CompletionsMenu::pre_resolve_completion_documentation(
 4424                                        buffer,
 4425                                        completions,
 4426                                        matches,
 4427                                        editor,
 4428                                        cx,
 4429                                    )
 4430                                });
 4431                        })
 4432                        .ok();
 4433                        Some(menu)
 4434                    }
 4435                } else {
 4436                    None
 4437                };
 4438
 4439                this.update(&mut cx, |this, cx| {
 4440                    let mut context_menu = this.context_menu.write();
 4441                    match context_menu.as_ref() {
 4442                        None => {}
 4443
 4444                        Some(ContextMenu::Completions(prev_menu)) => {
 4445                            if prev_menu.id > id {
 4446                                return;
 4447                            }
 4448                        }
 4449
 4450                        _ => return,
 4451                    }
 4452
 4453                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4454                        let menu = menu.unwrap();
 4455                        *context_menu = Some(ContextMenu::Completions(menu));
 4456                        drop(context_menu);
 4457                        this.discard_inline_completion(false, cx);
 4458                        cx.notify();
 4459                    } else if this.completion_tasks.len() <= 1 {
 4460                        // If there are no more completion tasks and the last menu was
 4461                        // empty, we should hide it. If it was already hidden, we should
 4462                        // also show the copilot completion when available.
 4463                        drop(context_menu);
 4464                        if this.hide_context_menu(cx).is_none() {
 4465                            this.update_visible_inline_completion(cx);
 4466                        }
 4467                    }
 4468                })?;
 4469
 4470                Ok::<_, anyhow::Error>(())
 4471            }
 4472            .log_err()
 4473        });
 4474
 4475        self.completion_tasks.push((id, task));
 4476    }
 4477
 4478    pub fn confirm_completion(
 4479        &mut self,
 4480        action: &ConfirmCompletion,
 4481        cx: &mut ViewContext<Self>,
 4482    ) -> Option<Task<Result<()>>> {
 4483        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4484    }
 4485
 4486    pub fn compose_completion(
 4487        &mut self,
 4488        action: &ComposeCompletion,
 4489        cx: &mut ViewContext<Self>,
 4490    ) -> Option<Task<Result<()>>> {
 4491        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4492    }
 4493
 4494    fn do_completion(
 4495        &mut self,
 4496        item_ix: Option<usize>,
 4497        intent: CompletionIntent,
 4498        cx: &mut ViewContext<Editor>,
 4499    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4500        use language::ToOffset as _;
 4501
 4502        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4503            menu
 4504        } else {
 4505            return None;
 4506        };
 4507
 4508        let mat = completions_menu
 4509            .matches
 4510            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4511        let buffer_handle = completions_menu.buffer;
 4512        let completions = completions_menu.completions.read();
 4513        let completion = completions.get(mat.candidate_id)?;
 4514        cx.stop_propagation();
 4515
 4516        let snippet;
 4517        let text;
 4518
 4519        if completion.is_snippet() {
 4520            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4521            text = snippet.as_ref().unwrap().text.clone();
 4522        } else {
 4523            snippet = None;
 4524            text = completion.new_text.clone();
 4525        };
 4526        let selections = self.selections.all::<usize>(cx);
 4527        let buffer = buffer_handle.read(cx);
 4528        let old_range = completion.old_range.to_offset(buffer);
 4529        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4530
 4531        let newest_selection = self.selections.newest_anchor();
 4532        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4533            return None;
 4534        }
 4535
 4536        let lookbehind = newest_selection
 4537            .start
 4538            .text_anchor
 4539            .to_offset(buffer)
 4540            .saturating_sub(old_range.start);
 4541        let lookahead = old_range
 4542            .end
 4543            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4544        let mut common_prefix_len = old_text
 4545            .bytes()
 4546            .zip(text.bytes())
 4547            .take_while(|(a, b)| a == b)
 4548            .count();
 4549
 4550        let snapshot = self.buffer.read(cx).snapshot(cx);
 4551        let mut range_to_replace: Option<Range<isize>> = None;
 4552        let mut ranges = Vec::new();
 4553        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4554        for selection in &selections {
 4555            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4556                let start = selection.start.saturating_sub(lookbehind);
 4557                let end = selection.end + lookahead;
 4558                if selection.id == newest_selection.id {
 4559                    range_to_replace = Some(
 4560                        ((start + common_prefix_len) as isize - selection.start as isize)
 4561                            ..(end as isize - selection.start as isize),
 4562                    );
 4563                }
 4564                ranges.push(start + common_prefix_len..end);
 4565            } else {
 4566                common_prefix_len = 0;
 4567                ranges.clear();
 4568                ranges.extend(selections.iter().map(|s| {
 4569                    if s.id == newest_selection.id {
 4570                        range_to_replace = Some(
 4571                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4572                                - selection.start as isize
 4573                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4574                                    - selection.start as isize,
 4575                        );
 4576                        old_range.clone()
 4577                    } else {
 4578                        s.start..s.end
 4579                    }
 4580                }));
 4581                break;
 4582            }
 4583            if !self.linked_edit_ranges.is_empty() {
 4584                let start_anchor = snapshot.anchor_before(selection.head());
 4585                let end_anchor = snapshot.anchor_after(selection.tail());
 4586                if let Some(ranges) = self
 4587                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4588                {
 4589                    for (buffer, edits) in ranges {
 4590                        linked_edits.entry(buffer.clone()).or_default().extend(
 4591                            edits
 4592                                .into_iter()
 4593                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4594                        );
 4595                    }
 4596                }
 4597            }
 4598        }
 4599        let text = &text[common_prefix_len..];
 4600
 4601        cx.emit(EditorEvent::InputHandled {
 4602            utf16_range_to_replace: range_to_replace,
 4603            text: text.into(),
 4604        });
 4605
 4606        self.transact(cx, |this, cx| {
 4607            if let Some(mut snippet) = snippet {
 4608                snippet.text = text.to_string();
 4609                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4610                    tabstop.start -= common_prefix_len as isize;
 4611                    tabstop.end -= common_prefix_len as isize;
 4612                }
 4613
 4614                this.insert_snippet(&ranges, snippet, cx).log_err();
 4615            } else {
 4616                this.buffer.update(cx, |buffer, cx| {
 4617                    buffer.edit(
 4618                        ranges.iter().map(|range| (range.clone(), text)),
 4619                        this.autoindent_mode.clone(),
 4620                        cx,
 4621                    );
 4622                });
 4623            }
 4624            for (buffer, edits) in linked_edits {
 4625                buffer.update(cx, |buffer, cx| {
 4626                    let snapshot = buffer.snapshot();
 4627                    let edits = edits
 4628                        .into_iter()
 4629                        .map(|(range, text)| {
 4630                            use text::ToPoint as TP;
 4631                            let end_point = TP::to_point(&range.end, &snapshot);
 4632                            let start_point = TP::to_point(&range.start, &snapshot);
 4633                            (start_point..end_point, text)
 4634                        })
 4635                        .sorted_by_key(|(range, _)| range.start)
 4636                        .collect::<Vec<_>>();
 4637                    buffer.edit(edits, None, cx);
 4638                })
 4639            }
 4640
 4641            this.refresh_inline_completion(true, false, cx);
 4642        });
 4643
 4644        let show_new_completions_on_confirm = completion
 4645            .confirm
 4646            .as_ref()
 4647            .map_or(false, |confirm| confirm(intent, cx));
 4648        if show_new_completions_on_confirm {
 4649            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4650        }
 4651
 4652        let provider = self.completion_provider.as_ref()?;
 4653        let apply_edits = provider.apply_additional_edits_for_completion(
 4654            buffer_handle,
 4655            completion.clone(),
 4656            true,
 4657            cx,
 4658        );
 4659
 4660        let editor_settings = EditorSettings::get_global(cx);
 4661        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4662            // After the code completion is finished, users often want to know what signatures are needed.
 4663            // so we should automatically call signature_help
 4664            self.show_signature_help(&ShowSignatureHelp, cx);
 4665        }
 4666
 4667        Some(cx.foreground_executor().spawn(async move {
 4668            apply_edits.await?;
 4669            Ok(())
 4670        }))
 4671    }
 4672
 4673    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4674        let mut context_menu = self.context_menu.write();
 4675        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4676            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4677                // Toggle if we're selecting the same one
 4678                *context_menu = None;
 4679                cx.notify();
 4680                return;
 4681            } else {
 4682                // Otherwise, clear it and start a new one
 4683                *context_menu = None;
 4684                cx.notify();
 4685            }
 4686        }
 4687        drop(context_menu);
 4688        let snapshot = self.snapshot(cx);
 4689        let deployed_from_indicator = action.deployed_from_indicator;
 4690        let mut task = self.code_actions_task.take();
 4691        let action = action.clone();
 4692        cx.spawn(|editor, mut cx| async move {
 4693            while let Some(prev_task) = task {
 4694                prev_task.await.log_err();
 4695                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4696            }
 4697
 4698            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4699                if editor.focus_handle.is_focused(cx) {
 4700                    let multibuffer_point = action
 4701                        .deployed_from_indicator
 4702                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4703                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4704                    let (buffer, buffer_row) = snapshot
 4705                        .buffer_snapshot
 4706                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4707                        .and_then(|(buffer_snapshot, range)| {
 4708                            editor
 4709                                .buffer
 4710                                .read(cx)
 4711                                .buffer(buffer_snapshot.remote_id())
 4712                                .map(|buffer| (buffer, range.start.row))
 4713                        })?;
 4714                    let (_, code_actions) = editor
 4715                        .available_code_actions
 4716                        .clone()
 4717                        .and_then(|(location, code_actions)| {
 4718                            let snapshot = location.buffer.read(cx).snapshot();
 4719                            let point_range = location.range.to_point(&snapshot);
 4720                            let point_range = point_range.start.row..=point_range.end.row;
 4721                            if point_range.contains(&buffer_row) {
 4722                                Some((location, code_actions))
 4723                            } else {
 4724                                None
 4725                            }
 4726                        })
 4727                        .unzip();
 4728                    let buffer_id = buffer.read(cx).remote_id();
 4729                    let tasks = editor
 4730                        .tasks
 4731                        .get(&(buffer_id, buffer_row))
 4732                        .map(|t| Arc::new(t.to_owned()));
 4733                    if tasks.is_none() && code_actions.is_none() {
 4734                        return None;
 4735                    }
 4736
 4737                    editor.completion_tasks.clear();
 4738                    editor.discard_inline_completion(false, cx);
 4739                    let task_context =
 4740                        tasks
 4741                            .as_ref()
 4742                            .zip(editor.project.clone())
 4743                            .map(|(tasks, project)| {
 4744                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4745                            });
 4746
 4747                    Some(cx.spawn(|editor, mut cx| async move {
 4748                        let task_context = match task_context {
 4749                            Some(task_context) => task_context.await,
 4750                            None => None,
 4751                        };
 4752                        let resolved_tasks =
 4753                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4754                                Arc::new(ResolvedTasks {
 4755                                    templates: tasks.resolve(&task_context).collect(),
 4756                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4757                                        multibuffer_point.row,
 4758                                        tasks.column,
 4759                                    )),
 4760                                })
 4761                            });
 4762                        let spawn_straight_away = resolved_tasks
 4763                            .as_ref()
 4764                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4765                            && code_actions
 4766                                .as_ref()
 4767                                .map_or(true, |actions| actions.is_empty());
 4768                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4769                            *editor.context_menu.write() =
 4770                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4771                                    buffer,
 4772                                    actions: CodeActionContents {
 4773                                        tasks: resolved_tasks,
 4774                                        actions: code_actions,
 4775                                    },
 4776                                    selected_item: Default::default(),
 4777                                    scroll_handle: UniformListScrollHandle::default(),
 4778                                    deployed_from_indicator,
 4779                                }));
 4780                            if spawn_straight_away {
 4781                                if let Some(task) = editor.confirm_code_action(
 4782                                    &ConfirmCodeAction { item_ix: Some(0) },
 4783                                    cx,
 4784                                ) {
 4785                                    cx.notify();
 4786                                    return task;
 4787                                }
 4788                            }
 4789                            cx.notify();
 4790                            Task::ready(Ok(()))
 4791                        }) {
 4792                            task.await
 4793                        } else {
 4794                            Ok(())
 4795                        }
 4796                    }))
 4797                } else {
 4798                    Some(Task::ready(Ok(())))
 4799                }
 4800            })?;
 4801            if let Some(task) = spawned_test_task {
 4802                task.await?;
 4803            }
 4804
 4805            Ok::<_, anyhow::Error>(())
 4806        })
 4807        .detach_and_log_err(cx);
 4808    }
 4809
 4810    pub fn confirm_code_action(
 4811        &mut self,
 4812        action: &ConfirmCodeAction,
 4813        cx: &mut ViewContext<Self>,
 4814    ) -> Option<Task<Result<()>>> {
 4815        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4816            menu
 4817        } else {
 4818            return None;
 4819        };
 4820        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4821        let action = actions_menu.actions.get(action_ix)?;
 4822        let title = action.label();
 4823        let buffer = actions_menu.buffer;
 4824        let workspace = self.workspace()?;
 4825
 4826        match action {
 4827            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4828                workspace.update(cx, |workspace, cx| {
 4829                    workspace::tasks::schedule_resolved_task(
 4830                        workspace,
 4831                        task_source_kind,
 4832                        resolved_task,
 4833                        false,
 4834                        cx,
 4835                    );
 4836
 4837                    Some(Task::ready(Ok(())))
 4838                })
 4839            }
 4840            CodeActionsItem::CodeAction {
 4841                excerpt_id,
 4842                action,
 4843                provider,
 4844            } => {
 4845                let apply_code_action =
 4846                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4847                let workspace = workspace.downgrade();
 4848                Some(cx.spawn(|editor, cx| async move {
 4849                    let project_transaction = apply_code_action.await?;
 4850                    Self::open_project_transaction(
 4851                        &editor,
 4852                        workspace,
 4853                        project_transaction,
 4854                        title,
 4855                        cx,
 4856                    )
 4857                    .await
 4858                }))
 4859            }
 4860        }
 4861    }
 4862
 4863    pub async fn open_project_transaction(
 4864        this: &WeakView<Editor>,
 4865        workspace: WeakView<Workspace>,
 4866        transaction: ProjectTransaction,
 4867        title: String,
 4868        mut cx: AsyncWindowContext,
 4869    ) -> Result<()> {
 4870        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4871        cx.update(|cx| {
 4872            entries.sort_unstable_by_key(|(buffer, _)| {
 4873                buffer.read(cx).file().map(|f| f.path().clone())
 4874            });
 4875        })?;
 4876
 4877        // If the project transaction's edits are all contained within this editor, then
 4878        // avoid opening a new editor to display them.
 4879
 4880        if let Some((buffer, transaction)) = entries.first() {
 4881            if entries.len() == 1 {
 4882                let excerpt = this.update(&mut cx, |editor, cx| {
 4883                    editor
 4884                        .buffer()
 4885                        .read(cx)
 4886                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4887                })?;
 4888                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4889                    if excerpted_buffer == *buffer {
 4890                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4891                            let excerpt_range = excerpt_range.to_offset(buffer);
 4892                            buffer
 4893                                .edited_ranges_for_transaction::<usize>(transaction)
 4894                                .all(|range| {
 4895                                    excerpt_range.start <= range.start
 4896                                        && excerpt_range.end >= range.end
 4897                                })
 4898                        })?;
 4899
 4900                        if all_edits_within_excerpt {
 4901                            return Ok(());
 4902                        }
 4903                    }
 4904                }
 4905            }
 4906        } else {
 4907            return Ok(());
 4908        }
 4909
 4910        let mut ranges_to_highlight = Vec::new();
 4911        let excerpt_buffer = cx.new_model(|cx| {
 4912            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4913            for (buffer_handle, transaction) in &entries {
 4914                let buffer = buffer_handle.read(cx);
 4915                ranges_to_highlight.extend(
 4916                    multibuffer.push_excerpts_with_context_lines(
 4917                        buffer_handle.clone(),
 4918                        buffer
 4919                            .edited_ranges_for_transaction::<usize>(transaction)
 4920                            .collect(),
 4921                        DEFAULT_MULTIBUFFER_CONTEXT,
 4922                        cx,
 4923                    ),
 4924                );
 4925            }
 4926            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4927            multibuffer
 4928        })?;
 4929
 4930        workspace.update(&mut cx, |workspace, cx| {
 4931            let project = workspace.project().clone();
 4932            let editor =
 4933                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4934            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4935            editor.update(cx, |editor, cx| {
 4936                editor.highlight_background::<Self>(
 4937                    &ranges_to_highlight,
 4938                    |theme| theme.editor_highlighted_line_background,
 4939                    cx,
 4940                );
 4941            });
 4942        })?;
 4943
 4944        Ok(())
 4945    }
 4946
 4947    pub fn clear_code_action_providers(&mut self) {
 4948        self.code_action_providers.clear();
 4949        self.available_code_actions.take();
 4950    }
 4951
 4952    pub fn push_code_action_provider(
 4953        &mut self,
 4954        provider: Arc<dyn CodeActionProvider>,
 4955        cx: &mut ViewContext<Self>,
 4956    ) {
 4957        self.code_action_providers.push(provider);
 4958        self.refresh_code_actions(cx);
 4959    }
 4960
 4961    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4962        let buffer = self.buffer.read(cx);
 4963        let newest_selection = self.selections.newest_anchor().clone();
 4964        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4965        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4966        if start_buffer != end_buffer {
 4967            return None;
 4968        }
 4969
 4970        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4971            cx.background_executor()
 4972                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4973                .await;
 4974
 4975            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4976                let providers = this.code_action_providers.clone();
 4977                let tasks = this
 4978                    .code_action_providers
 4979                    .iter()
 4980                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4981                    .collect::<Vec<_>>();
 4982                (providers, tasks)
 4983            })?;
 4984
 4985            let mut actions = Vec::new();
 4986            for (provider, provider_actions) in
 4987                providers.into_iter().zip(future::join_all(tasks).await)
 4988            {
 4989                if let Some(provider_actions) = provider_actions.log_err() {
 4990                    actions.extend(provider_actions.into_iter().map(|action| {
 4991                        AvailableCodeAction {
 4992                            excerpt_id: newest_selection.start.excerpt_id,
 4993                            action,
 4994                            provider: provider.clone(),
 4995                        }
 4996                    }));
 4997                }
 4998            }
 4999
 5000            this.update(&mut cx, |this, cx| {
 5001                this.available_code_actions = if actions.is_empty() {
 5002                    None
 5003                } else {
 5004                    Some((
 5005                        Location {
 5006                            buffer: start_buffer,
 5007                            range: start..end,
 5008                        },
 5009                        actions.into(),
 5010                    ))
 5011                };
 5012                cx.notify();
 5013            })
 5014        }));
 5015        None
 5016    }
 5017
 5018    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5019        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5020            self.show_git_blame_inline = false;
 5021
 5022            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5023                cx.background_executor().timer(delay).await;
 5024
 5025                this.update(&mut cx, |this, cx| {
 5026                    this.show_git_blame_inline = true;
 5027                    cx.notify();
 5028                })
 5029                .log_err();
 5030            }));
 5031        }
 5032    }
 5033
 5034    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5035        if self.pending_rename.is_some() {
 5036            return None;
 5037        }
 5038
 5039        let provider = self.semantics_provider.clone()?;
 5040        let buffer = self.buffer.read(cx);
 5041        let newest_selection = self.selections.newest_anchor().clone();
 5042        let cursor_position = newest_selection.head();
 5043        let (cursor_buffer, cursor_buffer_position) =
 5044            buffer.text_anchor_for_position(cursor_position, cx)?;
 5045        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5046        if cursor_buffer != tail_buffer {
 5047            return None;
 5048        }
 5049
 5050        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5051            cx.background_executor()
 5052                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5053                .await;
 5054
 5055            let highlights = if let Some(highlights) = cx
 5056                .update(|cx| {
 5057                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5058                })
 5059                .ok()
 5060                .flatten()
 5061            {
 5062                highlights.await.log_err()
 5063            } else {
 5064                None
 5065            };
 5066
 5067            if let Some(highlights) = highlights {
 5068                this.update(&mut cx, |this, cx| {
 5069                    if this.pending_rename.is_some() {
 5070                        return;
 5071                    }
 5072
 5073                    let buffer_id = cursor_position.buffer_id;
 5074                    let buffer = this.buffer.read(cx);
 5075                    if !buffer
 5076                        .text_anchor_for_position(cursor_position, cx)
 5077                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5078                    {
 5079                        return;
 5080                    }
 5081
 5082                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5083                    let mut write_ranges = Vec::new();
 5084                    let mut read_ranges = Vec::new();
 5085                    for highlight in highlights {
 5086                        for (excerpt_id, excerpt_range) in
 5087                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5088                        {
 5089                            let start = highlight
 5090                                .range
 5091                                .start
 5092                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5093                            let end = highlight
 5094                                .range
 5095                                .end
 5096                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5097                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5098                                continue;
 5099                            }
 5100
 5101                            let range = Anchor {
 5102                                buffer_id,
 5103                                excerpt_id,
 5104                                text_anchor: start,
 5105                            }..Anchor {
 5106                                buffer_id,
 5107                                excerpt_id,
 5108                                text_anchor: end,
 5109                            };
 5110                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5111                                write_ranges.push(range);
 5112                            } else {
 5113                                read_ranges.push(range);
 5114                            }
 5115                        }
 5116                    }
 5117
 5118                    this.highlight_background::<DocumentHighlightRead>(
 5119                        &read_ranges,
 5120                        |theme| theme.editor_document_highlight_read_background,
 5121                        cx,
 5122                    );
 5123                    this.highlight_background::<DocumentHighlightWrite>(
 5124                        &write_ranges,
 5125                        |theme| theme.editor_document_highlight_write_background,
 5126                        cx,
 5127                    );
 5128                    cx.notify();
 5129                })
 5130                .log_err();
 5131            }
 5132        }));
 5133        None
 5134    }
 5135
 5136    pub fn refresh_inline_completion(
 5137        &mut self,
 5138        debounce: bool,
 5139        user_requested: bool,
 5140        cx: &mut ViewContext<Self>,
 5141    ) -> Option<()> {
 5142        let provider = self.inline_completion_provider()?;
 5143        let cursor = self.selections.newest_anchor().head();
 5144        let (buffer, cursor_buffer_position) =
 5145            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5146
 5147        if !user_requested
 5148            && (!self.enable_inline_completions
 5149                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5150        {
 5151            self.discard_inline_completion(false, cx);
 5152            return None;
 5153        }
 5154
 5155        self.update_visible_inline_completion(cx);
 5156        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5157        Some(())
 5158    }
 5159
 5160    fn cycle_inline_completion(
 5161        &mut self,
 5162        direction: Direction,
 5163        cx: &mut ViewContext<Self>,
 5164    ) -> Option<()> {
 5165        let provider = self.inline_completion_provider()?;
 5166        let cursor = self.selections.newest_anchor().head();
 5167        let (buffer, cursor_buffer_position) =
 5168            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5169        if !self.enable_inline_completions
 5170            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5171        {
 5172            return None;
 5173        }
 5174
 5175        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5176        self.update_visible_inline_completion(cx);
 5177
 5178        Some(())
 5179    }
 5180
 5181    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5182        if !self.has_active_inline_completion(cx) {
 5183            self.refresh_inline_completion(false, true, cx);
 5184            return;
 5185        }
 5186
 5187        self.update_visible_inline_completion(cx);
 5188    }
 5189
 5190    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5191        self.show_cursor_names(cx);
 5192    }
 5193
 5194    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5195        self.show_cursor_names = true;
 5196        cx.notify();
 5197        cx.spawn(|this, mut cx| async move {
 5198            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5199            this.update(&mut cx, |this, cx| {
 5200                this.show_cursor_names = false;
 5201                cx.notify()
 5202            })
 5203            .ok()
 5204        })
 5205        .detach();
 5206    }
 5207
 5208    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5209        if self.has_active_inline_completion(cx) {
 5210            self.cycle_inline_completion(Direction::Next, cx);
 5211        } else {
 5212            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5213            if is_copilot_disabled {
 5214                cx.propagate();
 5215            }
 5216        }
 5217    }
 5218
 5219    pub fn previous_inline_completion(
 5220        &mut self,
 5221        _: &PreviousInlineCompletion,
 5222        cx: &mut ViewContext<Self>,
 5223    ) {
 5224        if self.has_active_inline_completion(cx) {
 5225            self.cycle_inline_completion(Direction::Prev, cx);
 5226        } else {
 5227            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5228            if is_copilot_disabled {
 5229                cx.propagate();
 5230            }
 5231        }
 5232    }
 5233
 5234    pub fn accept_inline_completion(
 5235        &mut self,
 5236        _: &AcceptInlineCompletion,
 5237        cx: &mut ViewContext<Self>,
 5238    ) {
 5239        let Some(completion) = self.take_active_inline_completion(cx) else {
 5240            return;
 5241        };
 5242        if let Some(provider) = self.inline_completion_provider() {
 5243            provider.accept(cx);
 5244        }
 5245
 5246        cx.emit(EditorEvent::InputHandled {
 5247            utf16_range_to_replace: None,
 5248            text: completion.text.to_string().into(),
 5249        });
 5250
 5251        if let Some(range) = completion.delete_range {
 5252            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5253        }
 5254        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5255        self.refresh_inline_completion(true, true, cx);
 5256        cx.notify();
 5257    }
 5258
 5259    pub fn accept_partial_inline_completion(
 5260        &mut self,
 5261        _: &AcceptPartialInlineCompletion,
 5262        cx: &mut ViewContext<Self>,
 5263    ) {
 5264        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5265            if let Some(completion) = self.take_active_inline_completion(cx) {
 5266                let mut partial_completion = completion
 5267                    .text
 5268                    .chars()
 5269                    .by_ref()
 5270                    .take_while(|c| c.is_alphabetic())
 5271                    .collect::<String>();
 5272                if partial_completion.is_empty() {
 5273                    partial_completion = completion
 5274                        .text
 5275                        .chars()
 5276                        .by_ref()
 5277                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5278                        .collect::<String>();
 5279                }
 5280
 5281                cx.emit(EditorEvent::InputHandled {
 5282                    utf16_range_to_replace: None,
 5283                    text: partial_completion.clone().into(),
 5284                });
 5285
 5286                if let Some(range) = completion.delete_range {
 5287                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5288                }
 5289                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5290
 5291                self.refresh_inline_completion(true, true, cx);
 5292                cx.notify();
 5293            }
 5294        }
 5295    }
 5296
 5297    fn discard_inline_completion(
 5298        &mut self,
 5299        should_report_inline_completion_event: bool,
 5300        cx: &mut ViewContext<Self>,
 5301    ) -> bool {
 5302        if let Some(provider) = self.inline_completion_provider() {
 5303            provider.discard(should_report_inline_completion_event, cx);
 5304        }
 5305
 5306        self.take_active_inline_completion(cx).is_some()
 5307    }
 5308
 5309    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5310        if let Some(completion) = self.active_inline_completion.as_ref() {
 5311            let buffer = self.buffer.read(cx).read(cx);
 5312            completion.position.is_valid(&buffer)
 5313        } else {
 5314            false
 5315        }
 5316    }
 5317
 5318    fn take_active_inline_completion(
 5319        &mut self,
 5320        cx: &mut ViewContext<Self>,
 5321    ) -> Option<CompletionState> {
 5322        let completion = self.active_inline_completion.take()?;
 5323        let render_inlay_ids = completion.render_inlay_ids.clone();
 5324        self.display_map.update(cx, |map, cx| {
 5325            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5326        });
 5327        let buffer = self.buffer.read(cx).read(cx);
 5328
 5329        if completion.position.is_valid(&buffer) {
 5330            Some(completion)
 5331        } else {
 5332            None
 5333        }
 5334    }
 5335
 5336    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5337        let selection = self.selections.newest_anchor();
 5338        let cursor = selection.head();
 5339
 5340        let excerpt_id = cursor.excerpt_id;
 5341
 5342        if self.context_menu.read().is_none()
 5343            && self.completion_tasks.is_empty()
 5344            && selection.start == selection.end
 5345        {
 5346            if let Some(provider) = self.inline_completion_provider() {
 5347                if let Some((buffer, cursor_buffer_position)) =
 5348                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5349                {
 5350                    if let Some(proposal) =
 5351                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5352                    {
 5353                        let mut to_remove = Vec::new();
 5354                        if let Some(completion) = self.active_inline_completion.take() {
 5355                            to_remove.extend(completion.render_inlay_ids.iter());
 5356                        }
 5357
 5358                        let to_add = proposal
 5359                            .inlays
 5360                            .iter()
 5361                            .filter_map(|inlay| {
 5362                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5363                                let id = post_inc(&mut self.next_inlay_id);
 5364                                match inlay {
 5365                                    InlayProposal::Hint(position, hint) => {
 5366                                        let position =
 5367                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5368                                        Some(Inlay::hint(id, position, hint))
 5369                                    }
 5370                                    InlayProposal::Suggestion(position, text) => {
 5371                                        let position =
 5372                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5373                                        Some(Inlay::suggestion(id, position, text.clone()))
 5374                                    }
 5375                                }
 5376                            })
 5377                            .collect_vec();
 5378
 5379                        self.active_inline_completion = Some(CompletionState {
 5380                            position: cursor,
 5381                            text: proposal.text,
 5382                            delete_range: proposal.delete_range.and_then(|range| {
 5383                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5384                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5385                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5386                                Some(start?..end?)
 5387                            }),
 5388                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5389                        });
 5390
 5391                        self.display_map
 5392                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5393
 5394                        cx.notify();
 5395                        return;
 5396                    }
 5397                }
 5398            }
 5399        }
 5400
 5401        self.discard_inline_completion(false, cx);
 5402    }
 5403
 5404    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5405        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5406    }
 5407
 5408    fn render_code_actions_indicator(
 5409        &self,
 5410        _style: &EditorStyle,
 5411        row: DisplayRow,
 5412        is_active: bool,
 5413        cx: &mut ViewContext<Self>,
 5414    ) -> Option<IconButton> {
 5415        if self.available_code_actions.is_some() {
 5416            Some(
 5417                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5418                    .shape(ui::IconButtonShape::Square)
 5419                    .icon_size(IconSize::XSmall)
 5420                    .icon_color(Color::Muted)
 5421                    .selected(is_active)
 5422                    .tooltip({
 5423                        let focus_handle = self.focus_handle.clone();
 5424                        move |cx| {
 5425                            Tooltip::for_action_in(
 5426                                "Toggle Code Actions",
 5427                                &ToggleCodeActions {
 5428                                    deployed_from_indicator: None,
 5429                                },
 5430                                &focus_handle,
 5431                                cx,
 5432                            )
 5433                        }
 5434                    })
 5435                    .on_click(cx.listener(move |editor, _e, cx| {
 5436                        editor.focus(cx);
 5437                        editor.toggle_code_actions(
 5438                            &ToggleCodeActions {
 5439                                deployed_from_indicator: Some(row),
 5440                            },
 5441                            cx,
 5442                        );
 5443                    })),
 5444            )
 5445        } else {
 5446            None
 5447        }
 5448    }
 5449
 5450    fn clear_tasks(&mut self) {
 5451        self.tasks.clear()
 5452    }
 5453
 5454    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5455        if self.tasks.insert(key, value).is_some() {
 5456            // This case should hopefully be rare, but just in case...
 5457            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5458        }
 5459    }
 5460
 5461    fn build_tasks_context(
 5462        project: &Model<Project>,
 5463        buffer: &Model<Buffer>,
 5464        buffer_row: u32,
 5465        tasks: &Arc<RunnableTasks>,
 5466        cx: &mut ViewContext<Self>,
 5467    ) -> Task<Option<task::TaskContext>> {
 5468        let position = Point::new(buffer_row, tasks.column);
 5469        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5470        let location = Location {
 5471            buffer: buffer.clone(),
 5472            range: range_start..range_start,
 5473        };
 5474        // Fill in the environmental variables from the tree-sitter captures
 5475        let mut captured_task_variables = TaskVariables::default();
 5476        for (capture_name, value) in tasks.extra_variables.clone() {
 5477            captured_task_variables.insert(
 5478                task::VariableName::Custom(capture_name.into()),
 5479                value.clone(),
 5480            );
 5481        }
 5482        project.update(cx, |project, cx| {
 5483            project.task_store().update(cx, |task_store, cx| {
 5484                task_store.task_context_for_location(captured_task_variables, location, cx)
 5485            })
 5486        })
 5487    }
 5488
 5489    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5490        let Some((workspace, _)) = self.workspace.clone() else {
 5491            return;
 5492        };
 5493        let Some(project) = self.project.clone() else {
 5494            return;
 5495        };
 5496
 5497        // Try to find a closest, enclosing node using tree-sitter that has a
 5498        // task
 5499        let Some((buffer, buffer_row, tasks)) = self
 5500            .find_enclosing_node_task(cx)
 5501            // Or find the task that's closest in row-distance.
 5502            .or_else(|| self.find_closest_task(cx))
 5503        else {
 5504            return;
 5505        };
 5506
 5507        let reveal_strategy = action.reveal;
 5508        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5509        cx.spawn(|_, mut cx| async move {
 5510            let context = task_context.await?;
 5511            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5512
 5513            let resolved = resolved_task.resolved.as_mut()?;
 5514            resolved.reveal = reveal_strategy;
 5515
 5516            workspace
 5517                .update(&mut cx, |workspace, cx| {
 5518                    workspace::tasks::schedule_resolved_task(
 5519                        workspace,
 5520                        task_source_kind,
 5521                        resolved_task,
 5522                        false,
 5523                        cx,
 5524                    );
 5525                })
 5526                .ok()
 5527        })
 5528        .detach();
 5529    }
 5530
 5531    fn find_closest_task(
 5532        &mut self,
 5533        cx: &mut ViewContext<Self>,
 5534    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5535        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5536
 5537        let ((buffer_id, row), tasks) = self
 5538            .tasks
 5539            .iter()
 5540            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5541
 5542        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5543        let tasks = Arc::new(tasks.to_owned());
 5544        Some((buffer, *row, tasks))
 5545    }
 5546
 5547    fn find_enclosing_node_task(
 5548        &mut self,
 5549        cx: &mut ViewContext<Self>,
 5550    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5551        let snapshot = self.buffer.read(cx).snapshot(cx);
 5552        let offset = self.selections.newest::<usize>(cx).head();
 5553        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5554        let buffer_id = excerpt.buffer().remote_id();
 5555
 5556        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5557        let mut cursor = layer.node().walk();
 5558
 5559        while cursor.goto_first_child_for_byte(offset).is_some() {
 5560            if cursor.node().end_byte() == offset {
 5561                cursor.goto_next_sibling();
 5562            }
 5563        }
 5564
 5565        // Ascend to the smallest ancestor that contains the range and has a task.
 5566        loop {
 5567            let node = cursor.node();
 5568            let node_range = node.byte_range();
 5569            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5570
 5571            // Check if this node contains our offset
 5572            if node_range.start <= offset && node_range.end >= offset {
 5573                // If it contains offset, check for task
 5574                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5575                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5576                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5577                }
 5578            }
 5579
 5580            if !cursor.goto_parent() {
 5581                break;
 5582            }
 5583        }
 5584        None
 5585    }
 5586
 5587    fn render_run_indicator(
 5588        &self,
 5589        _style: &EditorStyle,
 5590        is_active: bool,
 5591        row: DisplayRow,
 5592        cx: &mut ViewContext<Self>,
 5593    ) -> IconButton {
 5594        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5595            .shape(ui::IconButtonShape::Square)
 5596            .icon_size(IconSize::XSmall)
 5597            .icon_color(Color::Muted)
 5598            .selected(is_active)
 5599            .on_click(cx.listener(move |editor, _e, cx| {
 5600                editor.focus(cx);
 5601                editor.toggle_code_actions(
 5602                    &ToggleCodeActions {
 5603                        deployed_from_indicator: Some(row),
 5604                    },
 5605                    cx,
 5606                );
 5607            }))
 5608    }
 5609
 5610    pub fn context_menu_visible(&self) -> bool {
 5611        self.context_menu
 5612            .read()
 5613            .as_ref()
 5614            .map_or(false, |menu| menu.visible())
 5615    }
 5616
 5617    fn render_context_menu(
 5618        &self,
 5619        cursor_position: DisplayPoint,
 5620        style: &EditorStyle,
 5621        max_height: Pixels,
 5622        cx: &mut ViewContext<Editor>,
 5623    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5624        self.context_menu.read().as_ref().map(|menu| {
 5625            menu.render(
 5626                cursor_position,
 5627                style,
 5628                max_height,
 5629                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5630                cx,
 5631            )
 5632        })
 5633    }
 5634
 5635    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5636        cx.notify();
 5637        self.completion_tasks.clear();
 5638        let context_menu = self.context_menu.write().take();
 5639        if context_menu.is_some() {
 5640            self.update_visible_inline_completion(cx);
 5641        }
 5642        context_menu
 5643    }
 5644
 5645    pub fn insert_snippet(
 5646        &mut self,
 5647        insertion_ranges: &[Range<usize>],
 5648        snippet: Snippet,
 5649        cx: &mut ViewContext<Self>,
 5650    ) -> Result<()> {
 5651        struct Tabstop<T> {
 5652            is_end_tabstop: bool,
 5653            ranges: Vec<Range<T>>,
 5654        }
 5655
 5656        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5657            let snippet_text: Arc<str> = snippet.text.clone().into();
 5658            buffer.edit(
 5659                insertion_ranges
 5660                    .iter()
 5661                    .cloned()
 5662                    .map(|range| (range, snippet_text.clone())),
 5663                Some(AutoindentMode::EachLine),
 5664                cx,
 5665            );
 5666
 5667            let snapshot = &*buffer.read(cx);
 5668            let snippet = &snippet;
 5669            snippet
 5670                .tabstops
 5671                .iter()
 5672                .map(|tabstop| {
 5673                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5674                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5675                    });
 5676                    let mut tabstop_ranges = tabstop
 5677                        .iter()
 5678                        .flat_map(|tabstop_range| {
 5679                            let mut delta = 0_isize;
 5680                            insertion_ranges.iter().map(move |insertion_range| {
 5681                                let insertion_start = insertion_range.start as isize + delta;
 5682                                delta +=
 5683                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5684
 5685                                let start = ((insertion_start + tabstop_range.start) as usize)
 5686                                    .min(snapshot.len());
 5687                                let end = ((insertion_start + tabstop_range.end) as usize)
 5688                                    .min(snapshot.len());
 5689                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5690                            })
 5691                        })
 5692                        .collect::<Vec<_>>();
 5693                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5694
 5695                    Tabstop {
 5696                        is_end_tabstop,
 5697                        ranges: tabstop_ranges,
 5698                    }
 5699                })
 5700                .collect::<Vec<_>>()
 5701        });
 5702        if let Some(tabstop) = tabstops.first() {
 5703            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5704                s.select_ranges(tabstop.ranges.iter().cloned());
 5705            });
 5706
 5707            // If we're already at the last tabstop and it's at the end of the snippet,
 5708            // we're done, we don't need to keep the state around.
 5709            if !tabstop.is_end_tabstop {
 5710                let ranges = tabstops
 5711                    .into_iter()
 5712                    .map(|tabstop| tabstop.ranges)
 5713                    .collect::<Vec<_>>();
 5714                self.snippet_stack.push(SnippetState {
 5715                    active_index: 0,
 5716                    ranges,
 5717                });
 5718            }
 5719
 5720            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5721            if self.autoclose_regions.is_empty() {
 5722                let snapshot = self.buffer.read(cx).snapshot(cx);
 5723                for selection in &mut self.selections.all::<Point>(cx) {
 5724                    let selection_head = selection.head();
 5725                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5726                        continue;
 5727                    };
 5728
 5729                    let mut bracket_pair = None;
 5730                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5731                    let prev_chars = snapshot
 5732                        .reversed_chars_at(selection_head)
 5733                        .collect::<String>();
 5734                    for (pair, enabled) in scope.brackets() {
 5735                        if enabled
 5736                            && pair.close
 5737                            && prev_chars.starts_with(pair.start.as_str())
 5738                            && next_chars.starts_with(pair.end.as_str())
 5739                        {
 5740                            bracket_pair = Some(pair.clone());
 5741                            break;
 5742                        }
 5743                    }
 5744                    if let Some(pair) = bracket_pair {
 5745                        let start = snapshot.anchor_after(selection_head);
 5746                        let end = snapshot.anchor_after(selection_head);
 5747                        self.autoclose_regions.push(AutocloseRegion {
 5748                            selection_id: selection.id,
 5749                            range: start..end,
 5750                            pair,
 5751                        });
 5752                    }
 5753                }
 5754            }
 5755        }
 5756        Ok(())
 5757    }
 5758
 5759    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5760        self.move_to_snippet_tabstop(Bias::Right, cx)
 5761    }
 5762
 5763    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5764        self.move_to_snippet_tabstop(Bias::Left, cx)
 5765    }
 5766
 5767    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5768        if let Some(mut snippet) = self.snippet_stack.pop() {
 5769            match bias {
 5770                Bias::Left => {
 5771                    if snippet.active_index > 0 {
 5772                        snippet.active_index -= 1;
 5773                    } else {
 5774                        self.snippet_stack.push(snippet);
 5775                        return false;
 5776                    }
 5777                }
 5778                Bias::Right => {
 5779                    if snippet.active_index + 1 < snippet.ranges.len() {
 5780                        snippet.active_index += 1;
 5781                    } else {
 5782                        self.snippet_stack.push(snippet);
 5783                        return false;
 5784                    }
 5785                }
 5786            }
 5787            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5788                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5789                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5790                });
 5791                // If snippet state is not at the last tabstop, push it back on the stack
 5792                if snippet.active_index + 1 < snippet.ranges.len() {
 5793                    self.snippet_stack.push(snippet);
 5794                }
 5795                return true;
 5796            }
 5797        }
 5798
 5799        false
 5800    }
 5801
 5802    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5803        self.transact(cx, |this, cx| {
 5804            this.select_all(&SelectAll, cx);
 5805            this.insert("", cx);
 5806        });
 5807    }
 5808
 5809    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5810        self.transact(cx, |this, cx| {
 5811            this.select_autoclose_pair(cx);
 5812            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5813            if !this.linked_edit_ranges.is_empty() {
 5814                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5815                let snapshot = this.buffer.read(cx).snapshot(cx);
 5816
 5817                for selection in selections.iter() {
 5818                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5819                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5820                    if selection_start.buffer_id != selection_end.buffer_id {
 5821                        continue;
 5822                    }
 5823                    if let Some(ranges) =
 5824                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5825                    {
 5826                        for (buffer, entries) in ranges {
 5827                            linked_ranges.entry(buffer).or_default().extend(entries);
 5828                        }
 5829                    }
 5830                }
 5831            }
 5832
 5833            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5834            if !this.selections.line_mode {
 5835                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5836                for selection in &mut selections {
 5837                    if selection.is_empty() {
 5838                        let old_head = selection.head();
 5839                        let mut new_head =
 5840                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5841                                .to_point(&display_map);
 5842                        if let Some((buffer, line_buffer_range)) = display_map
 5843                            .buffer_snapshot
 5844                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5845                        {
 5846                            let indent_size =
 5847                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5848                            let indent_len = match indent_size.kind {
 5849                                IndentKind::Space => {
 5850                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5851                                }
 5852                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5853                            };
 5854                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5855                                let indent_len = indent_len.get();
 5856                                new_head = cmp::min(
 5857                                    new_head,
 5858                                    MultiBufferPoint::new(
 5859                                        old_head.row,
 5860                                        ((old_head.column - 1) / indent_len) * indent_len,
 5861                                    ),
 5862                                );
 5863                            }
 5864                        }
 5865
 5866                        selection.set_head(new_head, SelectionGoal::None);
 5867                    }
 5868                }
 5869            }
 5870
 5871            this.signature_help_state.set_backspace_pressed(true);
 5872            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5873            this.insert("", cx);
 5874            let empty_str: Arc<str> = Arc::from("");
 5875            for (buffer, edits) in linked_ranges {
 5876                let snapshot = buffer.read(cx).snapshot();
 5877                use text::ToPoint as TP;
 5878
 5879                let edits = edits
 5880                    .into_iter()
 5881                    .map(|range| {
 5882                        let end_point = TP::to_point(&range.end, &snapshot);
 5883                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5884
 5885                        if end_point == start_point {
 5886                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5887                                .saturating_sub(1);
 5888                            start_point = TP::to_point(&offset, &snapshot);
 5889                        };
 5890
 5891                        (start_point..end_point, empty_str.clone())
 5892                    })
 5893                    .sorted_by_key(|(range, _)| range.start)
 5894                    .collect::<Vec<_>>();
 5895                buffer.update(cx, |this, cx| {
 5896                    this.edit(edits, None, cx);
 5897                })
 5898            }
 5899            this.refresh_inline_completion(true, false, cx);
 5900            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5901        });
 5902    }
 5903
 5904    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5905        self.transact(cx, |this, cx| {
 5906            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5907                let line_mode = s.line_mode;
 5908                s.move_with(|map, selection| {
 5909                    if selection.is_empty() && !line_mode {
 5910                        let cursor = movement::right(map, selection.head());
 5911                        selection.end = cursor;
 5912                        selection.reversed = true;
 5913                        selection.goal = SelectionGoal::None;
 5914                    }
 5915                })
 5916            });
 5917            this.insert("", cx);
 5918            this.refresh_inline_completion(true, false, cx);
 5919        });
 5920    }
 5921
 5922    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5923        if self.move_to_prev_snippet_tabstop(cx) {
 5924            return;
 5925        }
 5926
 5927        self.outdent(&Outdent, cx);
 5928    }
 5929
 5930    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5931        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5932            return;
 5933        }
 5934
 5935        let mut selections = self.selections.all_adjusted(cx);
 5936        let buffer = self.buffer.read(cx);
 5937        let snapshot = buffer.snapshot(cx);
 5938        let rows_iter = selections.iter().map(|s| s.head().row);
 5939        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5940
 5941        let mut edits = Vec::new();
 5942        let mut prev_edited_row = 0;
 5943        let mut row_delta = 0;
 5944        for selection in &mut selections {
 5945            if selection.start.row != prev_edited_row {
 5946                row_delta = 0;
 5947            }
 5948            prev_edited_row = selection.end.row;
 5949
 5950            // If the selection is non-empty, then increase the indentation of the selected lines.
 5951            if !selection.is_empty() {
 5952                row_delta =
 5953                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5954                continue;
 5955            }
 5956
 5957            // If the selection is empty and the cursor is in the leading whitespace before the
 5958            // suggested indentation, then auto-indent the line.
 5959            let cursor = selection.head();
 5960            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5961            if let Some(suggested_indent) =
 5962                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5963            {
 5964                if cursor.column < suggested_indent.len
 5965                    && cursor.column <= current_indent.len
 5966                    && current_indent.len <= suggested_indent.len
 5967                {
 5968                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5969                    selection.end = selection.start;
 5970                    if row_delta == 0 {
 5971                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5972                            cursor.row,
 5973                            current_indent,
 5974                            suggested_indent,
 5975                        ));
 5976                        row_delta = suggested_indent.len - current_indent.len;
 5977                    }
 5978                    continue;
 5979                }
 5980            }
 5981
 5982            // Otherwise, insert a hard or soft tab.
 5983            let settings = buffer.settings_at(cursor, cx);
 5984            let tab_size = if settings.hard_tabs {
 5985                IndentSize::tab()
 5986            } else {
 5987                let tab_size = settings.tab_size.get();
 5988                let char_column = snapshot
 5989                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5990                    .flat_map(str::chars)
 5991                    .count()
 5992                    + row_delta as usize;
 5993                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5994                IndentSize::spaces(chars_to_next_tab_stop)
 5995            };
 5996            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5997            selection.end = selection.start;
 5998            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5999            row_delta += tab_size.len;
 6000        }
 6001
 6002        self.transact(cx, |this, cx| {
 6003            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6004            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6005            this.refresh_inline_completion(true, false, cx);
 6006        });
 6007    }
 6008
 6009    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6010        if self.read_only(cx) {
 6011            return;
 6012        }
 6013        let mut selections = self.selections.all::<Point>(cx);
 6014        let mut prev_edited_row = 0;
 6015        let mut row_delta = 0;
 6016        let mut edits = Vec::new();
 6017        let buffer = self.buffer.read(cx);
 6018        let snapshot = buffer.snapshot(cx);
 6019        for selection in &mut selections {
 6020            if selection.start.row != prev_edited_row {
 6021                row_delta = 0;
 6022            }
 6023            prev_edited_row = selection.end.row;
 6024
 6025            row_delta =
 6026                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6027        }
 6028
 6029        self.transact(cx, |this, cx| {
 6030            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6031            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6032        });
 6033    }
 6034
 6035    fn indent_selection(
 6036        buffer: &MultiBuffer,
 6037        snapshot: &MultiBufferSnapshot,
 6038        selection: &mut Selection<Point>,
 6039        edits: &mut Vec<(Range<Point>, String)>,
 6040        delta_for_start_row: u32,
 6041        cx: &AppContext,
 6042    ) -> u32 {
 6043        let settings = buffer.settings_at(selection.start, cx);
 6044        let tab_size = settings.tab_size.get();
 6045        let indent_kind = if settings.hard_tabs {
 6046            IndentKind::Tab
 6047        } else {
 6048            IndentKind::Space
 6049        };
 6050        let mut start_row = selection.start.row;
 6051        let mut end_row = selection.end.row + 1;
 6052
 6053        // If a selection ends at the beginning of a line, don't indent
 6054        // that last line.
 6055        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6056            end_row -= 1;
 6057        }
 6058
 6059        // Avoid re-indenting a row that has already been indented by a
 6060        // previous selection, but still update this selection's column
 6061        // to reflect that indentation.
 6062        if delta_for_start_row > 0 {
 6063            start_row += 1;
 6064            selection.start.column += delta_for_start_row;
 6065            if selection.end.row == selection.start.row {
 6066                selection.end.column += delta_for_start_row;
 6067            }
 6068        }
 6069
 6070        let mut delta_for_end_row = 0;
 6071        let has_multiple_rows = start_row + 1 != end_row;
 6072        for row in start_row..end_row {
 6073            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6074            let indent_delta = match (current_indent.kind, indent_kind) {
 6075                (IndentKind::Space, IndentKind::Space) => {
 6076                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6077                    IndentSize::spaces(columns_to_next_tab_stop)
 6078                }
 6079                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6080                (_, IndentKind::Tab) => IndentSize::tab(),
 6081            };
 6082
 6083            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6084                0
 6085            } else {
 6086                selection.start.column
 6087            };
 6088            let row_start = Point::new(row, start);
 6089            edits.push((
 6090                row_start..row_start,
 6091                indent_delta.chars().collect::<String>(),
 6092            ));
 6093
 6094            // Update this selection's endpoints to reflect the indentation.
 6095            if row == selection.start.row {
 6096                selection.start.column += indent_delta.len;
 6097            }
 6098            if row == selection.end.row {
 6099                selection.end.column += indent_delta.len;
 6100                delta_for_end_row = indent_delta.len;
 6101            }
 6102        }
 6103
 6104        if selection.start.row == selection.end.row {
 6105            delta_for_start_row + delta_for_end_row
 6106        } else {
 6107            delta_for_end_row
 6108        }
 6109    }
 6110
 6111    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6112        if self.read_only(cx) {
 6113            return;
 6114        }
 6115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6116        let selections = self.selections.all::<Point>(cx);
 6117        let mut deletion_ranges = Vec::new();
 6118        let mut last_outdent = None;
 6119        {
 6120            let buffer = self.buffer.read(cx);
 6121            let snapshot = buffer.snapshot(cx);
 6122            for selection in &selections {
 6123                let settings = buffer.settings_at(selection.start, cx);
 6124                let tab_size = settings.tab_size.get();
 6125                let mut rows = selection.spanned_rows(false, &display_map);
 6126
 6127                // Avoid re-outdenting a row that has already been outdented by a
 6128                // previous selection.
 6129                if let Some(last_row) = last_outdent {
 6130                    if last_row == rows.start {
 6131                        rows.start = rows.start.next_row();
 6132                    }
 6133                }
 6134                let has_multiple_rows = rows.len() > 1;
 6135                for row in rows.iter_rows() {
 6136                    let indent_size = snapshot.indent_size_for_line(row);
 6137                    if indent_size.len > 0 {
 6138                        let deletion_len = match indent_size.kind {
 6139                            IndentKind::Space => {
 6140                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6141                                if columns_to_prev_tab_stop == 0 {
 6142                                    tab_size
 6143                                } else {
 6144                                    columns_to_prev_tab_stop
 6145                                }
 6146                            }
 6147                            IndentKind::Tab => 1,
 6148                        };
 6149                        let start = if has_multiple_rows
 6150                            || deletion_len > selection.start.column
 6151                            || indent_size.len < selection.start.column
 6152                        {
 6153                            0
 6154                        } else {
 6155                            selection.start.column - deletion_len
 6156                        };
 6157                        deletion_ranges.push(
 6158                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6159                        );
 6160                        last_outdent = Some(row);
 6161                    }
 6162                }
 6163            }
 6164        }
 6165
 6166        self.transact(cx, |this, cx| {
 6167            this.buffer.update(cx, |buffer, cx| {
 6168                let empty_str: Arc<str> = Arc::default();
 6169                buffer.edit(
 6170                    deletion_ranges
 6171                        .into_iter()
 6172                        .map(|range| (range, empty_str.clone())),
 6173                    None,
 6174                    cx,
 6175                );
 6176            });
 6177            let selections = this.selections.all::<usize>(cx);
 6178            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6179        });
 6180    }
 6181
 6182    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6183        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6184        let selections = self.selections.all::<Point>(cx);
 6185
 6186        let mut new_cursors = Vec::new();
 6187        let mut edit_ranges = Vec::new();
 6188        let mut selections = selections.iter().peekable();
 6189        while let Some(selection) = selections.next() {
 6190            let mut rows = selection.spanned_rows(false, &display_map);
 6191            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6192
 6193            // Accumulate contiguous regions of rows that we want to delete.
 6194            while let Some(next_selection) = selections.peek() {
 6195                let next_rows = next_selection.spanned_rows(false, &display_map);
 6196                if next_rows.start <= rows.end {
 6197                    rows.end = next_rows.end;
 6198                    selections.next().unwrap();
 6199                } else {
 6200                    break;
 6201                }
 6202            }
 6203
 6204            let buffer = &display_map.buffer_snapshot;
 6205            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6206            let edit_end;
 6207            let cursor_buffer_row;
 6208            if buffer.max_point().row >= rows.end.0 {
 6209                // If there's a line after the range, delete the \n from the end of the row range
 6210                // and position the cursor on the next line.
 6211                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6212                cursor_buffer_row = rows.end;
 6213            } else {
 6214                // If there isn't a line after the range, delete the \n from the line before the
 6215                // start of the row range and position the cursor there.
 6216                edit_start = edit_start.saturating_sub(1);
 6217                edit_end = buffer.len();
 6218                cursor_buffer_row = rows.start.previous_row();
 6219            }
 6220
 6221            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6222            *cursor.column_mut() =
 6223                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6224
 6225            new_cursors.push((
 6226                selection.id,
 6227                buffer.anchor_after(cursor.to_point(&display_map)),
 6228            ));
 6229            edit_ranges.push(edit_start..edit_end);
 6230        }
 6231
 6232        self.transact(cx, |this, cx| {
 6233            let buffer = this.buffer.update(cx, |buffer, cx| {
 6234                let empty_str: Arc<str> = Arc::default();
 6235                buffer.edit(
 6236                    edit_ranges
 6237                        .into_iter()
 6238                        .map(|range| (range, empty_str.clone())),
 6239                    None,
 6240                    cx,
 6241                );
 6242                buffer.snapshot(cx)
 6243            });
 6244            let new_selections = new_cursors
 6245                .into_iter()
 6246                .map(|(id, cursor)| {
 6247                    let cursor = cursor.to_point(&buffer);
 6248                    Selection {
 6249                        id,
 6250                        start: cursor,
 6251                        end: cursor,
 6252                        reversed: false,
 6253                        goal: SelectionGoal::None,
 6254                    }
 6255                })
 6256                .collect();
 6257
 6258            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6259                s.select(new_selections);
 6260            });
 6261        });
 6262    }
 6263
 6264    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6265        if self.read_only(cx) {
 6266            return;
 6267        }
 6268        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6269        for selection in self.selections.all::<Point>(cx) {
 6270            let start = MultiBufferRow(selection.start.row);
 6271            let end = if selection.start.row == selection.end.row {
 6272                MultiBufferRow(selection.start.row + 1)
 6273            } else {
 6274                MultiBufferRow(selection.end.row)
 6275            };
 6276
 6277            if let Some(last_row_range) = row_ranges.last_mut() {
 6278                if start <= last_row_range.end {
 6279                    last_row_range.end = end;
 6280                    continue;
 6281                }
 6282            }
 6283            row_ranges.push(start..end);
 6284        }
 6285
 6286        let snapshot = self.buffer.read(cx).snapshot(cx);
 6287        let mut cursor_positions = Vec::new();
 6288        for row_range in &row_ranges {
 6289            let anchor = snapshot.anchor_before(Point::new(
 6290                row_range.end.previous_row().0,
 6291                snapshot.line_len(row_range.end.previous_row()),
 6292            ));
 6293            cursor_positions.push(anchor..anchor);
 6294        }
 6295
 6296        self.transact(cx, |this, cx| {
 6297            for row_range in row_ranges.into_iter().rev() {
 6298                for row in row_range.iter_rows().rev() {
 6299                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6300                    let next_line_row = row.next_row();
 6301                    let indent = snapshot.indent_size_for_line(next_line_row);
 6302                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6303
 6304                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6305                        " "
 6306                    } else {
 6307                        ""
 6308                    };
 6309
 6310                    this.buffer.update(cx, |buffer, cx| {
 6311                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6312                    });
 6313                }
 6314            }
 6315
 6316            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6317                s.select_anchor_ranges(cursor_positions)
 6318            });
 6319        });
 6320    }
 6321
 6322    pub fn sort_lines_case_sensitive(
 6323        &mut self,
 6324        _: &SortLinesCaseSensitive,
 6325        cx: &mut ViewContext<Self>,
 6326    ) {
 6327        self.manipulate_lines(cx, |lines| lines.sort())
 6328    }
 6329
 6330    pub fn sort_lines_case_insensitive(
 6331        &mut self,
 6332        _: &SortLinesCaseInsensitive,
 6333        cx: &mut ViewContext<Self>,
 6334    ) {
 6335        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6336    }
 6337
 6338    pub fn unique_lines_case_insensitive(
 6339        &mut self,
 6340        _: &UniqueLinesCaseInsensitive,
 6341        cx: &mut ViewContext<Self>,
 6342    ) {
 6343        self.manipulate_lines(cx, |lines| {
 6344            let mut seen = HashSet::default();
 6345            lines.retain(|line| seen.insert(line.to_lowercase()));
 6346        })
 6347    }
 6348
 6349    pub fn unique_lines_case_sensitive(
 6350        &mut self,
 6351        _: &UniqueLinesCaseSensitive,
 6352        cx: &mut ViewContext<Self>,
 6353    ) {
 6354        self.manipulate_lines(cx, |lines| {
 6355            let mut seen = HashSet::default();
 6356            lines.retain(|line| seen.insert(*line));
 6357        })
 6358    }
 6359
 6360    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6361        let mut revert_changes = HashMap::default();
 6362        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6363        for hunk in hunks_for_rows(
 6364            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6365            &multi_buffer_snapshot,
 6366        ) {
 6367            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6368        }
 6369        if !revert_changes.is_empty() {
 6370            self.transact(cx, |editor, cx| {
 6371                editor.revert(revert_changes, cx);
 6372            });
 6373        }
 6374    }
 6375
 6376    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6377        let Some(project) = self.project.clone() else {
 6378            return;
 6379        };
 6380        self.reload(project, cx).detach_and_notify_err(cx);
 6381    }
 6382
 6383    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6384        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6385        if !revert_changes.is_empty() {
 6386            self.transact(cx, |editor, cx| {
 6387                editor.revert(revert_changes, cx);
 6388            });
 6389        }
 6390    }
 6391
 6392    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6393        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6394            let project_path = buffer.read(cx).project_path(cx)?;
 6395            let project = self.project.as_ref()?.read(cx);
 6396            let entry = project.entry_for_path(&project_path, cx)?;
 6397            let parent = match &entry.canonical_path {
 6398                Some(canonical_path) => canonical_path.to_path_buf(),
 6399                None => project.absolute_path(&project_path, cx)?,
 6400            }
 6401            .parent()?
 6402            .to_path_buf();
 6403            Some(parent)
 6404        }) {
 6405            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6406        }
 6407    }
 6408
 6409    fn gather_revert_changes(
 6410        &mut self,
 6411        selections: &[Selection<Anchor>],
 6412        cx: &mut ViewContext<'_, Editor>,
 6413    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6414        let mut revert_changes = HashMap::default();
 6415        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6416        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6417            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6418        }
 6419        revert_changes
 6420    }
 6421
 6422    pub fn prepare_revert_change(
 6423        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6424        multi_buffer: &Model<MultiBuffer>,
 6425        hunk: &MultiBufferDiffHunk,
 6426        cx: &AppContext,
 6427    ) -> Option<()> {
 6428        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6429        let buffer = buffer.read(cx);
 6430        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6431        let buffer_snapshot = buffer.snapshot();
 6432        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6433        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6434            probe
 6435                .0
 6436                .start
 6437                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6438                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6439        }) {
 6440            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6441            Some(())
 6442        } else {
 6443            None
 6444        }
 6445    }
 6446
 6447    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6448        self.manipulate_lines(cx, |lines| lines.reverse())
 6449    }
 6450
 6451    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6452        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6453    }
 6454
 6455    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6456    where
 6457        Fn: FnMut(&mut Vec<&str>),
 6458    {
 6459        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6460        let buffer = self.buffer.read(cx).snapshot(cx);
 6461
 6462        let mut edits = Vec::new();
 6463
 6464        let selections = self.selections.all::<Point>(cx);
 6465        let mut selections = selections.iter().peekable();
 6466        let mut contiguous_row_selections = Vec::new();
 6467        let mut new_selections = Vec::new();
 6468        let mut added_lines = 0;
 6469        let mut removed_lines = 0;
 6470
 6471        while let Some(selection) = selections.next() {
 6472            let (start_row, end_row) = consume_contiguous_rows(
 6473                &mut contiguous_row_selections,
 6474                selection,
 6475                &display_map,
 6476                &mut selections,
 6477            );
 6478
 6479            let start_point = Point::new(start_row.0, 0);
 6480            let end_point = Point::new(
 6481                end_row.previous_row().0,
 6482                buffer.line_len(end_row.previous_row()),
 6483            );
 6484            let text = buffer
 6485                .text_for_range(start_point..end_point)
 6486                .collect::<String>();
 6487
 6488            let mut lines = text.split('\n').collect_vec();
 6489
 6490            let lines_before = lines.len();
 6491            callback(&mut lines);
 6492            let lines_after = lines.len();
 6493
 6494            edits.push((start_point..end_point, lines.join("\n")));
 6495
 6496            // Selections must change based on added and removed line count
 6497            let start_row =
 6498                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6499            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6500            new_selections.push(Selection {
 6501                id: selection.id,
 6502                start: start_row,
 6503                end: end_row,
 6504                goal: SelectionGoal::None,
 6505                reversed: selection.reversed,
 6506            });
 6507
 6508            if lines_after > lines_before {
 6509                added_lines += lines_after - lines_before;
 6510            } else if lines_before > lines_after {
 6511                removed_lines += lines_before - lines_after;
 6512            }
 6513        }
 6514
 6515        self.transact(cx, |this, cx| {
 6516            let buffer = this.buffer.update(cx, |buffer, cx| {
 6517                buffer.edit(edits, None, cx);
 6518                buffer.snapshot(cx)
 6519            });
 6520
 6521            // Recalculate offsets on newly edited buffer
 6522            let new_selections = new_selections
 6523                .iter()
 6524                .map(|s| {
 6525                    let start_point = Point::new(s.start.0, 0);
 6526                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6527                    Selection {
 6528                        id: s.id,
 6529                        start: buffer.point_to_offset(start_point),
 6530                        end: buffer.point_to_offset(end_point),
 6531                        goal: s.goal,
 6532                        reversed: s.reversed,
 6533                    }
 6534                })
 6535                .collect();
 6536
 6537            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6538                s.select(new_selections);
 6539            });
 6540
 6541            this.request_autoscroll(Autoscroll::fit(), cx);
 6542        });
 6543    }
 6544
 6545    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6546        self.manipulate_text(cx, |text| text.to_uppercase())
 6547    }
 6548
 6549    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6550        self.manipulate_text(cx, |text| text.to_lowercase())
 6551    }
 6552
 6553    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6554        self.manipulate_text(cx, |text| {
 6555            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6556            // https://github.com/rutrum/convert-case/issues/16
 6557            text.split('\n')
 6558                .map(|line| line.to_case(Case::Title))
 6559                .join("\n")
 6560        })
 6561    }
 6562
 6563    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6564        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6565    }
 6566
 6567    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6568        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6569    }
 6570
 6571    pub fn convert_to_upper_camel_case(
 6572        &mut self,
 6573        _: &ConvertToUpperCamelCase,
 6574        cx: &mut ViewContext<Self>,
 6575    ) {
 6576        self.manipulate_text(cx, |text| {
 6577            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6578            // https://github.com/rutrum/convert-case/issues/16
 6579            text.split('\n')
 6580                .map(|line| line.to_case(Case::UpperCamel))
 6581                .join("\n")
 6582        })
 6583    }
 6584
 6585    pub fn convert_to_lower_camel_case(
 6586        &mut self,
 6587        _: &ConvertToLowerCamelCase,
 6588        cx: &mut ViewContext<Self>,
 6589    ) {
 6590        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6591    }
 6592
 6593    pub fn convert_to_opposite_case(
 6594        &mut self,
 6595        _: &ConvertToOppositeCase,
 6596        cx: &mut ViewContext<Self>,
 6597    ) {
 6598        self.manipulate_text(cx, |text| {
 6599            text.chars()
 6600                .fold(String::with_capacity(text.len()), |mut t, c| {
 6601                    if c.is_uppercase() {
 6602                        t.extend(c.to_lowercase());
 6603                    } else {
 6604                        t.extend(c.to_uppercase());
 6605                    }
 6606                    t
 6607                })
 6608        })
 6609    }
 6610
 6611    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6612    where
 6613        Fn: FnMut(&str) -> String,
 6614    {
 6615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6616        let buffer = self.buffer.read(cx).snapshot(cx);
 6617
 6618        let mut new_selections = Vec::new();
 6619        let mut edits = Vec::new();
 6620        let mut selection_adjustment = 0i32;
 6621
 6622        for selection in self.selections.all::<usize>(cx) {
 6623            let selection_is_empty = selection.is_empty();
 6624
 6625            let (start, end) = if selection_is_empty {
 6626                let word_range = movement::surrounding_word(
 6627                    &display_map,
 6628                    selection.start.to_display_point(&display_map),
 6629                );
 6630                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6631                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6632                (start, end)
 6633            } else {
 6634                (selection.start, selection.end)
 6635            };
 6636
 6637            let text = buffer.text_for_range(start..end).collect::<String>();
 6638            let old_length = text.len() as i32;
 6639            let text = callback(&text);
 6640
 6641            new_selections.push(Selection {
 6642                start: (start as i32 - selection_adjustment) as usize,
 6643                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6644                goal: SelectionGoal::None,
 6645                ..selection
 6646            });
 6647
 6648            selection_adjustment += old_length - text.len() as i32;
 6649
 6650            edits.push((start..end, text));
 6651        }
 6652
 6653        self.transact(cx, |this, cx| {
 6654            this.buffer.update(cx, |buffer, cx| {
 6655                buffer.edit(edits, None, cx);
 6656            });
 6657
 6658            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6659                s.select(new_selections);
 6660            });
 6661
 6662            this.request_autoscroll(Autoscroll::fit(), cx);
 6663        });
 6664    }
 6665
 6666    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6667        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6668        let buffer = &display_map.buffer_snapshot;
 6669        let selections = self.selections.all::<Point>(cx);
 6670
 6671        let mut edits = Vec::new();
 6672        let mut selections_iter = selections.iter().peekable();
 6673        while let Some(selection) = selections_iter.next() {
 6674            // Avoid duplicating the same lines twice.
 6675            let mut rows = selection.spanned_rows(false, &display_map);
 6676
 6677            while let Some(next_selection) = selections_iter.peek() {
 6678                let next_rows = next_selection.spanned_rows(false, &display_map);
 6679                if next_rows.start < rows.end {
 6680                    rows.end = next_rows.end;
 6681                    selections_iter.next().unwrap();
 6682                } else {
 6683                    break;
 6684                }
 6685            }
 6686
 6687            // Copy the text from the selected row region and splice it either at the start
 6688            // or end of the region.
 6689            let start = Point::new(rows.start.0, 0);
 6690            let end = Point::new(
 6691                rows.end.previous_row().0,
 6692                buffer.line_len(rows.end.previous_row()),
 6693            );
 6694            let text = buffer
 6695                .text_for_range(start..end)
 6696                .chain(Some("\n"))
 6697                .collect::<String>();
 6698            let insert_location = if upwards {
 6699                Point::new(rows.end.0, 0)
 6700            } else {
 6701                start
 6702            };
 6703            edits.push((insert_location..insert_location, text));
 6704        }
 6705
 6706        self.transact(cx, |this, cx| {
 6707            this.buffer.update(cx, |buffer, cx| {
 6708                buffer.edit(edits, None, cx);
 6709            });
 6710
 6711            this.request_autoscroll(Autoscroll::fit(), cx);
 6712        });
 6713    }
 6714
 6715    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6716        self.duplicate_line(true, cx);
 6717    }
 6718
 6719    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6720        self.duplicate_line(false, cx);
 6721    }
 6722
 6723    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6724        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6725        let buffer = self.buffer.read(cx).snapshot(cx);
 6726
 6727        let mut edits = Vec::new();
 6728        let mut unfold_ranges = Vec::new();
 6729        let mut refold_ranges = Vec::new();
 6730
 6731        let selections = self.selections.all::<Point>(cx);
 6732        let mut selections = selections.iter().peekable();
 6733        let mut contiguous_row_selections = Vec::new();
 6734        let mut new_selections = Vec::new();
 6735
 6736        while let Some(selection) = selections.next() {
 6737            // Find all the selections that span a contiguous row range
 6738            let (start_row, end_row) = consume_contiguous_rows(
 6739                &mut contiguous_row_selections,
 6740                selection,
 6741                &display_map,
 6742                &mut selections,
 6743            );
 6744
 6745            // Move the text spanned by the row range to be before the line preceding the row range
 6746            if start_row.0 > 0 {
 6747                let range_to_move = Point::new(
 6748                    start_row.previous_row().0,
 6749                    buffer.line_len(start_row.previous_row()),
 6750                )
 6751                    ..Point::new(
 6752                        end_row.previous_row().0,
 6753                        buffer.line_len(end_row.previous_row()),
 6754                    );
 6755                let insertion_point = display_map
 6756                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6757                    .0;
 6758
 6759                // Don't move lines across excerpts
 6760                if buffer
 6761                    .excerpt_boundaries_in_range((
 6762                        Bound::Excluded(insertion_point),
 6763                        Bound::Included(range_to_move.end),
 6764                    ))
 6765                    .next()
 6766                    .is_none()
 6767                {
 6768                    let text = buffer
 6769                        .text_for_range(range_to_move.clone())
 6770                        .flat_map(|s| s.chars())
 6771                        .skip(1)
 6772                        .chain(['\n'])
 6773                        .collect::<String>();
 6774
 6775                    edits.push((
 6776                        buffer.anchor_after(range_to_move.start)
 6777                            ..buffer.anchor_before(range_to_move.end),
 6778                        String::new(),
 6779                    ));
 6780                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6781                    edits.push((insertion_anchor..insertion_anchor, text));
 6782
 6783                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6784
 6785                    // Move selections up
 6786                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6787                        |mut selection| {
 6788                            selection.start.row -= row_delta;
 6789                            selection.end.row -= row_delta;
 6790                            selection
 6791                        },
 6792                    ));
 6793
 6794                    // Move folds up
 6795                    unfold_ranges.push(range_to_move.clone());
 6796                    for fold in display_map.folds_in_range(
 6797                        buffer.anchor_before(range_to_move.start)
 6798                            ..buffer.anchor_after(range_to_move.end),
 6799                    ) {
 6800                        let mut start = fold.range.start.to_point(&buffer);
 6801                        let mut end = fold.range.end.to_point(&buffer);
 6802                        start.row -= row_delta;
 6803                        end.row -= row_delta;
 6804                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6805                    }
 6806                }
 6807            }
 6808
 6809            // If we didn't move line(s), preserve the existing selections
 6810            new_selections.append(&mut contiguous_row_selections);
 6811        }
 6812
 6813        self.transact(cx, |this, cx| {
 6814            this.unfold_ranges(unfold_ranges, true, true, cx);
 6815            this.buffer.update(cx, |buffer, cx| {
 6816                for (range, text) in edits {
 6817                    buffer.edit([(range, text)], None, cx);
 6818                }
 6819            });
 6820            this.fold_ranges(refold_ranges, true, cx);
 6821            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6822                s.select(new_selections);
 6823            })
 6824        });
 6825    }
 6826
 6827    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6829        let buffer = self.buffer.read(cx).snapshot(cx);
 6830
 6831        let mut edits = Vec::new();
 6832        let mut unfold_ranges = Vec::new();
 6833        let mut refold_ranges = Vec::new();
 6834
 6835        let selections = self.selections.all::<Point>(cx);
 6836        let mut selections = selections.iter().peekable();
 6837        let mut contiguous_row_selections = Vec::new();
 6838        let mut new_selections = Vec::new();
 6839
 6840        while let Some(selection) = selections.next() {
 6841            // Find all the selections that span a contiguous row range
 6842            let (start_row, end_row) = consume_contiguous_rows(
 6843                &mut contiguous_row_selections,
 6844                selection,
 6845                &display_map,
 6846                &mut selections,
 6847            );
 6848
 6849            // Move the text spanned by the row range to be after the last line of the row range
 6850            if end_row.0 <= buffer.max_point().row {
 6851                let range_to_move =
 6852                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6853                let insertion_point = display_map
 6854                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6855                    .0;
 6856
 6857                // Don't move lines across excerpt boundaries
 6858                if buffer
 6859                    .excerpt_boundaries_in_range((
 6860                        Bound::Excluded(range_to_move.start),
 6861                        Bound::Included(insertion_point),
 6862                    ))
 6863                    .next()
 6864                    .is_none()
 6865                {
 6866                    let mut text = String::from("\n");
 6867                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6868                    text.pop(); // Drop trailing newline
 6869                    edits.push((
 6870                        buffer.anchor_after(range_to_move.start)
 6871                            ..buffer.anchor_before(range_to_move.end),
 6872                        String::new(),
 6873                    ));
 6874                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6875                    edits.push((insertion_anchor..insertion_anchor, text));
 6876
 6877                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6878
 6879                    // Move selections down
 6880                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6881                        |mut selection| {
 6882                            selection.start.row += row_delta;
 6883                            selection.end.row += row_delta;
 6884                            selection
 6885                        },
 6886                    ));
 6887
 6888                    // Move folds down
 6889                    unfold_ranges.push(range_to_move.clone());
 6890                    for fold in display_map.folds_in_range(
 6891                        buffer.anchor_before(range_to_move.start)
 6892                            ..buffer.anchor_after(range_to_move.end),
 6893                    ) {
 6894                        let mut start = fold.range.start.to_point(&buffer);
 6895                        let mut end = fold.range.end.to_point(&buffer);
 6896                        start.row += row_delta;
 6897                        end.row += row_delta;
 6898                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6899                    }
 6900                }
 6901            }
 6902
 6903            // If we didn't move line(s), preserve the existing selections
 6904            new_selections.append(&mut contiguous_row_selections);
 6905        }
 6906
 6907        self.transact(cx, |this, cx| {
 6908            this.unfold_ranges(unfold_ranges, true, true, cx);
 6909            this.buffer.update(cx, |buffer, cx| {
 6910                for (range, text) in edits {
 6911                    buffer.edit([(range, text)], None, cx);
 6912                }
 6913            });
 6914            this.fold_ranges(refold_ranges, true, cx);
 6915            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6916        });
 6917    }
 6918
 6919    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6920        let text_layout_details = &self.text_layout_details(cx);
 6921        self.transact(cx, |this, cx| {
 6922            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6923                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6924                let line_mode = s.line_mode;
 6925                s.move_with(|display_map, selection| {
 6926                    if !selection.is_empty() || line_mode {
 6927                        return;
 6928                    }
 6929
 6930                    let mut head = selection.head();
 6931                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6932                    if head.column() == display_map.line_len(head.row()) {
 6933                        transpose_offset = display_map
 6934                            .buffer_snapshot
 6935                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6936                    }
 6937
 6938                    if transpose_offset == 0 {
 6939                        return;
 6940                    }
 6941
 6942                    *head.column_mut() += 1;
 6943                    head = display_map.clip_point(head, Bias::Right);
 6944                    let goal = SelectionGoal::HorizontalPosition(
 6945                        display_map
 6946                            .x_for_display_point(head, text_layout_details)
 6947                            .into(),
 6948                    );
 6949                    selection.collapse_to(head, goal);
 6950
 6951                    let transpose_start = display_map
 6952                        .buffer_snapshot
 6953                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6954                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6955                        let transpose_end = display_map
 6956                            .buffer_snapshot
 6957                            .clip_offset(transpose_offset + 1, Bias::Right);
 6958                        if let Some(ch) =
 6959                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6960                        {
 6961                            edits.push((transpose_start..transpose_offset, String::new()));
 6962                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6963                        }
 6964                    }
 6965                });
 6966                edits
 6967            });
 6968            this.buffer
 6969                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6970            let selections = this.selections.all::<usize>(cx);
 6971            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6972                s.select(selections);
 6973            });
 6974        });
 6975    }
 6976
 6977    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6978        self.rewrap_impl(true, cx)
 6979    }
 6980
 6981    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6982        let buffer = self.buffer.read(cx).snapshot(cx);
 6983        let selections = self.selections.all::<Point>(cx);
 6984        let mut selections = selections.iter().peekable();
 6985
 6986        let mut edits = Vec::new();
 6987        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6988
 6989        while let Some(selection) = selections.next() {
 6990            let mut start_row = selection.start.row;
 6991            let mut end_row = selection.end.row;
 6992
 6993            // Skip selections that overlap with a range that has already been rewrapped.
 6994            let selection_range = start_row..end_row;
 6995            if rewrapped_row_ranges
 6996                .iter()
 6997                .any(|range| range.overlaps(&selection_range))
 6998            {
 6999                continue;
 7000            }
 7001
 7002            let mut should_rewrap = !only_text;
 7003
 7004            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7005                match language_scope.language_name().0.as_ref() {
 7006                    "Markdown" | "Plain Text" => {
 7007                        should_rewrap = true;
 7008                    }
 7009                    _ => {}
 7010                }
 7011            }
 7012
 7013            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7014
 7015            // Since not all lines in the selection may be at the same indent
 7016            // level, choose the indent size that is the most common between all
 7017            // of the lines.
 7018            //
 7019            // If there is a tie, we use the deepest indent.
 7020            let (indent_size, indent_end) = {
 7021                let mut indent_size_occurrences = HashMap::default();
 7022                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7023
 7024                for row in start_row..=end_row {
 7025                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7026                    rows_by_indent_size.entry(indent).or_default().push(row);
 7027                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7028                }
 7029
 7030                let indent_size = indent_size_occurrences
 7031                    .into_iter()
 7032                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7033                    .map(|(indent, _)| indent)
 7034                    .unwrap_or_default();
 7035                let row = rows_by_indent_size[&indent_size][0];
 7036                let indent_end = Point::new(row, indent_size.len);
 7037
 7038                (indent_size, indent_end)
 7039            };
 7040
 7041            let mut line_prefix = indent_size.chars().collect::<String>();
 7042
 7043            if let Some(comment_prefix) =
 7044                buffer
 7045                    .language_scope_at(selection.head())
 7046                    .and_then(|language| {
 7047                        language
 7048                            .line_comment_prefixes()
 7049                            .iter()
 7050                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7051                            .cloned()
 7052                    })
 7053            {
 7054                line_prefix.push_str(&comment_prefix);
 7055                should_rewrap = true;
 7056            }
 7057
 7058            if !should_rewrap {
 7059                continue;
 7060            }
 7061
 7062            if selection.is_empty() {
 7063                'expand_upwards: while start_row > 0 {
 7064                    let prev_row = start_row - 1;
 7065                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7066                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7067                    {
 7068                        start_row = prev_row;
 7069                    } else {
 7070                        break 'expand_upwards;
 7071                    }
 7072                }
 7073
 7074                'expand_downwards: while end_row < buffer.max_point().row {
 7075                    let next_row = end_row + 1;
 7076                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7077                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7078                    {
 7079                        end_row = next_row;
 7080                    } else {
 7081                        break 'expand_downwards;
 7082                    }
 7083                }
 7084            }
 7085
 7086            let start = Point::new(start_row, 0);
 7087            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7088            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7089            let Some(lines_without_prefixes) = selection_text
 7090                .lines()
 7091                .map(|line| {
 7092                    line.strip_prefix(&line_prefix)
 7093                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7094                        .ok_or_else(|| {
 7095                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7096                        })
 7097                })
 7098                .collect::<Result<Vec<_>, _>>()
 7099                .log_err()
 7100            else {
 7101                continue;
 7102            };
 7103
 7104            let wrap_column = buffer
 7105                .settings_at(Point::new(start_row, 0), cx)
 7106                .preferred_line_length as usize;
 7107            let wrapped_text = wrap_with_prefix(
 7108                line_prefix,
 7109                lines_without_prefixes.join(" "),
 7110                wrap_column,
 7111                tab_size,
 7112            );
 7113
 7114            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7115            let mut offset = start.to_offset(&buffer);
 7116            let mut moved_since_edit = true;
 7117
 7118            for change in diff.iter_all_changes() {
 7119                let value = change.value();
 7120                match change.tag() {
 7121                    ChangeTag::Equal => {
 7122                        offset += value.len();
 7123                        moved_since_edit = true;
 7124                    }
 7125                    ChangeTag::Delete => {
 7126                        let start = buffer.anchor_after(offset);
 7127                        let end = buffer.anchor_before(offset + value.len());
 7128
 7129                        if moved_since_edit {
 7130                            edits.push((start..end, String::new()));
 7131                        } else {
 7132                            edits.last_mut().unwrap().0.end = end;
 7133                        }
 7134
 7135                        offset += value.len();
 7136                        moved_since_edit = false;
 7137                    }
 7138                    ChangeTag::Insert => {
 7139                        if moved_since_edit {
 7140                            let anchor = buffer.anchor_after(offset);
 7141                            edits.push((anchor..anchor, value.to_string()));
 7142                        } else {
 7143                            edits.last_mut().unwrap().1.push_str(value);
 7144                        }
 7145
 7146                        moved_since_edit = false;
 7147                    }
 7148                }
 7149            }
 7150
 7151            rewrapped_row_ranges.push(start_row..=end_row);
 7152        }
 7153
 7154        self.buffer
 7155            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7156    }
 7157
 7158    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7159        let mut text = String::new();
 7160        let buffer = self.buffer.read(cx).snapshot(cx);
 7161        let mut selections = self.selections.all::<Point>(cx);
 7162        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7163        {
 7164            let max_point = buffer.max_point();
 7165            let mut is_first = true;
 7166            for selection in &mut selections {
 7167                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7168                if is_entire_line {
 7169                    selection.start = Point::new(selection.start.row, 0);
 7170                    if !selection.is_empty() && selection.end.column == 0 {
 7171                        selection.end = cmp::min(max_point, selection.end);
 7172                    } else {
 7173                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7174                    }
 7175                    selection.goal = SelectionGoal::None;
 7176                }
 7177                if is_first {
 7178                    is_first = false;
 7179                } else {
 7180                    text += "\n";
 7181                }
 7182                let mut len = 0;
 7183                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7184                    text.push_str(chunk);
 7185                    len += chunk.len();
 7186                }
 7187                clipboard_selections.push(ClipboardSelection {
 7188                    len,
 7189                    is_entire_line,
 7190                    first_line_indent: buffer
 7191                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7192                        .len,
 7193                });
 7194            }
 7195        }
 7196
 7197        self.transact(cx, |this, cx| {
 7198            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7199                s.select(selections);
 7200            });
 7201            this.insert("", cx);
 7202            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7203                text,
 7204                clipboard_selections,
 7205            ));
 7206        });
 7207    }
 7208
 7209    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7210        let selections = self.selections.all::<Point>(cx);
 7211        let buffer = self.buffer.read(cx).read(cx);
 7212        let mut text = String::new();
 7213
 7214        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7215        {
 7216            let max_point = buffer.max_point();
 7217            let mut is_first = true;
 7218            for selection in selections.iter() {
 7219                let mut start = selection.start;
 7220                let mut end = selection.end;
 7221                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7222                if is_entire_line {
 7223                    start = Point::new(start.row, 0);
 7224                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7225                }
 7226                if is_first {
 7227                    is_first = false;
 7228                } else {
 7229                    text += "\n";
 7230                }
 7231                let mut len = 0;
 7232                for chunk in buffer.text_for_range(start..end) {
 7233                    text.push_str(chunk);
 7234                    len += chunk.len();
 7235                }
 7236                clipboard_selections.push(ClipboardSelection {
 7237                    len,
 7238                    is_entire_line,
 7239                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7240                });
 7241            }
 7242        }
 7243
 7244        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7245            text,
 7246            clipboard_selections,
 7247        ));
 7248    }
 7249
 7250    pub fn do_paste(
 7251        &mut self,
 7252        text: &String,
 7253        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7254        handle_entire_lines: bool,
 7255        cx: &mut ViewContext<Self>,
 7256    ) {
 7257        if self.read_only(cx) {
 7258            return;
 7259        }
 7260
 7261        let clipboard_text = Cow::Borrowed(text);
 7262
 7263        self.transact(cx, |this, cx| {
 7264            if let Some(mut clipboard_selections) = clipboard_selections {
 7265                let old_selections = this.selections.all::<usize>(cx);
 7266                let all_selections_were_entire_line =
 7267                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7268                let first_selection_indent_column =
 7269                    clipboard_selections.first().map(|s| s.first_line_indent);
 7270                if clipboard_selections.len() != old_selections.len() {
 7271                    clipboard_selections.drain(..);
 7272                }
 7273                let cursor_offset = this.selections.last::<usize>(cx).head();
 7274                let mut auto_indent_on_paste = true;
 7275
 7276                this.buffer.update(cx, |buffer, cx| {
 7277                    let snapshot = buffer.read(cx);
 7278                    auto_indent_on_paste =
 7279                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7280
 7281                    let mut start_offset = 0;
 7282                    let mut edits = Vec::new();
 7283                    let mut original_indent_columns = Vec::new();
 7284                    for (ix, selection) in old_selections.iter().enumerate() {
 7285                        let to_insert;
 7286                        let entire_line;
 7287                        let original_indent_column;
 7288                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7289                            let end_offset = start_offset + clipboard_selection.len;
 7290                            to_insert = &clipboard_text[start_offset..end_offset];
 7291                            entire_line = clipboard_selection.is_entire_line;
 7292                            start_offset = end_offset + 1;
 7293                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7294                        } else {
 7295                            to_insert = clipboard_text.as_str();
 7296                            entire_line = all_selections_were_entire_line;
 7297                            original_indent_column = first_selection_indent_column
 7298                        }
 7299
 7300                        // If the corresponding selection was empty when this slice of the
 7301                        // clipboard text was written, then the entire line containing the
 7302                        // selection was copied. If this selection is also currently empty,
 7303                        // then paste the line before the current line of the buffer.
 7304                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7305                            let column = selection.start.to_point(&snapshot).column as usize;
 7306                            let line_start = selection.start - column;
 7307                            line_start..line_start
 7308                        } else {
 7309                            selection.range()
 7310                        };
 7311
 7312                        edits.push((range, to_insert));
 7313                        original_indent_columns.extend(original_indent_column);
 7314                    }
 7315                    drop(snapshot);
 7316
 7317                    buffer.edit(
 7318                        edits,
 7319                        if auto_indent_on_paste {
 7320                            Some(AutoindentMode::Block {
 7321                                original_indent_columns,
 7322                            })
 7323                        } else {
 7324                            None
 7325                        },
 7326                        cx,
 7327                    );
 7328                });
 7329
 7330                let selections = this.selections.all::<usize>(cx);
 7331                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7332            } else {
 7333                this.insert(&clipboard_text, cx);
 7334            }
 7335        });
 7336    }
 7337
 7338    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7339        if let Some(item) = cx.read_from_clipboard() {
 7340            let entries = item.entries();
 7341
 7342            match entries.first() {
 7343                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7344                // of all the pasted entries.
 7345                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7346                    .do_paste(
 7347                        clipboard_string.text(),
 7348                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7349                        true,
 7350                        cx,
 7351                    ),
 7352                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7353            }
 7354        }
 7355    }
 7356
 7357    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7358        if self.read_only(cx) {
 7359            return;
 7360        }
 7361
 7362        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7363            if let Some((selections, _)) =
 7364                self.selection_history.transaction(transaction_id).cloned()
 7365            {
 7366                self.change_selections(None, cx, |s| {
 7367                    s.select_anchors(selections.to_vec());
 7368                });
 7369            }
 7370            self.request_autoscroll(Autoscroll::fit(), cx);
 7371            self.unmark_text(cx);
 7372            self.refresh_inline_completion(true, false, cx);
 7373            cx.emit(EditorEvent::Edited { transaction_id });
 7374            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7375        }
 7376    }
 7377
 7378    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7379        if self.read_only(cx) {
 7380            return;
 7381        }
 7382
 7383        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7384            if let Some((_, Some(selections))) =
 7385                self.selection_history.transaction(transaction_id).cloned()
 7386            {
 7387                self.change_selections(None, cx, |s| {
 7388                    s.select_anchors(selections.to_vec());
 7389                });
 7390            }
 7391            self.request_autoscroll(Autoscroll::fit(), cx);
 7392            self.unmark_text(cx);
 7393            self.refresh_inline_completion(true, false, cx);
 7394            cx.emit(EditorEvent::Edited { transaction_id });
 7395        }
 7396    }
 7397
 7398    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7399        self.buffer
 7400            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7401    }
 7402
 7403    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7404        self.buffer
 7405            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7406    }
 7407
 7408    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7409        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7410            let line_mode = s.line_mode;
 7411            s.move_with(|map, selection| {
 7412                let cursor = if selection.is_empty() && !line_mode {
 7413                    movement::left(map, selection.start)
 7414                } else {
 7415                    selection.start
 7416                };
 7417                selection.collapse_to(cursor, SelectionGoal::None);
 7418            });
 7419        })
 7420    }
 7421
 7422    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7425        })
 7426    }
 7427
 7428    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7429        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7430            let line_mode = s.line_mode;
 7431            s.move_with(|map, selection| {
 7432                let cursor = if selection.is_empty() && !line_mode {
 7433                    movement::right(map, selection.end)
 7434                } else {
 7435                    selection.end
 7436                };
 7437                selection.collapse_to(cursor, SelectionGoal::None)
 7438            });
 7439        })
 7440    }
 7441
 7442    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7443        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7444            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7445        })
 7446    }
 7447
 7448    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7449        if self.take_rename(true, cx).is_some() {
 7450            return;
 7451        }
 7452
 7453        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7454            cx.propagate();
 7455            return;
 7456        }
 7457
 7458        let text_layout_details = &self.text_layout_details(cx);
 7459        let selection_count = self.selections.count();
 7460        let first_selection = self.selections.first_anchor();
 7461
 7462        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7463            let line_mode = s.line_mode;
 7464            s.move_with(|map, selection| {
 7465                if !selection.is_empty() && !line_mode {
 7466                    selection.goal = SelectionGoal::None;
 7467                }
 7468                let (cursor, goal) = movement::up(
 7469                    map,
 7470                    selection.start,
 7471                    selection.goal,
 7472                    false,
 7473                    text_layout_details,
 7474                );
 7475                selection.collapse_to(cursor, goal);
 7476            });
 7477        });
 7478
 7479        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7480        {
 7481            cx.propagate();
 7482        }
 7483    }
 7484
 7485    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7486        if self.take_rename(true, cx).is_some() {
 7487            return;
 7488        }
 7489
 7490        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7491            cx.propagate();
 7492            return;
 7493        }
 7494
 7495        let text_layout_details = &self.text_layout_details(cx);
 7496
 7497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7498            let line_mode = s.line_mode;
 7499            s.move_with(|map, selection| {
 7500                if !selection.is_empty() && !line_mode {
 7501                    selection.goal = SelectionGoal::None;
 7502                }
 7503                let (cursor, goal) = movement::up_by_rows(
 7504                    map,
 7505                    selection.start,
 7506                    action.lines,
 7507                    selection.goal,
 7508                    false,
 7509                    text_layout_details,
 7510                );
 7511                selection.collapse_to(cursor, goal);
 7512            });
 7513        })
 7514    }
 7515
 7516    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7517        if self.take_rename(true, cx).is_some() {
 7518            return;
 7519        }
 7520
 7521        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7522            cx.propagate();
 7523            return;
 7524        }
 7525
 7526        let text_layout_details = &self.text_layout_details(cx);
 7527
 7528        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7529            let line_mode = s.line_mode;
 7530            s.move_with(|map, selection| {
 7531                if !selection.is_empty() && !line_mode {
 7532                    selection.goal = SelectionGoal::None;
 7533                }
 7534                let (cursor, goal) = movement::down_by_rows(
 7535                    map,
 7536                    selection.start,
 7537                    action.lines,
 7538                    selection.goal,
 7539                    false,
 7540                    text_layout_details,
 7541                );
 7542                selection.collapse_to(cursor, goal);
 7543            });
 7544        })
 7545    }
 7546
 7547    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7548        let text_layout_details = &self.text_layout_details(cx);
 7549        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7550            s.move_heads_with(|map, head, goal| {
 7551                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7552            })
 7553        })
 7554    }
 7555
 7556    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7557        let text_layout_details = &self.text_layout_details(cx);
 7558        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7559            s.move_heads_with(|map, head, goal| {
 7560                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7561            })
 7562        })
 7563    }
 7564
 7565    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7566        let Some(row_count) = self.visible_row_count() else {
 7567            return;
 7568        };
 7569
 7570        let text_layout_details = &self.text_layout_details(cx);
 7571
 7572        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7573            s.move_heads_with(|map, head, goal| {
 7574                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7575            })
 7576        })
 7577    }
 7578
 7579    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7580        if self.take_rename(true, cx).is_some() {
 7581            return;
 7582        }
 7583
 7584        if self
 7585            .context_menu
 7586            .write()
 7587            .as_mut()
 7588            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7589            .unwrap_or(false)
 7590        {
 7591            return;
 7592        }
 7593
 7594        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7595            cx.propagate();
 7596            return;
 7597        }
 7598
 7599        let Some(row_count) = self.visible_row_count() else {
 7600            return;
 7601        };
 7602
 7603        let autoscroll = if action.center_cursor {
 7604            Autoscroll::center()
 7605        } else {
 7606            Autoscroll::fit()
 7607        };
 7608
 7609        let text_layout_details = &self.text_layout_details(cx);
 7610
 7611        self.change_selections(Some(autoscroll), cx, |s| {
 7612            let line_mode = s.line_mode;
 7613            s.move_with(|map, selection| {
 7614                if !selection.is_empty() && !line_mode {
 7615                    selection.goal = SelectionGoal::None;
 7616                }
 7617                let (cursor, goal) = movement::up_by_rows(
 7618                    map,
 7619                    selection.end,
 7620                    row_count,
 7621                    selection.goal,
 7622                    false,
 7623                    text_layout_details,
 7624                );
 7625                selection.collapse_to(cursor, goal);
 7626            });
 7627        });
 7628    }
 7629
 7630    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7631        let text_layout_details = &self.text_layout_details(cx);
 7632        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7633            s.move_heads_with(|map, head, goal| {
 7634                movement::up(map, head, goal, false, text_layout_details)
 7635            })
 7636        })
 7637    }
 7638
 7639    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7640        self.take_rename(true, cx);
 7641
 7642        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7643            cx.propagate();
 7644            return;
 7645        }
 7646
 7647        let text_layout_details = &self.text_layout_details(cx);
 7648        let selection_count = self.selections.count();
 7649        let first_selection = self.selections.first_anchor();
 7650
 7651        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7652            let line_mode = s.line_mode;
 7653            s.move_with(|map, selection| {
 7654                if !selection.is_empty() && !line_mode {
 7655                    selection.goal = SelectionGoal::None;
 7656                }
 7657                let (cursor, goal) = movement::down(
 7658                    map,
 7659                    selection.end,
 7660                    selection.goal,
 7661                    false,
 7662                    text_layout_details,
 7663                );
 7664                selection.collapse_to(cursor, goal);
 7665            });
 7666        });
 7667
 7668        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7669        {
 7670            cx.propagate();
 7671        }
 7672    }
 7673
 7674    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7675        let Some(row_count) = self.visible_row_count() else {
 7676            return;
 7677        };
 7678
 7679        let text_layout_details = &self.text_layout_details(cx);
 7680
 7681        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7682            s.move_heads_with(|map, head, goal| {
 7683                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7684            })
 7685        })
 7686    }
 7687
 7688    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7689        if self.take_rename(true, cx).is_some() {
 7690            return;
 7691        }
 7692
 7693        if self
 7694            .context_menu
 7695            .write()
 7696            .as_mut()
 7697            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7698            .unwrap_or(false)
 7699        {
 7700            return;
 7701        }
 7702
 7703        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7704            cx.propagate();
 7705            return;
 7706        }
 7707
 7708        let Some(row_count) = self.visible_row_count() else {
 7709            return;
 7710        };
 7711
 7712        let autoscroll = if action.center_cursor {
 7713            Autoscroll::center()
 7714        } else {
 7715            Autoscroll::fit()
 7716        };
 7717
 7718        let text_layout_details = &self.text_layout_details(cx);
 7719        self.change_selections(Some(autoscroll), cx, |s| {
 7720            let line_mode = s.line_mode;
 7721            s.move_with(|map, selection| {
 7722                if !selection.is_empty() && !line_mode {
 7723                    selection.goal = SelectionGoal::None;
 7724                }
 7725                let (cursor, goal) = movement::down_by_rows(
 7726                    map,
 7727                    selection.end,
 7728                    row_count,
 7729                    selection.goal,
 7730                    false,
 7731                    text_layout_details,
 7732                );
 7733                selection.collapse_to(cursor, goal);
 7734            });
 7735        });
 7736    }
 7737
 7738    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7739        let text_layout_details = &self.text_layout_details(cx);
 7740        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7741            s.move_heads_with(|map, head, goal| {
 7742                movement::down(map, head, goal, false, text_layout_details)
 7743            })
 7744        });
 7745    }
 7746
 7747    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7748        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7749            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7750        }
 7751    }
 7752
 7753    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7754        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7755            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7756        }
 7757    }
 7758
 7759    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7760        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7761            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7762        }
 7763    }
 7764
 7765    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7766        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7767            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7768        }
 7769    }
 7770
 7771    pub fn move_to_previous_word_start(
 7772        &mut self,
 7773        _: &MoveToPreviousWordStart,
 7774        cx: &mut ViewContext<Self>,
 7775    ) {
 7776        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7777            s.move_cursors_with(|map, head, _| {
 7778                (
 7779                    movement::previous_word_start(map, head),
 7780                    SelectionGoal::None,
 7781                )
 7782            });
 7783        })
 7784    }
 7785
 7786    pub fn move_to_previous_subword_start(
 7787        &mut self,
 7788        _: &MoveToPreviousSubwordStart,
 7789        cx: &mut ViewContext<Self>,
 7790    ) {
 7791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7792            s.move_cursors_with(|map, head, _| {
 7793                (
 7794                    movement::previous_subword_start(map, head),
 7795                    SelectionGoal::None,
 7796                )
 7797            });
 7798        })
 7799    }
 7800
 7801    pub fn select_to_previous_word_start(
 7802        &mut self,
 7803        _: &SelectToPreviousWordStart,
 7804        cx: &mut ViewContext<Self>,
 7805    ) {
 7806        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7807            s.move_heads_with(|map, head, _| {
 7808                (
 7809                    movement::previous_word_start(map, head),
 7810                    SelectionGoal::None,
 7811                )
 7812            });
 7813        })
 7814    }
 7815
 7816    pub fn select_to_previous_subword_start(
 7817        &mut self,
 7818        _: &SelectToPreviousSubwordStart,
 7819        cx: &mut ViewContext<Self>,
 7820    ) {
 7821        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7822            s.move_heads_with(|map, head, _| {
 7823                (
 7824                    movement::previous_subword_start(map, head),
 7825                    SelectionGoal::None,
 7826                )
 7827            });
 7828        })
 7829    }
 7830
 7831    pub fn delete_to_previous_word_start(
 7832        &mut self,
 7833        action: &DeleteToPreviousWordStart,
 7834        cx: &mut ViewContext<Self>,
 7835    ) {
 7836        self.transact(cx, |this, cx| {
 7837            this.select_autoclose_pair(cx);
 7838            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7839                let line_mode = s.line_mode;
 7840                s.move_with(|map, selection| {
 7841                    if selection.is_empty() && !line_mode {
 7842                        let cursor = if action.ignore_newlines {
 7843                            movement::previous_word_start(map, selection.head())
 7844                        } else {
 7845                            movement::previous_word_start_or_newline(map, selection.head())
 7846                        };
 7847                        selection.set_head(cursor, SelectionGoal::None);
 7848                    }
 7849                });
 7850            });
 7851            this.insert("", cx);
 7852        });
 7853    }
 7854
 7855    pub fn delete_to_previous_subword_start(
 7856        &mut self,
 7857        _: &DeleteToPreviousSubwordStart,
 7858        cx: &mut ViewContext<Self>,
 7859    ) {
 7860        self.transact(cx, |this, cx| {
 7861            this.select_autoclose_pair(cx);
 7862            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7863                let line_mode = s.line_mode;
 7864                s.move_with(|map, selection| {
 7865                    if selection.is_empty() && !line_mode {
 7866                        let cursor = movement::previous_subword_start(map, selection.head());
 7867                        selection.set_head(cursor, SelectionGoal::None);
 7868                    }
 7869                });
 7870            });
 7871            this.insert("", cx);
 7872        });
 7873    }
 7874
 7875    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7876        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7877            s.move_cursors_with(|map, head, _| {
 7878                (movement::next_word_end(map, head), SelectionGoal::None)
 7879            });
 7880        })
 7881    }
 7882
 7883    pub fn move_to_next_subword_end(
 7884        &mut self,
 7885        _: &MoveToNextSubwordEnd,
 7886        cx: &mut ViewContext<Self>,
 7887    ) {
 7888        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7889            s.move_cursors_with(|map, head, _| {
 7890                (movement::next_subword_end(map, head), SelectionGoal::None)
 7891            });
 7892        })
 7893    }
 7894
 7895    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7896        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897            s.move_heads_with(|map, head, _| {
 7898                (movement::next_word_end(map, head), SelectionGoal::None)
 7899            });
 7900        })
 7901    }
 7902
 7903    pub fn select_to_next_subword_end(
 7904        &mut self,
 7905        _: &SelectToNextSubwordEnd,
 7906        cx: &mut ViewContext<Self>,
 7907    ) {
 7908        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7909            s.move_heads_with(|map, head, _| {
 7910                (movement::next_subword_end(map, head), SelectionGoal::None)
 7911            });
 7912        })
 7913    }
 7914
 7915    pub fn delete_to_next_word_end(
 7916        &mut self,
 7917        action: &DeleteToNextWordEnd,
 7918        cx: &mut ViewContext<Self>,
 7919    ) {
 7920        self.transact(cx, |this, cx| {
 7921            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7922                let line_mode = s.line_mode;
 7923                s.move_with(|map, selection| {
 7924                    if selection.is_empty() && !line_mode {
 7925                        let cursor = if action.ignore_newlines {
 7926                            movement::next_word_end(map, selection.head())
 7927                        } else {
 7928                            movement::next_word_end_or_newline(map, selection.head())
 7929                        };
 7930                        selection.set_head(cursor, SelectionGoal::None);
 7931                    }
 7932                });
 7933            });
 7934            this.insert("", cx);
 7935        });
 7936    }
 7937
 7938    pub fn delete_to_next_subword_end(
 7939        &mut self,
 7940        _: &DeleteToNextSubwordEnd,
 7941        cx: &mut ViewContext<Self>,
 7942    ) {
 7943        self.transact(cx, |this, cx| {
 7944            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7945                s.move_with(|map, selection| {
 7946                    if selection.is_empty() {
 7947                        let cursor = movement::next_subword_end(map, selection.head());
 7948                        selection.set_head(cursor, SelectionGoal::None);
 7949                    }
 7950                });
 7951            });
 7952            this.insert("", cx);
 7953        });
 7954    }
 7955
 7956    pub fn move_to_beginning_of_line(
 7957        &mut self,
 7958        action: &MoveToBeginningOfLine,
 7959        cx: &mut ViewContext<Self>,
 7960    ) {
 7961        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7962            s.move_cursors_with(|map, head, _| {
 7963                (
 7964                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7965                    SelectionGoal::None,
 7966                )
 7967            });
 7968        })
 7969    }
 7970
 7971    pub fn select_to_beginning_of_line(
 7972        &mut self,
 7973        action: &SelectToBeginningOfLine,
 7974        cx: &mut ViewContext<Self>,
 7975    ) {
 7976        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7977            s.move_heads_with(|map, head, _| {
 7978                (
 7979                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7980                    SelectionGoal::None,
 7981                )
 7982            });
 7983        });
 7984    }
 7985
 7986    pub fn delete_to_beginning_of_line(
 7987        &mut self,
 7988        _: &DeleteToBeginningOfLine,
 7989        cx: &mut ViewContext<Self>,
 7990    ) {
 7991        self.transact(cx, |this, cx| {
 7992            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7993                s.move_with(|_, selection| {
 7994                    selection.reversed = true;
 7995                });
 7996            });
 7997
 7998            this.select_to_beginning_of_line(
 7999                &SelectToBeginningOfLine {
 8000                    stop_at_soft_wraps: false,
 8001                },
 8002                cx,
 8003            );
 8004            this.backspace(&Backspace, cx);
 8005        });
 8006    }
 8007
 8008    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8009        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8010            s.move_cursors_with(|map, head, _| {
 8011                (
 8012                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8013                    SelectionGoal::None,
 8014                )
 8015            });
 8016        })
 8017    }
 8018
 8019    pub fn select_to_end_of_line(
 8020        &mut self,
 8021        action: &SelectToEndOfLine,
 8022        cx: &mut ViewContext<Self>,
 8023    ) {
 8024        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8025            s.move_heads_with(|map, head, _| {
 8026                (
 8027                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8028                    SelectionGoal::None,
 8029                )
 8030            });
 8031        })
 8032    }
 8033
 8034    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8035        self.transact(cx, |this, cx| {
 8036            this.select_to_end_of_line(
 8037                &SelectToEndOfLine {
 8038                    stop_at_soft_wraps: false,
 8039                },
 8040                cx,
 8041            );
 8042            this.delete(&Delete, cx);
 8043        });
 8044    }
 8045
 8046    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8047        self.transact(cx, |this, cx| {
 8048            this.select_to_end_of_line(
 8049                &SelectToEndOfLine {
 8050                    stop_at_soft_wraps: false,
 8051                },
 8052                cx,
 8053            );
 8054            this.cut(&Cut, cx);
 8055        });
 8056    }
 8057
 8058    pub fn move_to_start_of_paragraph(
 8059        &mut self,
 8060        _: &MoveToStartOfParagraph,
 8061        cx: &mut ViewContext<Self>,
 8062    ) {
 8063        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8064            cx.propagate();
 8065            return;
 8066        }
 8067
 8068        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8069            s.move_with(|map, selection| {
 8070                selection.collapse_to(
 8071                    movement::start_of_paragraph(map, selection.head(), 1),
 8072                    SelectionGoal::None,
 8073                )
 8074            });
 8075        })
 8076    }
 8077
 8078    pub fn move_to_end_of_paragraph(
 8079        &mut self,
 8080        _: &MoveToEndOfParagraph,
 8081        cx: &mut ViewContext<Self>,
 8082    ) {
 8083        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8084            cx.propagate();
 8085            return;
 8086        }
 8087
 8088        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8089            s.move_with(|map, selection| {
 8090                selection.collapse_to(
 8091                    movement::end_of_paragraph(map, selection.head(), 1),
 8092                    SelectionGoal::None,
 8093                )
 8094            });
 8095        })
 8096    }
 8097
 8098    pub fn select_to_start_of_paragraph(
 8099        &mut self,
 8100        _: &SelectToStartOfParagraph,
 8101        cx: &mut ViewContext<Self>,
 8102    ) {
 8103        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8104            cx.propagate();
 8105            return;
 8106        }
 8107
 8108        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8109            s.move_heads_with(|map, head, _| {
 8110                (
 8111                    movement::start_of_paragraph(map, head, 1),
 8112                    SelectionGoal::None,
 8113                )
 8114            });
 8115        })
 8116    }
 8117
 8118    pub fn select_to_end_of_paragraph(
 8119        &mut self,
 8120        _: &SelectToEndOfParagraph,
 8121        cx: &mut ViewContext<Self>,
 8122    ) {
 8123        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8124            cx.propagate();
 8125            return;
 8126        }
 8127
 8128        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8129            s.move_heads_with(|map, head, _| {
 8130                (
 8131                    movement::end_of_paragraph(map, head, 1),
 8132                    SelectionGoal::None,
 8133                )
 8134            });
 8135        })
 8136    }
 8137
 8138    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8139        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8140            cx.propagate();
 8141            return;
 8142        }
 8143
 8144        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8145            s.select_ranges(vec![0..0]);
 8146        });
 8147    }
 8148
 8149    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8150        let mut selection = self.selections.last::<Point>(cx);
 8151        selection.set_head(Point::zero(), SelectionGoal::None);
 8152
 8153        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8154            s.select(vec![selection]);
 8155        });
 8156    }
 8157
 8158    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8159        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8160            cx.propagate();
 8161            return;
 8162        }
 8163
 8164        let cursor = self.buffer.read(cx).read(cx).len();
 8165        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8166            s.select_ranges(vec![cursor..cursor])
 8167        });
 8168    }
 8169
 8170    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8171        self.nav_history = nav_history;
 8172    }
 8173
 8174    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8175        self.nav_history.as_ref()
 8176    }
 8177
 8178    fn push_to_nav_history(
 8179        &mut self,
 8180        cursor_anchor: Anchor,
 8181        new_position: Option<Point>,
 8182        cx: &mut ViewContext<Self>,
 8183    ) {
 8184        if let Some(nav_history) = self.nav_history.as_mut() {
 8185            let buffer = self.buffer.read(cx).read(cx);
 8186            let cursor_position = cursor_anchor.to_point(&buffer);
 8187            let scroll_state = self.scroll_manager.anchor();
 8188            let scroll_top_row = scroll_state.top_row(&buffer);
 8189            drop(buffer);
 8190
 8191            if let Some(new_position) = new_position {
 8192                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8193                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8194                    return;
 8195                }
 8196            }
 8197
 8198            nav_history.push(
 8199                Some(NavigationData {
 8200                    cursor_anchor,
 8201                    cursor_position,
 8202                    scroll_anchor: scroll_state,
 8203                    scroll_top_row,
 8204                }),
 8205                cx,
 8206            );
 8207        }
 8208    }
 8209
 8210    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8211        let buffer = self.buffer.read(cx).snapshot(cx);
 8212        let mut selection = self.selections.first::<usize>(cx);
 8213        selection.set_head(buffer.len(), SelectionGoal::None);
 8214        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8215            s.select(vec![selection]);
 8216        });
 8217    }
 8218
 8219    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8220        let end = self.buffer.read(cx).read(cx).len();
 8221        self.change_selections(None, cx, |s| {
 8222            s.select_ranges(vec![0..end]);
 8223        });
 8224    }
 8225
 8226    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8227        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8228        let mut selections = self.selections.all::<Point>(cx);
 8229        let max_point = display_map.buffer_snapshot.max_point();
 8230        for selection in &mut selections {
 8231            let rows = selection.spanned_rows(true, &display_map);
 8232            selection.start = Point::new(rows.start.0, 0);
 8233            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8234            selection.reversed = false;
 8235        }
 8236        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8237            s.select(selections);
 8238        });
 8239    }
 8240
 8241    pub fn split_selection_into_lines(
 8242        &mut self,
 8243        _: &SplitSelectionIntoLines,
 8244        cx: &mut ViewContext<Self>,
 8245    ) {
 8246        let mut to_unfold = Vec::new();
 8247        let mut new_selection_ranges = Vec::new();
 8248        {
 8249            let selections = self.selections.all::<Point>(cx);
 8250            let buffer = self.buffer.read(cx).read(cx);
 8251            for selection in selections {
 8252                for row in selection.start.row..selection.end.row {
 8253                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8254                    new_selection_ranges.push(cursor..cursor);
 8255                }
 8256                new_selection_ranges.push(selection.end..selection.end);
 8257                to_unfold.push(selection.start..selection.end);
 8258            }
 8259        }
 8260        self.unfold_ranges(to_unfold, true, true, cx);
 8261        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8262            s.select_ranges(new_selection_ranges);
 8263        });
 8264    }
 8265
 8266    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8267        self.add_selection(true, cx);
 8268    }
 8269
 8270    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8271        self.add_selection(false, cx);
 8272    }
 8273
 8274    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8276        let mut selections = self.selections.all::<Point>(cx);
 8277        let text_layout_details = self.text_layout_details(cx);
 8278        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8279            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8280            let range = oldest_selection.display_range(&display_map).sorted();
 8281
 8282            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8283            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8284            let positions = start_x.min(end_x)..start_x.max(end_x);
 8285
 8286            selections.clear();
 8287            let mut stack = Vec::new();
 8288            for row in range.start.row().0..=range.end.row().0 {
 8289                if let Some(selection) = self.selections.build_columnar_selection(
 8290                    &display_map,
 8291                    DisplayRow(row),
 8292                    &positions,
 8293                    oldest_selection.reversed,
 8294                    &text_layout_details,
 8295                ) {
 8296                    stack.push(selection.id);
 8297                    selections.push(selection);
 8298                }
 8299            }
 8300
 8301            if above {
 8302                stack.reverse();
 8303            }
 8304
 8305            AddSelectionsState { above, stack }
 8306        });
 8307
 8308        let last_added_selection = *state.stack.last().unwrap();
 8309        let mut new_selections = Vec::new();
 8310        if above == state.above {
 8311            let end_row = if above {
 8312                DisplayRow(0)
 8313            } else {
 8314                display_map.max_point().row()
 8315            };
 8316
 8317            'outer: for selection in selections {
 8318                if selection.id == last_added_selection {
 8319                    let range = selection.display_range(&display_map).sorted();
 8320                    debug_assert_eq!(range.start.row(), range.end.row());
 8321                    let mut row = range.start.row();
 8322                    let positions =
 8323                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8324                            px(start)..px(end)
 8325                        } else {
 8326                            let start_x =
 8327                                display_map.x_for_display_point(range.start, &text_layout_details);
 8328                            let end_x =
 8329                                display_map.x_for_display_point(range.end, &text_layout_details);
 8330                            start_x.min(end_x)..start_x.max(end_x)
 8331                        };
 8332
 8333                    while row != end_row {
 8334                        if above {
 8335                            row.0 -= 1;
 8336                        } else {
 8337                            row.0 += 1;
 8338                        }
 8339
 8340                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8341                            &display_map,
 8342                            row,
 8343                            &positions,
 8344                            selection.reversed,
 8345                            &text_layout_details,
 8346                        ) {
 8347                            state.stack.push(new_selection.id);
 8348                            if above {
 8349                                new_selections.push(new_selection);
 8350                                new_selections.push(selection);
 8351                            } else {
 8352                                new_selections.push(selection);
 8353                                new_selections.push(new_selection);
 8354                            }
 8355
 8356                            continue 'outer;
 8357                        }
 8358                    }
 8359                }
 8360
 8361                new_selections.push(selection);
 8362            }
 8363        } else {
 8364            new_selections = selections;
 8365            new_selections.retain(|s| s.id != last_added_selection);
 8366            state.stack.pop();
 8367        }
 8368
 8369        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8370            s.select(new_selections);
 8371        });
 8372        if state.stack.len() > 1 {
 8373            self.add_selections_state = Some(state);
 8374        }
 8375    }
 8376
 8377    pub fn select_next_match_internal(
 8378        &mut self,
 8379        display_map: &DisplaySnapshot,
 8380        replace_newest: bool,
 8381        autoscroll: Option<Autoscroll>,
 8382        cx: &mut ViewContext<Self>,
 8383    ) -> Result<()> {
 8384        fn select_next_match_ranges(
 8385            this: &mut Editor,
 8386            range: Range<usize>,
 8387            replace_newest: bool,
 8388            auto_scroll: Option<Autoscroll>,
 8389            cx: &mut ViewContext<Editor>,
 8390        ) {
 8391            this.unfold_ranges([range.clone()], false, true, cx);
 8392            this.change_selections(auto_scroll, cx, |s| {
 8393                if replace_newest {
 8394                    s.delete(s.newest_anchor().id);
 8395                }
 8396                s.insert_range(range.clone());
 8397            });
 8398        }
 8399
 8400        let buffer = &display_map.buffer_snapshot;
 8401        let mut selections = self.selections.all::<usize>(cx);
 8402        if let Some(mut select_next_state) = self.select_next_state.take() {
 8403            let query = &select_next_state.query;
 8404            if !select_next_state.done {
 8405                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8406                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8407                let mut next_selected_range = None;
 8408
 8409                let bytes_after_last_selection =
 8410                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8411                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8412                let query_matches = query
 8413                    .stream_find_iter(bytes_after_last_selection)
 8414                    .map(|result| (last_selection.end, result))
 8415                    .chain(
 8416                        query
 8417                            .stream_find_iter(bytes_before_first_selection)
 8418                            .map(|result| (0, result)),
 8419                    );
 8420
 8421                for (start_offset, query_match) in query_matches {
 8422                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8423                    let offset_range =
 8424                        start_offset + query_match.start()..start_offset + query_match.end();
 8425                    let display_range = offset_range.start.to_display_point(display_map)
 8426                        ..offset_range.end.to_display_point(display_map);
 8427
 8428                    if !select_next_state.wordwise
 8429                        || (!movement::is_inside_word(display_map, display_range.start)
 8430                            && !movement::is_inside_word(display_map, display_range.end))
 8431                    {
 8432                        // TODO: This is n^2, because we might check all the selections
 8433                        if !selections
 8434                            .iter()
 8435                            .any(|selection| selection.range().overlaps(&offset_range))
 8436                        {
 8437                            next_selected_range = Some(offset_range);
 8438                            break;
 8439                        }
 8440                    }
 8441                }
 8442
 8443                if let Some(next_selected_range) = next_selected_range {
 8444                    select_next_match_ranges(
 8445                        self,
 8446                        next_selected_range,
 8447                        replace_newest,
 8448                        autoscroll,
 8449                        cx,
 8450                    );
 8451                } else {
 8452                    select_next_state.done = true;
 8453                }
 8454            }
 8455
 8456            self.select_next_state = Some(select_next_state);
 8457        } else {
 8458            let mut only_carets = true;
 8459            let mut same_text_selected = true;
 8460            let mut selected_text = None;
 8461
 8462            let mut selections_iter = selections.iter().peekable();
 8463            while let Some(selection) = selections_iter.next() {
 8464                if selection.start != selection.end {
 8465                    only_carets = false;
 8466                }
 8467
 8468                if same_text_selected {
 8469                    if selected_text.is_none() {
 8470                        selected_text =
 8471                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8472                    }
 8473
 8474                    if let Some(next_selection) = selections_iter.peek() {
 8475                        if next_selection.range().len() == selection.range().len() {
 8476                            let next_selected_text = buffer
 8477                                .text_for_range(next_selection.range())
 8478                                .collect::<String>();
 8479                            if Some(next_selected_text) != selected_text {
 8480                                same_text_selected = false;
 8481                                selected_text = None;
 8482                            }
 8483                        } else {
 8484                            same_text_selected = false;
 8485                            selected_text = None;
 8486                        }
 8487                    }
 8488                }
 8489            }
 8490
 8491            if only_carets {
 8492                for selection in &mut selections {
 8493                    let word_range = movement::surrounding_word(
 8494                        display_map,
 8495                        selection.start.to_display_point(display_map),
 8496                    );
 8497                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8498                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8499                    selection.goal = SelectionGoal::None;
 8500                    selection.reversed = false;
 8501                    select_next_match_ranges(
 8502                        self,
 8503                        selection.start..selection.end,
 8504                        replace_newest,
 8505                        autoscroll,
 8506                        cx,
 8507                    );
 8508                }
 8509
 8510                if selections.len() == 1 {
 8511                    let selection = selections
 8512                        .last()
 8513                        .expect("ensured that there's only one selection");
 8514                    let query = buffer
 8515                        .text_for_range(selection.start..selection.end)
 8516                        .collect::<String>();
 8517                    let is_empty = query.is_empty();
 8518                    let select_state = SelectNextState {
 8519                        query: AhoCorasick::new(&[query])?,
 8520                        wordwise: true,
 8521                        done: is_empty,
 8522                    };
 8523                    self.select_next_state = Some(select_state);
 8524                } else {
 8525                    self.select_next_state = None;
 8526                }
 8527            } else if let Some(selected_text) = selected_text {
 8528                self.select_next_state = Some(SelectNextState {
 8529                    query: AhoCorasick::new(&[selected_text])?,
 8530                    wordwise: false,
 8531                    done: false,
 8532                });
 8533                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8534            }
 8535        }
 8536        Ok(())
 8537    }
 8538
 8539    pub fn select_all_matches(
 8540        &mut self,
 8541        _action: &SelectAllMatches,
 8542        cx: &mut ViewContext<Self>,
 8543    ) -> Result<()> {
 8544        self.push_to_selection_history();
 8545        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8546
 8547        self.select_next_match_internal(&display_map, false, None, cx)?;
 8548        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8549            return Ok(());
 8550        };
 8551        if select_next_state.done {
 8552            return Ok(());
 8553        }
 8554
 8555        let mut new_selections = self.selections.all::<usize>(cx);
 8556
 8557        let buffer = &display_map.buffer_snapshot;
 8558        let query_matches = select_next_state
 8559            .query
 8560            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8561
 8562        for query_match in query_matches {
 8563            let query_match = query_match.unwrap(); // can only fail due to I/O
 8564            let offset_range = query_match.start()..query_match.end();
 8565            let display_range = offset_range.start.to_display_point(&display_map)
 8566                ..offset_range.end.to_display_point(&display_map);
 8567
 8568            if !select_next_state.wordwise
 8569                || (!movement::is_inside_word(&display_map, display_range.start)
 8570                    && !movement::is_inside_word(&display_map, display_range.end))
 8571            {
 8572                self.selections.change_with(cx, |selections| {
 8573                    new_selections.push(Selection {
 8574                        id: selections.new_selection_id(),
 8575                        start: offset_range.start,
 8576                        end: offset_range.end,
 8577                        reversed: false,
 8578                        goal: SelectionGoal::None,
 8579                    });
 8580                });
 8581            }
 8582        }
 8583
 8584        new_selections.sort_by_key(|selection| selection.start);
 8585        let mut ix = 0;
 8586        while ix + 1 < new_selections.len() {
 8587            let current_selection = &new_selections[ix];
 8588            let next_selection = &new_selections[ix + 1];
 8589            if current_selection.range().overlaps(&next_selection.range()) {
 8590                if current_selection.id < next_selection.id {
 8591                    new_selections.remove(ix + 1);
 8592                } else {
 8593                    new_selections.remove(ix);
 8594                }
 8595            } else {
 8596                ix += 1;
 8597            }
 8598        }
 8599
 8600        select_next_state.done = true;
 8601        self.unfold_ranges(
 8602            new_selections.iter().map(|selection| selection.range()),
 8603            false,
 8604            false,
 8605            cx,
 8606        );
 8607        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8608            selections.select(new_selections)
 8609        });
 8610
 8611        Ok(())
 8612    }
 8613
 8614    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8615        self.push_to_selection_history();
 8616        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8617        self.select_next_match_internal(
 8618            &display_map,
 8619            action.replace_newest,
 8620            Some(Autoscroll::newest()),
 8621            cx,
 8622        )?;
 8623        Ok(())
 8624    }
 8625
 8626    pub fn select_previous(
 8627        &mut self,
 8628        action: &SelectPrevious,
 8629        cx: &mut ViewContext<Self>,
 8630    ) -> Result<()> {
 8631        self.push_to_selection_history();
 8632        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8633        let buffer = &display_map.buffer_snapshot;
 8634        let mut selections = self.selections.all::<usize>(cx);
 8635        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8636            let query = &select_prev_state.query;
 8637            if !select_prev_state.done {
 8638                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8639                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8640                let mut next_selected_range = None;
 8641                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8642                let bytes_before_last_selection =
 8643                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8644                let bytes_after_first_selection =
 8645                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8646                let query_matches = query
 8647                    .stream_find_iter(bytes_before_last_selection)
 8648                    .map(|result| (last_selection.start, result))
 8649                    .chain(
 8650                        query
 8651                            .stream_find_iter(bytes_after_first_selection)
 8652                            .map(|result| (buffer.len(), result)),
 8653                    );
 8654                for (end_offset, query_match) in query_matches {
 8655                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8656                    let offset_range =
 8657                        end_offset - query_match.end()..end_offset - query_match.start();
 8658                    let display_range = offset_range.start.to_display_point(&display_map)
 8659                        ..offset_range.end.to_display_point(&display_map);
 8660
 8661                    if !select_prev_state.wordwise
 8662                        || (!movement::is_inside_word(&display_map, display_range.start)
 8663                            && !movement::is_inside_word(&display_map, display_range.end))
 8664                    {
 8665                        next_selected_range = Some(offset_range);
 8666                        break;
 8667                    }
 8668                }
 8669
 8670                if let Some(next_selected_range) = next_selected_range {
 8671                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8672                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8673                        if action.replace_newest {
 8674                            s.delete(s.newest_anchor().id);
 8675                        }
 8676                        s.insert_range(next_selected_range);
 8677                    });
 8678                } else {
 8679                    select_prev_state.done = true;
 8680                }
 8681            }
 8682
 8683            self.select_prev_state = Some(select_prev_state);
 8684        } else {
 8685            let mut only_carets = true;
 8686            let mut same_text_selected = true;
 8687            let mut selected_text = None;
 8688
 8689            let mut selections_iter = selections.iter().peekable();
 8690            while let Some(selection) = selections_iter.next() {
 8691                if selection.start != selection.end {
 8692                    only_carets = false;
 8693                }
 8694
 8695                if same_text_selected {
 8696                    if selected_text.is_none() {
 8697                        selected_text =
 8698                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8699                    }
 8700
 8701                    if let Some(next_selection) = selections_iter.peek() {
 8702                        if next_selection.range().len() == selection.range().len() {
 8703                            let next_selected_text = buffer
 8704                                .text_for_range(next_selection.range())
 8705                                .collect::<String>();
 8706                            if Some(next_selected_text) != selected_text {
 8707                                same_text_selected = false;
 8708                                selected_text = None;
 8709                            }
 8710                        } else {
 8711                            same_text_selected = false;
 8712                            selected_text = None;
 8713                        }
 8714                    }
 8715                }
 8716            }
 8717
 8718            if only_carets {
 8719                for selection in &mut selections {
 8720                    let word_range = movement::surrounding_word(
 8721                        &display_map,
 8722                        selection.start.to_display_point(&display_map),
 8723                    );
 8724                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8725                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8726                    selection.goal = SelectionGoal::None;
 8727                    selection.reversed = false;
 8728                }
 8729                if selections.len() == 1 {
 8730                    let selection = selections
 8731                        .last()
 8732                        .expect("ensured that there's only one selection");
 8733                    let query = buffer
 8734                        .text_for_range(selection.start..selection.end)
 8735                        .collect::<String>();
 8736                    let is_empty = query.is_empty();
 8737                    let select_state = SelectNextState {
 8738                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8739                        wordwise: true,
 8740                        done: is_empty,
 8741                    };
 8742                    self.select_prev_state = Some(select_state);
 8743                } else {
 8744                    self.select_prev_state = None;
 8745                }
 8746
 8747                self.unfold_ranges(
 8748                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8749                    false,
 8750                    true,
 8751                    cx,
 8752                );
 8753                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8754                    s.select(selections);
 8755                });
 8756            } else if let Some(selected_text) = selected_text {
 8757                self.select_prev_state = Some(SelectNextState {
 8758                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8759                    wordwise: false,
 8760                    done: false,
 8761                });
 8762                self.select_previous(action, cx)?;
 8763            }
 8764        }
 8765        Ok(())
 8766    }
 8767
 8768    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8769        let text_layout_details = &self.text_layout_details(cx);
 8770        self.transact(cx, |this, cx| {
 8771            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8772            let mut edits = Vec::new();
 8773            let mut selection_edit_ranges = Vec::new();
 8774            let mut last_toggled_row = None;
 8775            let snapshot = this.buffer.read(cx).read(cx);
 8776            let empty_str: Arc<str> = Arc::default();
 8777            let mut suffixes_inserted = Vec::new();
 8778            let ignore_indent = action.ignore_indent;
 8779
 8780            fn comment_prefix_range(
 8781                snapshot: &MultiBufferSnapshot,
 8782                row: MultiBufferRow,
 8783                comment_prefix: &str,
 8784                comment_prefix_whitespace: &str,
 8785                ignore_indent: bool,
 8786            ) -> Range<Point> {
 8787                let indent_size = if ignore_indent {
 8788                    0
 8789                } else {
 8790                    snapshot.indent_size_for_line(row).len
 8791                };
 8792
 8793                let start = Point::new(row.0, indent_size);
 8794
 8795                let mut line_bytes = snapshot
 8796                    .bytes_in_range(start..snapshot.max_point())
 8797                    .flatten()
 8798                    .copied();
 8799
 8800                // If this line currently begins with the line comment prefix, then record
 8801                // the range containing the prefix.
 8802                if line_bytes
 8803                    .by_ref()
 8804                    .take(comment_prefix.len())
 8805                    .eq(comment_prefix.bytes())
 8806                {
 8807                    // Include any whitespace that matches the comment prefix.
 8808                    let matching_whitespace_len = line_bytes
 8809                        .zip(comment_prefix_whitespace.bytes())
 8810                        .take_while(|(a, b)| a == b)
 8811                        .count() as u32;
 8812                    let end = Point::new(
 8813                        start.row,
 8814                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8815                    );
 8816                    start..end
 8817                } else {
 8818                    start..start
 8819                }
 8820            }
 8821
 8822            fn comment_suffix_range(
 8823                snapshot: &MultiBufferSnapshot,
 8824                row: MultiBufferRow,
 8825                comment_suffix: &str,
 8826                comment_suffix_has_leading_space: bool,
 8827            ) -> Range<Point> {
 8828                let end = Point::new(row.0, snapshot.line_len(row));
 8829                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8830
 8831                let mut line_end_bytes = snapshot
 8832                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8833                    .flatten()
 8834                    .copied();
 8835
 8836                let leading_space_len = if suffix_start_column > 0
 8837                    && line_end_bytes.next() == Some(b' ')
 8838                    && comment_suffix_has_leading_space
 8839                {
 8840                    1
 8841                } else {
 8842                    0
 8843                };
 8844
 8845                // If this line currently begins with the line comment prefix, then record
 8846                // the range containing the prefix.
 8847                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8848                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8849                    start..end
 8850                } else {
 8851                    end..end
 8852                }
 8853            }
 8854
 8855            // TODO: Handle selections that cross excerpts
 8856            for selection in &mut selections {
 8857                let start_column = snapshot
 8858                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8859                    .len;
 8860                let language = if let Some(language) =
 8861                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8862                {
 8863                    language
 8864                } else {
 8865                    continue;
 8866                };
 8867
 8868                selection_edit_ranges.clear();
 8869
 8870                // If multiple selections contain a given row, avoid processing that
 8871                // row more than once.
 8872                let mut start_row = MultiBufferRow(selection.start.row);
 8873                if last_toggled_row == Some(start_row) {
 8874                    start_row = start_row.next_row();
 8875                }
 8876                let end_row =
 8877                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8878                        MultiBufferRow(selection.end.row - 1)
 8879                    } else {
 8880                        MultiBufferRow(selection.end.row)
 8881                    };
 8882                last_toggled_row = Some(end_row);
 8883
 8884                if start_row > end_row {
 8885                    continue;
 8886                }
 8887
 8888                // If the language has line comments, toggle those.
 8889                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8890
 8891                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8892                if ignore_indent {
 8893                    full_comment_prefixes = full_comment_prefixes
 8894                        .into_iter()
 8895                        .map(|s| Arc::from(s.trim_end()))
 8896                        .collect();
 8897                }
 8898
 8899                if !full_comment_prefixes.is_empty() {
 8900                    let first_prefix = full_comment_prefixes
 8901                        .first()
 8902                        .expect("prefixes is non-empty");
 8903                    let prefix_trimmed_lengths = full_comment_prefixes
 8904                        .iter()
 8905                        .map(|p| p.trim_end_matches(' ').len())
 8906                        .collect::<SmallVec<[usize; 4]>>();
 8907
 8908                    let mut all_selection_lines_are_comments = true;
 8909
 8910                    for row in start_row.0..=end_row.0 {
 8911                        let row = MultiBufferRow(row);
 8912                        if start_row < end_row && snapshot.is_line_blank(row) {
 8913                            continue;
 8914                        }
 8915
 8916                        let prefix_range = full_comment_prefixes
 8917                            .iter()
 8918                            .zip(prefix_trimmed_lengths.iter().copied())
 8919                            .map(|(prefix, trimmed_prefix_len)| {
 8920                                comment_prefix_range(
 8921                                    snapshot.deref(),
 8922                                    row,
 8923                                    &prefix[..trimmed_prefix_len],
 8924                                    &prefix[trimmed_prefix_len..],
 8925                                    ignore_indent,
 8926                                )
 8927                            })
 8928                            .max_by_key(|range| range.end.column - range.start.column)
 8929                            .expect("prefixes is non-empty");
 8930
 8931                        if prefix_range.is_empty() {
 8932                            all_selection_lines_are_comments = false;
 8933                        }
 8934
 8935                        selection_edit_ranges.push(prefix_range);
 8936                    }
 8937
 8938                    if all_selection_lines_are_comments {
 8939                        edits.extend(
 8940                            selection_edit_ranges
 8941                                .iter()
 8942                                .cloned()
 8943                                .map(|range| (range, empty_str.clone())),
 8944                        );
 8945                    } else {
 8946                        let min_column = selection_edit_ranges
 8947                            .iter()
 8948                            .map(|range| range.start.column)
 8949                            .min()
 8950                            .unwrap_or(0);
 8951                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8952                            let position = Point::new(range.start.row, min_column);
 8953                            (position..position, first_prefix.clone())
 8954                        }));
 8955                    }
 8956                } else if let Some((full_comment_prefix, comment_suffix)) =
 8957                    language.block_comment_delimiters()
 8958                {
 8959                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8960                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8961                    let prefix_range = comment_prefix_range(
 8962                        snapshot.deref(),
 8963                        start_row,
 8964                        comment_prefix,
 8965                        comment_prefix_whitespace,
 8966                        ignore_indent,
 8967                    );
 8968                    let suffix_range = comment_suffix_range(
 8969                        snapshot.deref(),
 8970                        end_row,
 8971                        comment_suffix.trim_start_matches(' '),
 8972                        comment_suffix.starts_with(' '),
 8973                    );
 8974
 8975                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8976                        edits.push((
 8977                            prefix_range.start..prefix_range.start,
 8978                            full_comment_prefix.clone(),
 8979                        ));
 8980                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8981                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8982                    } else {
 8983                        edits.push((prefix_range, empty_str.clone()));
 8984                        edits.push((suffix_range, empty_str.clone()));
 8985                    }
 8986                } else {
 8987                    continue;
 8988                }
 8989            }
 8990
 8991            drop(snapshot);
 8992            this.buffer.update(cx, |buffer, cx| {
 8993                buffer.edit(edits, None, cx);
 8994            });
 8995
 8996            // Adjust selections so that they end before any comment suffixes that
 8997            // were inserted.
 8998            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8999            let mut selections = this.selections.all::<Point>(cx);
 9000            let snapshot = this.buffer.read(cx).read(cx);
 9001            for selection in &mut selections {
 9002                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9003                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9004                        Ordering::Less => {
 9005                            suffixes_inserted.next();
 9006                            continue;
 9007                        }
 9008                        Ordering::Greater => break,
 9009                        Ordering::Equal => {
 9010                            if selection.end.column == snapshot.line_len(row) {
 9011                                if selection.is_empty() {
 9012                                    selection.start.column -= suffix_len as u32;
 9013                                }
 9014                                selection.end.column -= suffix_len as u32;
 9015                            }
 9016                            break;
 9017                        }
 9018                    }
 9019                }
 9020            }
 9021
 9022            drop(snapshot);
 9023            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9024
 9025            let selections = this.selections.all::<Point>(cx);
 9026            let selections_on_single_row = selections.windows(2).all(|selections| {
 9027                selections[0].start.row == selections[1].start.row
 9028                    && selections[0].end.row == selections[1].end.row
 9029                    && selections[0].start.row == selections[0].end.row
 9030            });
 9031            let selections_selecting = selections
 9032                .iter()
 9033                .any(|selection| selection.start != selection.end);
 9034            let advance_downwards = action.advance_downwards
 9035                && selections_on_single_row
 9036                && !selections_selecting
 9037                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9038
 9039            if advance_downwards {
 9040                let snapshot = this.buffer.read(cx).snapshot(cx);
 9041
 9042                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9043                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9044                        let mut point = display_point.to_point(display_snapshot);
 9045                        point.row += 1;
 9046                        point = snapshot.clip_point(point, Bias::Left);
 9047                        let display_point = point.to_display_point(display_snapshot);
 9048                        let goal = SelectionGoal::HorizontalPosition(
 9049                            display_snapshot
 9050                                .x_for_display_point(display_point, text_layout_details)
 9051                                .into(),
 9052                        );
 9053                        (display_point, goal)
 9054                    })
 9055                });
 9056            }
 9057        });
 9058    }
 9059
 9060    pub fn select_enclosing_symbol(
 9061        &mut self,
 9062        _: &SelectEnclosingSymbol,
 9063        cx: &mut ViewContext<Self>,
 9064    ) {
 9065        let buffer = self.buffer.read(cx).snapshot(cx);
 9066        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9067
 9068        fn update_selection(
 9069            selection: &Selection<usize>,
 9070            buffer_snap: &MultiBufferSnapshot,
 9071        ) -> Option<Selection<usize>> {
 9072            let cursor = selection.head();
 9073            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9074            for symbol in symbols.iter().rev() {
 9075                let start = symbol.range.start.to_offset(buffer_snap);
 9076                let end = symbol.range.end.to_offset(buffer_snap);
 9077                let new_range = start..end;
 9078                if start < selection.start || end > selection.end {
 9079                    return Some(Selection {
 9080                        id: selection.id,
 9081                        start: new_range.start,
 9082                        end: new_range.end,
 9083                        goal: SelectionGoal::None,
 9084                        reversed: selection.reversed,
 9085                    });
 9086                }
 9087            }
 9088            None
 9089        }
 9090
 9091        let mut selected_larger_symbol = false;
 9092        let new_selections = old_selections
 9093            .iter()
 9094            .map(|selection| match update_selection(selection, &buffer) {
 9095                Some(new_selection) => {
 9096                    if new_selection.range() != selection.range() {
 9097                        selected_larger_symbol = true;
 9098                    }
 9099                    new_selection
 9100                }
 9101                None => selection.clone(),
 9102            })
 9103            .collect::<Vec<_>>();
 9104
 9105        if selected_larger_symbol {
 9106            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9107                s.select(new_selections);
 9108            });
 9109        }
 9110    }
 9111
 9112    pub fn select_larger_syntax_node(
 9113        &mut self,
 9114        _: &SelectLargerSyntaxNode,
 9115        cx: &mut ViewContext<Self>,
 9116    ) {
 9117        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9118        let buffer = self.buffer.read(cx).snapshot(cx);
 9119        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9120
 9121        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9122        let mut selected_larger_node = false;
 9123        let new_selections = old_selections
 9124            .iter()
 9125            .map(|selection| {
 9126                let old_range = selection.start..selection.end;
 9127                let mut new_range = old_range.clone();
 9128                while let Some(containing_range) =
 9129                    buffer.range_for_syntax_ancestor(new_range.clone())
 9130                {
 9131                    new_range = containing_range;
 9132                    if !display_map.intersects_fold(new_range.start)
 9133                        && !display_map.intersects_fold(new_range.end)
 9134                    {
 9135                        break;
 9136                    }
 9137                }
 9138
 9139                selected_larger_node |= new_range != old_range;
 9140                Selection {
 9141                    id: selection.id,
 9142                    start: new_range.start,
 9143                    end: new_range.end,
 9144                    goal: SelectionGoal::None,
 9145                    reversed: selection.reversed,
 9146                }
 9147            })
 9148            .collect::<Vec<_>>();
 9149
 9150        if selected_larger_node {
 9151            stack.push(old_selections);
 9152            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9153                s.select(new_selections);
 9154            });
 9155        }
 9156        self.select_larger_syntax_node_stack = stack;
 9157    }
 9158
 9159    pub fn select_smaller_syntax_node(
 9160        &mut self,
 9161        _: &SelectSmallerSyntaxNode,
 9162        cx: &mut ViewContext<Self>,
 9163    ) {
 9164        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9165        if let Some(selections) = stack.pop() {
 9166            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9167                s.select(selections.to_vec());
 9168            });
 9169        }
 9170        self.select_larger_syntax_node_stack = stack;
 9171    }
 9172
 9173    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9174        if !EditorSettings::get_global(cx).gutter.runnables {
 9175            self.clear_tasks();
 9176            return Task::ready(());
 9177        }
 9178        let project = self.project.clone();
 9179        cx.spawn(|this, mut cx| async move {
 9180            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9181                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9182            }) else {
 9183                return;
 9184            };
 9185
 9186            let Some(project) = project else {
 9187                return;
 9188            };
 9189
 9190            let hide_runnables = project
 9191                .update(&mut cx, |project, cx| {
 9192                    // Do not display any test indicators in non-dev server remote projects.
 9193                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9194                })
 9195                .unwrap_or(true);
 9196            if hide_runnables {
 9197                return;
 9198            }
 9199            let new_rows =
 9200                cx.background_executor()
 9201                    .spawn({
 9202                        let snapshot = display_snapshot.clone();
 9203                        async move {
 9204                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9205                        }
 9206                    })
 9207                    .await;
 9208            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9209
 9210            this.update(&mut cx, |this, _| {
 9211                this.clear_tasks();
 9212                for (key, value) in rows {
 9213                    this.insert_tasks(key, value);
 9214                }
 9215            })
 9216            .ok();
 9217        })
 9218    }
 9219    fn fetch_runnable_ranges(
 9220        snapshot: &DisplaySnapshot,
 9221        range: Range<Anchor>,
 9222    ) -> Vec<language::RunnableRange> {
 9223        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9224    }
 9225
 9226    fn runnable_rows(
 9227        project: Model<Project>,
 9228        snapshot: DisplaySnapshot,
 9229        runnable_ranges: Vec<RunnableRange>,
 9230        mut cx: AsyncWindowContext,
 9231    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9232        runnable_ranges
 9233            .into_iter()
 9234            .filter_map(|mut runnable| {
 9235                let tasks = cx
 9236                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9237                    .ok()?;
 9238                if tasks.is_empty() {
 9239                    return None;
 9240                }
 9241
 9242                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9243
 9244                let row = snapshot
 9245                    .buffer_snapshot
 9246                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9247                    .1
 9248                    .start
 9249                    .row;
 9250
 9251                let context_range =
 9252                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9253                Some((
 9254                    (runnable.buffer_id, row),
 9255                    RunnableTasks {
 9256                        templates: tasks,
 9257                        offset: MultiBufferOffset(runnable.run_range.start),
 9258                        context_range,
 9259                        column: point.column,
 9260                        extra_variables: runnable.extra_captures,
 9261                    },
 9262                ))
 9263            })
 9264            .collect()
 9265    }
 9266
 9267    fn templates_with_tags(
 9268        project: &Model<Project>,
 9269        runnable: &mut Runnable,
 9270        cx: &WindowContext<'_>,
 9271    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9272        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9273            let (worktree_id, file) = project
 9274                .buffer_for_id(runnable.buffer, cx)
 9275                .and_then(|buffer| buffer.read(cx).file())
 9276                .map(|file| (file.worktree_id(cx), file.clone()))
 9277                .unzip();
 9278
 9279            (
 9280                project.task_store().read(cx).task_inventory().cloned(),
 9281                worktree_id,
 9282                file,
 9283            )
 9284        });
 9285
 9286        let tags = mem::take(&mut runnable.tags);
 9287        let mut tags: Vec<_> = tags
 9288            .into_iter()
 9289            .flat_map(|tag| {
 9290                let tag = tag.0.clone();
 9291                inventory
 9292                    .as_ref()
 9293                    .into_iter()
 9294                    .flat_map(|inventory| {
 9295                        inventory.read(cx).list_tasks(
 9296                            file.clone(),
 9297                            Some(runnable.language.clone()),
 9298                            worktree_id,
 9299                            cx,
 9300                        )
 9301                    })
 9302                    .filter(move |(_, template)| {
 9303                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9304                    })
 9305            })
 9306            .sorted_by_key(|(kind, _)| kind.to_owned())
 9307            .collect();
 9308        if let Some((leading_tag_source, _)) = tags.first() {
 9309            // Strongest source wins; if we have worktree tag binding, prefer that to
 9310            // global and language bindings;
 9311            // if we have a global binding, prefer that to language binding.
 9312            let first_mismatch = tags
 9313                .iter()
 9314                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9315            if let Some(index) = first_mismatch {
 9316                tags.truncate(index);
 9317            }
 9318        }
 9319
 9320        tags
 9321    }
 9322
 9323    pub fn move_to_enclosing_bracket(
 9324        &mut self,
 9325        _: &MoveToEnclosingBracket,
 9326        cx: &mut ViewContext<Self>,
 9327    ) {
 9328        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9329            s.move_offsets_with(|snapshot, selection| {
 9330                let Some(enclosing_bracket_ranges) =
 9331                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9332                else {
 9333                    return;
 9334                };
 9335
 9336                let mut best_length = usize::MAX;
 9337                let mut best_inside = false;
 9338                let mut best_in_bracket_range = false;
 9339                let mut best_destination = None;
 9340                for (open, close) in enclosing_bracket_ranges {
 9341                    let close = close.to_inclusive();
 9342                    let length = close.end() - open.start;
 9343                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9344                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9345                        || close.contains(&selection.head());
 9346
 9347                    // If best is next to a bracket and current isn't, skip
 9348                    if !in_bracket_range && best_in_bracket_range {
 9349                        continue;
 9350                    }
 9351
 9352                    // Prefer smaller lengths unless best is inside and current isn't
 9353                    if length > best_length && (best_inside || !inside) {
 9354                        continue;
 9355                    }
 9356
 9357                    best_length = length;
 9358                    best_inside = inside;
 9359                    best_in_bracket_range = in_bracket_range;
 9360                    best_destination = Some(
 9361                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9362                            if inside {
 9363                                open.end
 9364                            } else {
 9365                                open.start
 9366                            }
 9367                        } else if inside {
 9368                            *close.start()
 9369                        } else {
 9370                            *close.end()
 9371                        },
 9372                    );
 9373                }
 9374
 9375                if let Some(destination) = best_destination {
 9376                    selection.collapse_to(destination, SelectionGoal::None);
 9377                }
 9378            })
 9379        });
 9380    }
 9381
 9382    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9383        self.end_selection(cx);
 9384        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9385        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9386            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9387            self.select_next_state = entry.select_next_state;
 9388            self.select_prev_state = entry.select_prev_state;
 9389            self.add_selections_state = entry.add_selections_state;
 9390            self.request_autoscroll(Autoscroll::newest(), cx);
 9391        }
 9392        self.selection_history.mode = SelectionHistoryMode::Normal;
 9393    }
 9394
 9395    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9396        self.end_selection(cx);
 9397        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9398        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9399            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9400            self.select_next_state = entry.select_next_state;
 9401            self.select_prev_state = entry.select_prev_state;
 9402            self.add_selections_state = entry.add_selections_state;
 9403            self.request_autoscroll(Autoscroll::newest(), cx);
 9404        }
 9405        self.selection_history.mode = SelectionHistoryMode::Normal;
 9406    }
 9407
 9408    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9409        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9410    }
 9411
 9412    pub fn expand_excerpts_down(
 9413        &mut self,
 9414        action: &ExpandExcerptsDown,
 9415        cx: &mut ViewContext<Self>,
 9416    ) {
 9417        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9418    }
 9419
 9420    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9421        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9422    }
 9423
 9424    pub fn expand_excerpts_for_direction(
 9425        &mut self,
 9426        lines: u32,
 9427        direction: ExpandExcerptDirection,
 9428        cx: &mut ViewContext<Self>,
 9429    ) {
 9430        let selections = self.selections.disjoint_anchors();
 9431
 9432        let lines = if lines == 0 {
 9433            EditorSettings::get_global(cx).expand_excerpt_lines
 9434        } else {
 9435            lines
 9436        };
 9437
 9438        self.buffer.update(cx, |buffer, cx| {
 9439            buffer.expand_excerpts(
 9440                selections
 9441                    .iter()
 9442                    .map(|selection| selection.head().excerpt_id)
 9443                    .dedup(),
 9444                lines,
 9445                direction,
 9446                cx,
 9447            )
 9448        })
 9449    }
 9450
 9451    pub fn expand_excerpt(
 9452        &mut self,
 9453        excerpt: ExcerptId,
 9454        direction: ExpandExcerptDirection,
 9455        cx: &mut ViewContext<Self>,
 9456    ) {
 9457        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9458        self.buffer.update(cx, |buffer, cx| {
 9459            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9460        })
 9461    }
 9462
 9463    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9464        self.go_to_diagnostic_impl(Direction::Next, cx)
 9465    }
 9466
 9467    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9468        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9469    }
 9470
 9471    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9472        let buffer = self.buffer.read(cx).snapshot(cx);
 9473        let selection = self.selections.newest::<usize>(cx);
 9474
 9475        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9476        if direction == Direction::Next {
 9477            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9478                let (group_id, jump_to) = popover.activation_info();
 9479                if self.activate_diagnostics(group_id, cx) {
 9480                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9481                        let mut new_selection = s.newest_anchor().clone();
 9482                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9483                        s.select_anchors(vec![new_selection.clone()]);
 9484                    });
 9485                }
 9486                return;
 9487            }
 9488        }
 9489
 9490        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9491            active_diagnostics
 9492                .primary_range
 9493                .to_offset(&buffer)
 9494                .to_inclusive()
 9495        });
 9496        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9497            if active_primary_range.contains(&selection.head()) {
 9498                *active_primary_range.start()
 9499            } else {
 9500                selection.head()
 9501            }
 9502        } else {
 9503            selection.head()
 9504        };
 9505        let snapshot = self.snapshot(cx);
 9506        loop {
 9507            let diagnostics = if direction == Direction::Prev {
 9508                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9509            } else {
 9510                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9511            }
 9512            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9513            let group = diagnostics
 9514                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9515                // be sorted in a stable way
 9516                // skip until we are at current active diagnostic, if it exists
 9517                .skip_while(|entry| {
 9518                    (match direction {
 9519                        Direction::Prev => entry.range.start >= search_start,
 9520                        Direction::Next => entry.range.start <= search_start,
 9521                    }) && self
 9522                        .active_diagnostics
 9523                        .as_ref()
 9524                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9525                })
 9526                .find_map(|entry| {
 9527                    if entry.diagnostic.is_primary
 9528                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9529                        && !entry.range.is_empty()
 9530                        // if we match with the active diagnostic, skip it
 9531                        && Some(entry.diagnostic.group_id)
 9532                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9533                    {
 9534                        Some((entry.range, entry.diagnostic.group_id))
 9535                    } else {
 9536                        None
 9537                    }
 9538                });
 9539
 9540            if let Some((primary_range, group_id)) = group {
 9541                if self.activate_diagnostics(group_id, cx) {
 9542                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9543                        s.select(vec![Selection {
 9544                            id: selection.id,
 9545                            start: primary_range.start,
 9546                            end: primary_range.start,
 9547                            reversed: false,
 9548                            goal: SelectionGoal::None,
 9549                        }]);
 9550                    });
 9551                }
 9552                break;
 9553            } else {
 9554                // Cycle around to the start of the buffer, potentially moving back to the start of
 9555                // the currently active diagnostic.
 9556                active_primary_range.take();
 9557                if direction == Direction::Prev {
 9558                    if search_start == buffer.len() {
 9559                        break;
 9560                    } else {
 9561                        search_start = buffer.len();
 9562                    }
 9563                } else if search_start == 0 {
 9564                    break;
 9565                } else {
 9566                    search_start = 0;
 9567                }
 9568            }
 9569        }
 9570    }
 9571
 9572    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9573        let snapshot = self
 9574            .display_map
 9575            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9576        let selection = self.selections.newest::<Point>(cx);
 9577        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9578    }
 9579
 9580    fn go_to_hunk_after_position(
 9581        &mut self,
 9582        snapshot: &DisplaySnapshot,
 9583        position: Point,
 9584        cx: &mut ViewContext<'_, Editor>,
 9585    ) -> Option<MultiBufferDiffHunk> {
 9586        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9587            snapshot,
 9588            position,
 9589            false,
 9590            snapshot
 9591                .buffer_snapshot
 9592                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9593            cx,
 9594        ) {
 9595            return Some(hunk);
 9596        }
 9597
 9598        let wrapped_point = Point::zero();
 9599        self.go_to_next_hunk_in_direction(
 9600            snapshot,
 9601            wrapped_point,
 9602            true,
 9603            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9604                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9605            ),
 9606            cx,
 9607        )
 9608    }
 9609
 9610    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9611        let snapshot = self
 9612            .display_map
 9613            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9614        let selection = self.selections.newest::<Point>(cx);
 9615
 9616        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9617    }
 9618
 9619    fn go_to_hunk_before_position(
 9620        &mut self,
 9621        snapshot: &DisplaySnapshot,
 9622        position: Point,
 9623        cx: &mut ViewContext<'_, Editor>,
 9624    ) -> Option<MultiBufferDiffHunk> {
 9625        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9626            snapshot,
 9627            position,
 9628            false,
 9629            snapshot
 9630                .buffer_snapshot
 9631                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9632            cx,
 9633        ) {
 9634            return Some(hunk);
 9635        }
 9636
 9637        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9638        self.go_to_next_hunk_in_direction(
 9639            snapshot,
 9640            wrapped_point,
 9641            true,
 9642            snapshot
 9643                .buffer_snapshot
 9644                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9645            cx,
 9646        )
 9647    }
 9648
 9649    fn go_to_next_hunk_in_direction(
 9650        &mut self,
 9651        snapshot: &DisplaySnapshot,
 9652        initial_point: Point,
 9653        is_wrapped: bool,
 9654        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9655        cx: &mut ViewContext<Editor>,
 9656    ) -> Option<MultiBufferDiffHunk> {
 9657        let display_point = initial_point.to_display_point(snapshot);
 9658        let mut hunks = hunks
 9659            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9660            .filter(|(display_hunk, _)| {
 9661                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9662            })
 9663            .dedup();
 9664
 9665        if let Some((display_hunk, hunk)) = hunks.next() {
 9666            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9667                let row = display_hunk.start_display_row();
 9668                let point = DisplayPoint::new(row, 0);
 9669                s.select_display_ranges([point..point]);
 9670            });
 9671
 9672            Some(hunk)
 9673        } else {
 9674            None
 9675        }
 9676    }
 9677
 9678    pub fn go_to_definition(
 9679        &mut self,
 9680        _: &GoToDefinition,
 9681        cx: &mut ViewContext<Self>,
 9682    ) -> Task<Result<Navigated>> {
 9683        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9684        cx.spawn(|editor, mut cx| async move {
 9685            if definition.await? == Navigated::Yes {
 9686                return Ok(Navigated::Yes);
 9687            }
 9688            match editor.update(&mut cx, |editor, cx| {
 9689                editor.find_all_references(&FindAllReferences, cx)
 9690            })? {
 9691                Some(references) => references.await,
 9692                None => Ok(Navigated::No),
 9693            }
 9694        })
 9695    }
 9696
 9697    pub fn go_to_declaration(
 9698        &mut self,
 9699        _: &GoToDeclaration,
 9700        cx: &mut ViewContext<Self>,
 9701    ) -> Task<Result<Navigated>> {
 9702        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9703    }
 9704
 9705    pub fn go_to_declaration_split(
 9706        &mut self,
 9707        _: &GoToDeclaration,
 9708        cx: &mut ViewContext<Self>,
 9709    ) -> Task<Result<Navigated>> {
 9710        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9711    }
 9712
 9713    pub fn go_to_implementation(
 9714        &mut self,
 9715        _: &GoToImplementation,
 9716        cx: &mut ViewContext<Self>,
 9717    ) -> Task<Result<Navigated>> {
 9718        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9719    }
 9720
 9721    pub fn go_to_implementation_split(
 9722        &mut self,
 9723        _: &GoToImplementationSplit,
 9724        cx: &mut ViewContext<Self>,
 9725    ) -> Task<Result<Navigated>> {
 9726        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9727    }
 9728
 9729    pub fn go_to_type_definition(
 9730        &mut self,
 9731        _: &GoToTypeDefinition,
 9732        cx: &mut ViewContext<Self>,
 9733    ) -> Task<Result<Navigated>> {
 9734        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9735    }
 9736
 9737    pub fn go_to_definition_split(
 9738        &mut self,
 9739        _: &GoToDefinitionSplit,
 9740        cx: &mut ViewContext<Self>,
 9741    ) -> Task<Result<Navigated>> {
 9742        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9743    }
 9744
 9745    pub fn go_to_type_definition_split(
 9746        &mut self,
 9747        _: &GoToTypeDefinitionSplit,
 9748        cx: &mut ViewContext<Self>,
 9749    ) -> Task<Result<Navigated>> {
 9750        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9751    }
 9752
 9753    fn go_to_definition_of_kind(
 9754        &mut self,
 9755        kind: GotoDefinitionKind,
 9756        split: bool,
 9757        cx: &mut ViewContext<Self>,
 9758    ) -> Task<Result<Navigated>> {
 9759        let Some(provider) = self.semantics_provider.clone() else {
 9760            return Task::ready(Ok(Navigated::No));
 9761        };
 9762        let head = self.selections.newest::<usize>(cx).head();
 9763        let buffer = self.buffer.read(cx);
 9764        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9765            text_anchor
 9766        } else {
 9767            return Task::ready(Ok(Navigated::No));
 9768        };
 9769
 9770        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9771            return Task::ready(Ok(Navigated::No));
 9772        };
 9773
 9774        cx.spawn(|editor, mut cx| async move {
 9775            let definitions = definitions.await?;
 9776            let navigated = editor
 9777                .update(&mut cx, |editor, cx| {
 9778                    editor.navigate_to_hover_links(
 9779                        Some(kind),
 9780                        definitions
 9781                            .into_iter()
 9782                            .filter(|location| {
 9783                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9784                            })
 9785                            .map(HoverLink::Text)
 9786                            .collect::<Vec<_>>(),
 9787                        split,
 9788                        cx,
 9789                    )
 9790                })?
 9791                .await?;
 9792            anyhow::Ok(navigated)
 9793        })
 9794    }
 9795
 9796    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9797        let position = self.selections.newest_anchor().head();
 9798        let Some((buffer, buffer_position)) =
 9799            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9800        else {
 9801            return;
 9802        };
 9803
 9804        cx.spawn(|editor, mut cx| async move {
 9805            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9806                editor.update(&mut cx, |_, cx| {
 9807                    cx.open_url(&url);
 9808                })
 9809            } else {
 9810                Ok(())
 9811            }
 9812        })
 9813        .detach();
 9814    }
 9815
 9816    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9817        let Some(workspace) = self.workspace() else {
 9818            return;
 9819        };
 9820
 9821        let position = self.selections.newest_anchor().head();
 9822
 9823        let Some((buffer, buffer_position)) =
 9824            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9825        else {
 9826            return;
 9827        };
 9828
 9829        let project = self.project.clone();
 9830
 9831        cx.spawn(|_, mut cx| async move {
 9832            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9833
 9834            if let Some((_, path)) = result {
 9835                workspace
 9836                    .update(&mut cx, |workspace, cx| {
 9837                        workspace.open_resolved_path(path, cx)
 9838                    })?
 9839                    .await?;
 9840            }
 9841            anyhow::Ok(())
 9842        })
 9843        .detach();
 9844    }
 9845
 9846    pub(crate) fn navigate_to_hover_links(
 9847        &mut self,
 9848        kind: Option<GotoDefinitionKind>,
 9849        mut definitions: Vec<HoverLink>,
 9850        split: bool,
 9851        cx: &mut ViewContext<Editor>,
 9852    ) -> Task<Result<Navigated>> {
 9853        // If there is one definition, just open it directly
 9854        if definitions.len() == 1 {
 9855            let definition = definitions.pop().unwrap();
 9856
 9857            enum TargetTaskResult {
 9858                Location(Option<Location>),
 9859                AlreadyNavigated,
 9860            }
 9861
 9862            let target_task = match definition {
 9863                HoverLink::Text(link) => {
 9864                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9865                }
 9866                HoverLink::InlayHint(lsp_location, server_id) => {
 9867                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9868                    cx.background_executor().spawn(async move {
 9869                        let location = computation.await?;
 9870                        Ok(TargetTaskResult::Location(location))
 9871                    })
 9872                }
 9873                HoverLink::Url(url) => {
 9874                    cx.open_url(&url);
 9875                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9876                }
 9877                HoverLink::File(path) => {
 9878                    if let Some(workspace) = self.workspace() {
 9879                        cx.spawn(|_, mut cx| async move {
 9880                            workspace
 9881                                .update(&mut cx, |workspace, cx| {
 9882                                    workspace.open_resolved_path(path, cx)
 9883                                })?
 9884                                .await
 9885                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9886                        })
 9887                    } else {
 9888                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9889                    }
 9890                }
 9891            };
 9892            cx.spawn(|editor, mut cx| async move {
 9893                let target = match target_task.await.context("target resolution task")? {
 9894                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9895                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9896                    TargetTaskResult::Location(Some(target)) => target,
 9897                };
 9898
 9899                editor.update(&mut cx, |editor, cx| {
 9900                    let Some(workspace) = editor.workspace() else {
 9901                        return Navigated::No;
 9902                    };
 9903                    let pane = workspace.read(cx).active_pane().clone();
 9904
 9905                    let range = target.range.to_offset(target.buffer.read(cx));
 9906                    let range = editor.range_for_match(&range);
 9907
 9908                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9909                        let buffer = target.buffer.read(cx);
 9910                        let range = check_multiline_range(buffer, range);
 9911                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9912                            s.select_ranges([range]);
 9913                        });
 9914                    } else {
 9915                        cx.window_context().defer(move |cx| {
 9916                            let target_editor: View<Self> =
 9917                                workspace.update(cx, |workspace, cx| {
 9918                                    let pane = if split {
 9919                                        workspace.adjacent_pane(cx)
 9920                                    } else {
 9921                                        workspace.active_pane().clone()
 9922                                    };
 9923
 9924                                    workspace.open_project_item(
 9925                                        pane,
 9926                                        target.buffer.clone(),
 9927                                        true,
 9928                                        true,
 9929                                        cx,
 9930                                    )
 9931                                });
 9932                            target_editor.update(cx, |target_editor, cx| {
 9933                                // When selecting a definition in a different buffer, disable the nav history
 9934                                // to avoid creating a history entry at the previous cursor location.
 9935                                pane.update(cx, |pane, _| pane.disable_history());
 9936                                let buffer = target.buffer.read(cx);
 9937                                let range = check_multiline_range(buffer, range);
 9938                                target_editor.change_selections(
 9939                                    Some(Autoscroll::focused()),
 9940                                    cx,
 9941                                    |s| {
 9942                                        s.select_ranges([range]);
 9943                                    },
 9944                                );
 9945                                pane.update(cx, |pane, _| pane.enable_history());
 9946                            });
 9947                        });
 9948                    }
 9949                    Navigated::Yes
 9950                })
 9951            })
 9952        } else if !definitions.is_empty() {
 9953            cx.spawn(|editor, mut cx| async move {
 9954                let (title, location_tasks, workspace) = editor
 9955                    .update(&mut cx, |editor, cx| {
 9956                        let tab_kind = match kind {
 9957                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9958                            _ => "Definitions",
 9959                        };
 9960                        let title = definitions
 9961                            .iter()
 9962                            .find_map(|definition| match definition {
 9963                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9964                                    let buffer = origin.buffer.read(cx);
 9965                                    format!(
 9966                                        "{} for {}",
 9967                                        tab_kind,
 9968                                        buffer
 9969                                            .text_for_range(origin.range.clone())
 9970                                            .collect::<String>()
 9971                                    )
 9972                                }),
 9973                                HoverLink::InlayHint(_, _) => None,
 9974                                HoverLink::Url(_) => None,
 9975                                HoverLink::File(_) => None,
 9976                            })
 9977                            .unwrap_or(tab_kind.to_string());
 9978                        let location_tasks = definitions
 9979                            .into_iter()
 9980                            .map(|definition| match definition {
 9981                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9982                                HoverLink::InlayHint(lsp_location, server_id) => {
 9983                                    editor.compute_target_location(lsp_location, server_id, cx)
 9984                                }
 9985                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9986                                HoverLink::File(_) => Task::ready(Ok(None)),
 9987                            })
 9988                            .collect::<Vec<_>>();
 9989                        (title, location_tasks, editor.workspace().clone())
 9990                    })
 9991                    .context("location tasks preparation")?;
 9992
 9993                let locations = future::join_all(location_tasks)
 9994                    .await
 9995                    .into_iter()
 9996                    .filter_map(|location| location.transpose())
 9997                    .collect::<Result<_>>()
 9998                    .context("location tasks")?;
 9999
10000                let Some(workspace) = workspace else {
10001                    return Ok(Navigated::No);
10002                };
10003                let opened = workspace
10004                    .update(&mut cx, |workspace, cx| {
10005                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10006                    })
10007                    .ok();
10008
10009                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10010            })
10011        } else {
10012            Task::ready(Ok(Navigated::No))
10013        }
10014    }
10015
10016    fn compute_target_location(
10017        &self,
10018        lsp_location: lsp::Location,
10019        server_id: LanguageServerId,
10020        cx: &mut ViewContext<Self>,
10021    ) -> Task<anyhow::Result<Option<Location>>> {
10022        let Some(project) = self.project.clone() else {
10023            return Task::Ready(Some(Ok(None)));
10024        };
10025
10026        cx.spawn(move |editor, mut cx| async move {
10027            let location_task = editor.update(&mut cx, |_, cx| {
10028                project.update(cx, |project, cx| {
10029                    let language_server_name = project
10030                        .language_server_statuses(cx)
10031                        .find(|(id, _)| server_id == *id)
10032                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10033                    language_server_name.map(|language_server_name| {
10034                        project.open_local_buffer_via_lsp(
10035                            lsp_location.uri.clone(),
10036                            server_id,
10037                            language_server_name,
10038                            cx,
10039                        )
10040                    })
10041                })
10042            })?;
10043            let location = match location_task {
10044                Some(task) => Some({
10045                    let target_buffer_handle = task.await.context("open local buffer")?;
10046                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10047                        let target_start = target_buffer
10048                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10049                        let target_end = target_buffer
10050                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10051                        target_buffer.anchor_after(target_start)
10052                            ..target_buffer.anchor_before(target_end)
10053                    })?;
10054                    Location {
10055                        buffer: target_buffer_handle,
10056                        range,
10057                    }
10058                }),
10059                None => None,
10060            };
10061            Ok(location)
10062        })
10063    }
10064
10065    pub fn find_all_references(
10066        &mut self,
10067        _: &FindAllReferences,
10068        cx: &mut ViewContext<Self>,
10069    ) -> Option<Task<Result<Navigated>>> {
10070        let selection = self.selections.newest::<usize>(cx);
10071        let multi_buffer = self.buffer.read(cx);
10072        let head = selection.head();
10073
10074        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10075        let head_anchor = multi_buffer_snapshot.anchor_at(
10076            head,
10077            if head < selection.tail() {
10078                Bias::Right
10079            } else {
10080                Bias::Left
10081            },
10082        );
10083
10084        match self
10085            .find_all_references_task_sources
10086            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10087        {
10088            Ok(_) => {
10089                log::info!(
10090                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10091                );
10092                return None;
10093            }
10094            Err(i) => {
10095                self.find_all_references_task_sources.insert(i, head_anchor);
10096            }
10097        }
10098
10099        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10100        let workspace = self.workspace()?;
10101        let project = workspace.read(cx).project().clone();
10102        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10103        Some(cx.spawn(|editor, mut cx| async move {
10104            let _cleanup = defer({
10105                let mut cx = cx.clone();
10106                move || {
10107                    let _ = editor.update(&mut cx, |editor, _| {
10108                        if let Ok(i) =
10109                            editor
10110                                .find_all_references_task_sources
10111                                .binary_search_by(|anchor| {
10112                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10113                                })
10114                        {
10115                            editor.find_all_references_task_sources.remove(i);
10116                        }
10117                    });
10118                }
10119            });
10120
10121            let locations = references.await?;
10122            if locations.is_empty() {
10123                return anyhow::Ok(Navigated::No);
10124            }
10125
10126            workspace.update(&mut cx, |workspace, cx| {
10127                let title = locations
10128                    .first()
10129                    .as_ref()
10130                    .map(|location| {
10131                        let buffer = location.buffer.read(cx);
10132                        format!(
10133                            "References to `{}`",
10134                            buffer
10135                                .text_for_range(location.range.clone())
10136                                .collect::<String>()
10137                        )
10138                    })
10139                    .unwrap();
10140                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10141                Navigated::Yes
10142            })
10143        }))
10144    }
10145
10146    /// Opens a multibuffer with the given project locations in it
10147    pub fn open_locations_in_multibuffer(
10148        workspace: &mut Workspace,
10149        mut locations: Vec<Location>,
10150        title: String,
10151        split: bool,
10152        cx: &mut ViewContext<Workspace>,
10153    ) {
10154        // If there are multiple definitions, open them in a multibuffer
10155        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10156        let mut locations = locations.into_iter().peekable();
10157        let mut ranges_to_highlight = Vec::new();
10158        let capability = workspace.project().read(cx).capability();
10159
10160        let excerpt_buffer = cx.new_model(|cx| {
10161            let mut multibuffer = MultiBuffer::new(capability);
10162            while let Some(location) = locations.next() {
10163                let buffer = location.buffer.read(cx);
10164                let mut ranges_for_buffer = Vec::new();
10165                let range = location.range.to_offset(buffer);
10166                ranges_for_buffer.push(range.clone());
10167
10168                while let Some(next_location) = locations.peek() {
10169                    if next_location.buffer == location.buffer {
10170                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10171                        locations.next();
10172                    } else {
10173                        break;
10174                    }
10175                }
10176
10177                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10178                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10179                    location.buffer.clone(),
10180                    ranges_for_buffer,
10181                    DEFAULT_MULTIBUFFER_CONTEXT,
10182                    cx,
10183                ))
10184            }
10185
10186            multibuffer.with_title(title)
10187        });
10188
10189        let editor = cx.new_view(|cx| {
10190            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10191        });
10192        editor.update(cx, |editor, cx| {
10193            if let Some(first_range) = ranges_to_highlight.first() {
10194                editor.change_selections(None, cx, |selections| {
10195                    selections.clear_disjoint();
10196                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10197                });
10198            }
10199            editor.highlight_background::<Self>(
10200                &ranges_to_highlight,
10201                |theme| theme.editor_highlighted_line_background,
10202                cx,
10203            );
10204        });
10205
10206        let item = Box::new(editor);
10207        let item_id = item.item_id();
10208
10209        if split {
10210            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10211        } else {
10212            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10213                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10214                    pane.close_current_preview_item(cx)
10215                } else {
10216                    None
10217                }
10218            });
10219            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10220        }
10221        workspace.active_pane().update(cx, |pane, cx| {
10222            pane.set_preview_item_id(Some(item_id), cx);
10223        });
10224    }
10225
10226    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10227        use language::ToOffset as _;
10228
10229        let provider = self.semantics_provider.clone()?;
10230        let selection = self.selections.newest_anchor().clone();
10231        let (cursor_buffer, cursor_buffer_position) = self
10232            .buffer
10233            .read(cx)
10234            .text_anchor_for_position(selection.head(), cx)?;
10235        let (tail_buffer, cursor_buffer_position_end) = self
10236            .buffer
10237            .read(cx)
10238            .text_anchor_for_position(selection.tail(), cx)?;
10239        if tail_buffer != cursor_buffer {
10240            return None;
10241        }
10242
10243        let snapshot = cursor_buffer.read(cx).snapshot();
10244        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10245        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10246        let prepare_rename = provider
10247            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10248            .unwrap_or_else(|| Task::ready(Ok(None)));
10249        drop(snapshot);
10250
10251        Some(cx.spawn(|this, mut cx| async move {
10252            let rename_range = if let Some(range) = prepare_rename.await? {
10253                Some(range)
10254            } else {
10255                this.update(&mut cx, |this, cx| {
10256                    let buffer = this.buffer.read(cx).snapshot(cx);
10257                    let mut buffer_highlights = this
10258                        .document_highlights_for_position(selection.head(), &buffer)
10259                        .filter(|highlight| {
10260                            highlight.start.excerpt_id == selection.head().excerpt_id
10261                                && highlight.end.excerpt_id == selection.head().excerpt_id
10262                        });
10263                    buffer_highlights
10264                        .next()
10265                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10266                })?
10267            };
10268            if let Some(rename_range) = rename_range {
10269                this.update(&mut cx, |this, cx| {
10270                    let snapshot = cursor_buffer.read(cx).snapshot();
10271                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10272                    let cursor_offset_in_rename_range =
10273                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10274                    let cursor_offset_in_rename_range_end =
10275                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10276
10277                    this.take_rename(false, cx);
10278                    let buffer = this.buffer.read(cx).read(cx);
10279                    let cursor_offset = selection.head().to_offset(&buffer);
10280                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10281                    let rename_end = rename_start + rename_buffer_range.len();
10282                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10283                    let mut old_highlight_id = None;
10284                    let old_name: Arc<str> = buffer
10285                        .chunks(rename_start..rename_end, true)
10286                        .map(|chunk| {
10287                            if old_highlight_id.is_none() {
10288                                old_highlight_id = chunk.syntax_highlight_id;
10289                            }
10290                            chunk.text
10291                        })
10292                        .collect::<String>()
10293                        .into();
10294
10295                    drop(buffer);
10296
10297                    // Position the selection in the rename editor so that it matches the current selection.
10298                    this.show_local_selections = false;
10299                    let rename_editor = cx.new_view(|cx| {
10300                        let mut editor = Editor::single_line(cx);
10301                        editor.buffer.update(cx, |buffer, cx| {
10302                            buffer.edit([(0..0, old_name.clone())], None, cx)
10303                        });
10304                        let rename_selection_range = match cursor_offset_in_rename_range
10305                            .cmp(&cursor_offset_in_rename_range_end)
10306                        {
10307                            Ordering::Equal => {
10308                                editor.select_all(&SelectAll, cx);
10309                                return editor;
10310                            }
10311                            Ordering::Less => {
10312                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10313                            }
10314                            Ordering::Greater => {
10315                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10316                            }
10317                        };
10318                        if rename_selection_range.end > old_name.len() {
10319                            editor.select_all(&SelectAll, cx);
10320                        } else {
10321                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10322                                s.select_ranges([rename_selection_range]);
10323                            });
10324                        }
10325                        editor
10326                    });
10327                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10328                        if e == &EditorEvent::Focused {
10329                            cx.emit(EditorEvent::FocusedIn)
10330                        }
10331                    })
10332                    .detach();
10333
10334                    let write_highlights =
10335                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10336                    let read_highlights =
10337                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10338                    let ranges = write_highlights
10339                        .iter()
10340                        .flat_map(|(_, ranges)| ranges.iter())
10341                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10342                        .cloned()
10343                        .collect();
10344
10345                    this.highlight_text::<Rename>(
10346                        ranges,
10347                        HighlightStyle {
10348                            fade_out: Some(0.6),
10349                            ..Default::default()
10350                        },
10351                        cx,
10352                    );
10353                    let rename_focus_handle = rename_editor.focus_handle(cx);
10354                    cx.focus(&rename_focus_handle);
10355                    let block_id = this.insert_blocks(
10356                        [BlockProperties {
10357                            style: BlockStyle::Flex,
10358                            placement: BlockPlacement::Below(range.start),
10359                            height: 1,
10360                            render: Box::new({
10361                                let rename_editor = rename_editor.clone();
10362                                move |cx: &mut BlockContext| {
10363                                    let mut text_style = cx.editor_style.text.clone();
10364                                    if let Some(highlight_style) = old_highlight_id
10365                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10366                                    {
10367                                        text_style = text_style.highlight(highlight_style);
10368                                    }
10369                                    div()
10370                                        .pl(cx.anchor_x)
10371                                        .child(EditorElement::new(
10372                                            &rename_editor,
10373                                            EditorStyle {
10374                                                background: cx.theme().system().transparent,
10375                                                local_player: cx.editor_style.local_player,
10376                                                text: text_style,
10377                                                scrollbar_width: cx.editor_style.scrollbar_width,
10378                                                syntax: cx.editor_style.syntax.clone(),
10379                                                status: cx.editor_style.status.clone(),
10380                                                inlay_hints_style: HighlightStyle {
10381                                                    font_weight: Some(FontWeight::BOLD),
10382                                                    ..make_inlay_hints_style(cx)
10383                                                },
10384                                                suggestions_style: HighlightStyle {
10385                                                    color: Some(cx.theme().status().predictive),
10386                                                    ..HighlightStyle::default()
10387                                                },
10388                                                ..EditorStyle::default()
10389                                            },
10390                                        ))
10391                                        .into_any_element()
10392                                }
10393                            }),
10394                            priority: 0,
10395                        }],
10396                        Some(Autoscroll::fit()),
10397                        cx,
10398                    )[0];
10399                    this.pending_rename = Some(RenameState {
10400                        range,
10401                        old_name,
10402                        editor: rename_editor,
10403                        block_id,
10404                    });
10405                })?;
10406            }
10407
10408            Ok(())
10409        }))
10410    }
10411
10412    pub fn confirm_rename(
10413        &mut self,
10414        _: &ConfirmRename,
10415        cx: &mut ViewContext<Self>,
10416    ) -> Option<Task<Result<()>>> {
10417        let rename = self.take_rename(false, cx)?;
10418        let workspace = self.workspace()?.downgrade();
10419        let (buffer, start) = self
10420            .buffer
10421            .read(cx)
10422            .text_anchor_for_position(rename.range.start, cx)?;
10423        let (end_buffer, _) = self
10424            .buffer
10425            .read(cx)
10426            .text_anchor_for_position(rename.range.end, cx)?;
10427        if buffer != end_buffer {
10428            return None;
10429        }
10430
10431        let old_name = rename.old_name;
10432        let new_name = rename.editor.read(cx).text(cx);
10433
10434        let rename = self.semantics_provider.as_ref()?.perform_rename(
10435            &buffer,
10436            start,
10437            new_name.clone(),
10438            cx,
10439        )?;
10440
10441        Some(cx.spawn(|editor, mut cx| async move {
10442            let project_transaction = rename.await?;
10443            Self::open_project_transaction(
10444                &editor,
10445                workspace,
10446                project_transaction,
10447                format!("Rename: {}{}", old_name, new_name),
10448                cx.clone(),
10449            )
10450            .await?;
10451
10452            editor.update(&mut cx, |editor, cx| {
10453                editor.refresh_document_highlights(cx);
10454            })?;
10455            Ok(())
10456        }))
10457    }
10458
10459    fn take_rename(
10460        &mut self,
10461        moving_cursor: bool,
10462        cx: &mut ViewContext<Self>,
10463    ) -> Option<RenameState> {
10464        let rename = self.pending_rename.take()?;
10465        if rename.editor.focus_handle(cx).is_focused(cx) {
10466            cx.focus(&self.focus_handle);
10467        }
10468
10469        self.remove_blocks(
10470            [rename.block_id].into_iter().collect(),
10471            Some(Autoscroll::fit()),
10472            cx,
10473        );
10474        self.clear_highlights::<Rename>(cx);
10475        self.show_local_selections = true;
10476
10477        if moving_cursor {
10478            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10479                editor.selections.newest::<usize>(cx).head()
10480            });
10481
10482            // Update the selection to match the position of the selection inside
10483            // the rename editor.
10484            let snapshot = self.buffer.read(cx).read(cx);
10485            let rename_range = rename.range.to_offset(&snapshot);
10486            let cursor_in_editor = snapshot
10487                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10488                .min(rename_range.end);
10489            drop(snapshot);
10490
10491            self.change_selections(None, cx, |s| {
10492                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10493            });
10494        } else {
10495            self.refresh_document_highlights(cx);
10496        }
10497
10498        Some(rename)
10499    }
10500
10501    pub fn pending_rename(&self) -> Option<&RenameState> {
10502        self.pending_rename.as_ref()
10503    }
10504
10505    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10506        let project = match &self.project {
10507            Some(project) => project.clone(),
10508            None => return None,
10509        };
10510
10511        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10512    }
10513
10514    fn format_selections(
10515        &mut self,
10516        _: &FormatSelections,
10517        cx: &mut ViewContext<Self>,
10518    ) -> Option<Task<Result<()>>> {
10519        let project = match &self.project {
10520            Some(project) => project.clone(),
10521            None => return None,
10522        };
10523
10524        let selections = self
10525            .selections
10526            .all_adjusted(cx)
10527            .into_iter()
10528            .filter(|s| !s.is_empty())
10529            .collect_vec();
10530
10531        Some(self.perform_format(
10532            project,
10533            FormatTrigger::Manual,
10534            FormatTarget::Ranges(selections),
10535            cx,
10536        ))
10537    }
10538
10539    fn perform_format(
10540        &mut self,
10541        project: Model<Project>,
10542        trigger: FormatTrigger,
10543        target: FormatTarget,
10544        cx: &mut ViewContext<Self>,
10545    ) -> Task<Result<()>> {
10546        let buffer = self.buffer().clone();
10547        let mut buffers = buffer.read(cx).all_buffers();
10548        if trigger == FormatTrigger::Save {
10549            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10550        }
10551
10552        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10553        let format = project.update(cx, |project, cx| {
10554            project.format(buffers, true, trigger, target, cx)
10555        });
10556
10557        cx.spawn(|_, mut cx| async move {
10558            let transaction = futures::select_biased! {
10559                () = timeout => {
10560                    log::warn!("timed out waiting for formatting");
10561                    None
10562                }
10563                transaction = format.log_err().fuse() => transaction,
10564            };
10565
10566            buffer
10567                .update(&mut cx, |buffer, cx| {
10568                    if let Some(transaction) = transaction {
10569                        if !buffer.is_singleton() {
10570                            buffer.push_transaction(&transaction.0, cx);
10571                        }
10572                    }
10573
10574                    cx.notify();
10575                })
10576                .ok();
10577
10578            Ok(())
10579        })
10580    }
10581
10582    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10583        if let Some(project) = self.project.clone() {
10584            self.buffer.update(cx, |multi_buffer, cx| {
10585                project.update(cx, |project, cx| {
10586                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10587                });
10588            })
10589        }
10590    }
10591
10592    fn cancel_language_server_work(
10593        &mut self,
10594        _: &actions::CancelLanguageServerWork,
10595        cx: &mut ViewContext<Self>,
10596    ) {
10597        if let Some(project) = self.project.clone() {
10598            self.buffer.update(cx, |multi_buffer, cx| {
10599                project.update(cx, |project, cx| {
10600                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10601                });
10602            })
10603        }
10604    }
10605
10606    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10607        cx.show_character_palette();
10608    }
10609
10610    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10611        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10612            let buffer = self.buffer.read(cx).snapshot(cx);
10613            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10614            let is_valid = buffer
10615                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10616                .any(|entry| {
10617                    entry.diagnostic.is_primary
10618                        && !entry.range.is_empty()
10619                        && entry.range.start == primary_range_start
10620                        && entry.diagnostic.message == active_diagnostics.primary_message
10621                });
10622
10623            if is_valid != active_diagnostics.is_valid {
10624                active_diagnostics.is_valid = is_valid;
10625                let mut new_styles = HashMap::default();
10626                for (block_id, diagnostic) in &active_diagnostics.blocks {
10627                    new_styles.insert(
10628                        *block_id,
10629                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10630                    );
10631                }
10632                self.display_map.update(cx, |display_map, _cx| {
10633                    display_map.replace_blocks(new_styles)
10634                });
10635            }
10636        }
10637    }
10638
10639    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10640        self.dismiss_diagnostics(cx);
10641        let snapshot = self.snapshot(cx);
10642        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10643            let buffer = self.buffer.read(cx).snapshot(cx);
10644
10645            let mut primary_range = None;
10646            let mut primary_message = None;
10647            let mut group_end = Point::zero();
10648            let diagnostic_group = buffer
10649                .diagnostic_group::<MultiBufferPoint>(group_id)
10650                .filter_map(|entry| {
10651                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10652                        && (entry.range.start.row == entry.range.end.row
10653                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10654                    {
10655                        return None;
10656                    }
10657                    if entry.range.end > group_end {
10658                        group_end = entry.range.end;
10659                    }
10660                    if entry.diagnostic.is_primary {
10661                        primary_range = Some(entry.range.clone());
10662                        primary_message = Some(entry.diagnostic.message.clone());
10663                    }
10664                    Some(entry)
10665                })
10666                .collect::<Vec<_>>();
10667            let primary_range = primary_range?;
10668            let primary_message = primary_message?;
10669            let primary_range =
10670                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10671
10672            let blocks = display_map
10673                .insert_blocks(
10674                    diagnostic_group.iter().map(|entry| {
10675                        let diagnostic = entry.diagnostic.clone();
10676                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10677                        BlockProperties {
10678                            style: BlockStyle::Fixed,
10679                            placement: BlockPlacement::Below(
10680                                buffer.anchor_after(entry.range.start),
10681                            ),
10682                            height: message_height,
10683                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10684                            priority: 0,
10685                        }
10686                    }),
10687                    cx,
10688                )
10689                .into_iter()
10690                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10691                .collect();
10692
10693            Some(ActiveDiagnosticGroup {
10694                primary_range,
10695                primary_message,
10696                group_id,
10697                blocks,
10698                is_valid: true,
10699            })
10700        });
10701        self.active_diagnostics.is_some()
10702    }
10703
10704    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10705        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10706            self.display_map.update(cx, |display_map, cx| {
10707                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10708            });
10709            cx.notify();
10710        }
10711    }
10712
10713    pub fn set_selections_from_remote(
10714        &mut self,
10715        selections: Vec<Selection<Anchor>>,
10716        pending_selection: Option<Selection<Anchor>>,
10717        cx: &mut ViewContext<Self>,
10718    ) {
10719        let old_cursor_position = self.selections.newest_anchor().head();
10720        self.selections.change_with(cx, |s| {
10721            s.select_anchors(selections);
10722            if let Some(pending_selection) = pending_selection {
10723                s.set_pending(pending_selection, SelectMode::Character);
10724            } else {
10725                s.clear_pending();
10726            }
10727        });
10728        self.selections_did_change(false, &old_cursor_position, true, cx);
10729    }
10730
10731    fn push_to_selection_history(&mut self) {
10732        self.selection_history.push(SelectionHistoryEntry {
10733            selections: self.selections.disjoint_anchors(),
10734            select_next_state: self.select_next_state.clone(),
10735            select_prev_state: self.select_prev_state.clone(),
10736            add_selections_state: self.add_selections_state.clone(),
10737        });
10738    }
10739
10740    pub fn transact(
10741        &mut self,
10742        cx: &mut ViewContext<Self>,
10743        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10744    ) -> Option<TransactionId> {
10745        self.start_transaction_at(Instant::now(), cx);
10746        update(self, cx);
10747        self.end_transaction_at(Instant::now(), cx)
10748    }
10749
10750    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10751        self.end_selection(cx);
10752        if let Some(tx_id) = self
10753            .buffer
10754            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10755        {
10756            self.selection_history
10757                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10758            cx.emit(EditorEvent::TransactionBegun {
10759                transaction_id: tx_id,
10760            })
10761        }
10762    }
10763
10764    fn end_transaction_at(
10765        &mut self,
10766        now: Instant,
10767        cx: &mut ViewContext<Self>,
10768    ) -> Option<TransactionId> {
10769        if let Some(transaction_id) = self
10770            .buffer
10771            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10772        {
10773            if let Some((_, end_selections)) =
10774                self.selection_history.transaction_mut(transaction_id)
10775            {
10776                *end_selections = Some(self.selections.disjoint_anchors());
10777            } else {
10778                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10779            }
10780
10781            cx.emit(EditorEvent::Edited { transaction_id });
10782            Some(transaction_id)
10783        } else {
10784            None
10785        }
10786    }
10787
10788    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10789        let selection = self.selections.newest::<Point>(cx);
10790
10791        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10792        let range = if selection.is_empty() {
10793            let point = selection.head().to_display_point(&display_map);
10794            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10795            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10796                .to_point(&display_map);
10797            start..end
10798        } else {
10799            selection.range()
10800        };
10801        if display_map.folds_in_range(range).next().is_some() {
10802            self.unfold_lines(&Default::default(), cx)
10803        } else {
10804            self.fold(&Default::default(), cx)
10805        }
10806    }
10807
10808    pub fn toggle_fold_recursive(
10809        &mut self,
10810        _: &actions::ToggleFoldRecursive,
10811        cx: &mut ViewContext<Self>,
10812    ) {
10813        let selection = self.selections.newest::<Point>(cx);
10814
10815        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10816        let range = if selection.is_empty() {
10817            let point = selection.head().to_display_point(&display_map);
10818            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10819            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10820                .to_point(&display_map);
10821            start..end
10822        } else {
10823            selection.range()
10824        };
10825        if display_map.folds_in_range(range).next().is_some() {
10826            self.unfold_recursive(&Default::default(), cx)
10827        } else {
10828            self.fold_recursive(&Default::default(), cx)
10829        }
10830    }
10831
10832    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10833        let mut fold_ranges = Vec::new();
10834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10835        let selections = self.selections.all_adjusted(cx);
10836
10837        for selection in selections {
10838            let range = selection.range().sorted();
10839            let buffer_start_row = range.start.row;
10840
10841            if range.start.row != range.end.row {
10842                let mut found = false;
10843                let mut row = range.start.row;
10844                while row <= range.end.row {
10845                    if let Some((foldable_range, fold_text)) =
10846                        { display_map.foldable_range(MultiBufferRow(row)) }
10847                    {
10848                        found = true;
10849                        row = foldable_range.end.row + 1;
10850                        fold_ranges.push((foldable_range, fold_text));
10851                    } else {
10852                        row += 1
10853                    }
10854                }
10855                if found {
10856                    continue;
10857                }
10858            }
10859
10860            for row in (0..=range.start.row).rev() {
10861                if let Some((foldable_range, fold_text)) =
10862                    display_map.foldable_range(MultiBufferRow(row))
10863                {
10864                    if foldable_range.end.row >= buffer_start_row {
10865                        fold_ranges.push((foldable_range, fold_text));
10866                        if row <= range.start.row {
10867                            break;
10868                        }
10869                    }
10870                }
10871            }
10872        }
10873
10874        self.fold_ranges(fold_ranges, true, cx);
10875    }
10876
10877    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10878        let fold_at_level = fold_at.level;
10879        let snapshot = self.buffer.read(cx).snapshot(cx);
10880        let mut fold_ranges = Vec::new();
10881        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10882
10883        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10884            while start_row < end_row {
10885                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10886                    Some(foldable_range) => {
10887                        let nested_start_row = foldable_range.0.start.row + 1;
10888                        let nested_end_row = foldable_range.0.end.row;
10889
10890                        if current_level < fold_at_level {
10891                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10892                        } else if current_level == fold_at_level {
10893                            fold_ranges.push(foldable_range);
10894                        }
10895
10896                        start_row = nested_end_row + 1;
10897                    }
10898                    None => start_row += 1,
10899                }
10900            }
10901        }
10902
10903        self.fold_ranges(fold_ranges, true, cx);
10904    }
10905
10906    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10907        let mut fold_ranges = Vec::new();
10908        let snapshot = self.buffer.read(cx).snapshot(cx);
10909
10910        for row in 0..snapshot.max_buffer_row().0 {
10911            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10912                fold_ranges.push(foldable_range);
10913            }
10914        }
10915
10916        self.fold_ranges(fold_ranges, true, cx);
10917    }
10918
10919    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10920        let mut fold_ranges = Vec::new();
10921        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10922        let selections = self.selections.all_adjusted(cx);
10923
10924        for selection in selections {
10925            let range = selection.range().sorted();
10926            let buffer_start_row = range.start.row;
10927
10928            if range.start.row != range.end.row {
10929                let mut found = false;
10930                for row in range.start.row..=range.end.row {
10931                    if let Some((foldable_range, fold_text)) =
10932                        { display_map.foldable_range(MultiBufferRow(row)) }
10933                    {
10934                        found = true;
10935                        fold_ranges.push((foldable_range, fold_text));
10936                    }
10937                }
10938                if found {
10939                    continue;
10940                }
10941            }
10942
10943            for row in (0..=range.start.row).rev() {
10944                if let Some((foldable_range, fold_text)) =
10945                    display_map.foldable_range(MultiBufferRow(row))
10946                {
10947                    if foldable_range.end.row >= buffer_start_row {
10948                        fold_ranges.push((foldable_range, fold_text));
10949                    } else {
10950                        break;
10951                    }
10952                }
10953            }
10954        }
10955
10956        self.fold_ranges(fold_ranges, true, cx);
10957    }
10958
10959    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10960        let buffer_row = fold_at.buffer_row;
10961        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10962
10963        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10964            let autoscroll = self
10965                .selections
10966                .all::<Point>(cx)
10967                .iter()
10968                .any(|selection| fold_range.overlaps(&selection.range()));
10969
10970            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10971        }
10972    }
10973
10974    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10975        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10976        let buffer = &display_map.buffer_snapshot;
10977        let selections = self.selections.all::<Point>(cx);
10978        let ranges = selections
10979            .iter()
10980            .map(|s| {
10981                let range = s.display_range(&display_map).sorted();
10982                let mut start = range.start.to_point(&display_map);
10983                let mut end = range.end.to_point(&display_map);
10984                start.column = 0;
10985                end.column = buffer.line_len(MultiBufferRow(end.row));
10986                start..end
10987            })
10988            .collect::<Vec<_>>();
10989
10990        self.unfold_ranges(ranges, true, true, cx);
10991    }
10992
10993    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10994        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10995        let selections = self.selections.all::<Point>(cx);
10996        let ranges = selections
10997            .iter()
10998            .map(|s| {
10999                let mut range = s.display_range(&display_map).sorted();
11000                *range.start.column_mut() = 0;
11001                *range.end.column_mut() = display_map.line_len(range.end.row());
11002                let start = range.start.to_point(&display_map);
11003                let end = range.end.to_point(&display_map);
11004                start..end
11005            })
11006            .collect::<Vec<_>>();
11007
11008        self.unfold_ranges(ranges, true, true, cx);
11009    }
11010
11011    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11013
11014        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11015            ..Point::new(
11016                unfold_at.buffer_row.0,
11017                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11018            );
11019
11020        let autoscroll = self
11021            .selections
11022            .all::<Point>(cx)
11023            .iter()
11024            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11025
11026        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
11027    }
11028
11029    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11031        self.unfold_ranges(
11032            [Point::zero()..display_map.max_point().to_point(&display_map)],
11033            true,
11034            true,
11035            cx,
11036        );
11037    }
11038
11039    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11040        let selections = self.selections.all::<Point>(cx);
11041        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11042        let line_mode = self.selections.line_mode;
11043        let ranges = selections.into_iter().map(|s| {
11044            if line_mode {
11045                let start = Point::new(s.start.row, 0);
11046                let end = Point::new(
11047                    s.end.row,
11048                    display_map
11049                        .buffer_snapshot
11050                        .line_len(MultiBufferRow(s.end.row)),
11051                );
11052                (start..end, display_map.fold_placeholder.clone())
11053            } else {
11054                (s.start..s.end, display_map.fold_placeholder.clone())
11055            }
11056        });
11057        self.fold_ranges(ranges, true, cx);
11058    }
11059
11060    pub fn fold_ranges<T: ToOffset + Clone>(
11061        &mut self,
11062        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11063        auto_scroll: bool,
11064        cx: &mut ViewContext<Self>,
11065    ) {
11066        let mut fold_ranges = Vec::new();
11067        let mut buffers_affected = HashMap::default();
11068        let multi_buffer = self.buffer().read(cx);
11069        for (fold_range, fold_text) in ranges {
11070            if let Some((_, buffer, _)) =
11071                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11072            {
11073                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11074            };
11075            fold_ranges.push((fold_range, fold_text));
11076        }
11077
11078        let mut ranges = fold_ranges.into_iter().peekable();
11079        if ranges.peek().is_some() {
11080            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11081
11082            if auto_scroll {
11083                self.request_autoscroll(Autoscroll::fit(), cx);
11084            }
11085
11086            for buffer in buffers_affected.into_values() {
11087                self.sync_expanded_diff_hunks(buffer, cx);
11088            }
11089
11090            cx.notify();
11091
11092            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11093                // Clear diagnostics block when folding a range that contains it.
11094                let snapshot = self.snapshot(cx);
11095                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11096                    drop(snapshot);
11097                    self.active_diagnostics = Some(active_diagnostics);
11098                    self.dismiss_diagnostics(cx);
11099                } else {
11100                    self.active_diagnostics = Some(active_diagnostics);
11101                }
11102            }
11103
11104            self.scrollbar_marker_state.dirty = true;
11105        }
11106    }
11107
11108    pub fn unfold_ranges<T: ToOffset + Clone>(
11109        &mut self,
11110        ranges: impl IntoIterator<Item = Range<T>>,
11111        inclusive: bool,
11112        auto_scroll: bool,
11113        cx: &mut ViewContext<Self>,
11114    ) {
11115        let mut unfold_ranges = Vec::new();
11116        let mut buffers_affected = HashMap::default();
11117        let multi_buffer = self.buffer().read(cx);
11118        for range in ranges {
11119            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11120                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11121            };
11122            unfold_ranges.push(range);
11123        }
11124
11125        let mut ranges = unfold_ranges.into_iter().peekable();
11126        if ranges.peek().is_some() {
11127            self.display_map
11128                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11129            if auto_scroll {
11130                self.request_autoscroll(Autoscroll::fit(), cx);
11131            }
11132
11133            for buffer in buffers_affected.into_values() {
11134                self.sync_expanded_diff_hunks(buffer, cx);
11135            }
11136
11137            cx.notify();
11138            self.scrollbar_marker_state.dirty = true;
11139            self.active_indent_guides_state.dirty = true;
11140        }
11141    }
11142
11143    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11144        self.display_map.read(cx).fold_placeholder.clone()
11145    }
11146
11147    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11148        if hovered != self.gutter_hovered {
11149            self.gutter_hovered = hovered;
11150            cx.notify();
11151        }
11152    }
11153
11154    pub fn insert_blocks(
11155        &mut self,
11156        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11157        autoscroll: Option<Autoscroll>,
11158        cx: &mut ViewContext<Self>,
11159    ) -> Vec<CustomBlockId> {
11160        let blocks = self
11161            .display_map
11162            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11163        if let Some(autoscroll) = autoscroll {
11164            self.request_autoscroll(autoscroll, cx);
11165        }
11166        cx.notify();
11167        blocks
11168    }
11169
11170    pub fn resize_blocks(
11171        &mut self,
11172        heights: HashMap<CustomBlockId, u32>,
11173        autoscroll: Option<Autoscroll>,
11174        cx: &mut ViewContext<Self>,
11175    ) {
11176        self.display_map
11177            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11178        if let Some(autoscroll) = autoscroll {
11179            self.request_autoscroll(autoscroll, cx);
11180        }
11181        cx.notify();
11182    }
11183
11184    pub fn replace_blocks(
11185        &mut self,
11186        renderers: HashMap<CustomBlockId, RenderBlock>,
11187        autoscroll: Option<Autoscroll>,
11188        cx: &mut ViewContext<Self>,
11189    ) {
11190        self.display_map
11191            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11192        if let Some(autoscroll) = autoscroll {
11193            self.request_autoscroll(autoscroll, cx);
11194        }
11195        cx.notify();
11196    }
11197
11198    pub fn remove_blocks(
11199        &mut self,
11200        block_ids: HashSet<CustomBlockId>,
11201        autoscroll: Option<Autoscroll>,
11202        cx: &mut ViewContext<Self>,
11203    ) {
11204        self.display_map.update(cx, |display_map, cx| {
11205            display_map.remove_blocks(block_ids, cx)
11206        });
11207        if let Some(autoscroll) = autoscroll {
11208            self.request_autoscroll(autoscroll, cx);
11209        }
11210        cx.notify();
11211    }
11212
11213    pub fn row_for_block(
11214        &self,
11215        block_id: CustomBlockId,
11216        cx: &mut ViewContext<Self>,
11217    ) -> Option<DisplayRow> {
11218        self.display_map
11219            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11220    }
11221
11222    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11223        self.focused_block = Some(focused_block);
11224    }
11225
11226    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11227        self.focused_block.take()
11228    }
11229
11230    pub fn insert_creases(
11231        &mut self,
11232        creases: impl IntoIterator<Item = Crease>,
11233        cx: &mut ViewContext<Self>,
11234    ) -> Vec<CreaseId> {
11235        self.display_map
11236            .update(cx, |map, cx| map.insert_creases(creases, cx))
11237    }
11238
11239    pub fn remove_creases(
11240        &mut self,
11241        ids: impl IntoIterator<Item = CreaseId>,
11242        cx: &mut ViewContext<Self>,
11243    ) {
11244        self.display_map
11245            .update(cx, |map, cx| map.remove_creases(ids, cx));
11246    }
11247
11248    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11249        self.display_map
11250            .update(cx, |map, cx| map.snapshot(cx))
11251            .longest_row()
11252    }
11253
11254    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11255        self.display_map
11256            .update(cx, |map, cx| map.snapshot(cx))
11257            .max_point()
11258    }
11259
11260    pub fn text(&self, cx: &AppContext) -> String {
11261        self.buffer.read(cx).read(cx).text()
11262    }
11263
11264    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11265        let text = self.text(cx);
11266        let text = text.trim();
11267
11268        if text.is_empty() {
11269            return None;
11270        }
11271
11272        Some(text.to_string())
11273    }
11274
11275    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11276        self.transact(cx, |this, cx| {
11277            this.buffer
11278                .read(cx)
11279                .as_singleton()
11280                .expect("you can only call set_text on editors for singleton buffers")
11281                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11282        });
11283    }
11284
11285    pub fn display_text(&self, cx: &mut AppContext) -> String {
11286        self.display_map
11287            .update(cx, |map, cx| map.snapshot(cx))
11288            .text()
11289    }
11290
11291    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11292        let mut wrap_guides = smallvec::smallvec![];
11293
11294        if self.show_wrap_guides == Some(false) {
11295            return wrap_guides;
11296        }
11297
11298        let settings = self.buffer.read(cx).settings_at(0, cx);
11299        if settings.show_wrap_guides {
11300            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11301                wrap_guides.push((soft_wrap as usize, true));
11302            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11303                wrap_guides.push((soft_wrap as usize, true));
11304            }
11305            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11306        }
11307
11308        wrap_guides
11309    }
11310
11311    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11312        let settings = self.buffer.read(cx).settings_at(0, cx);
11313        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11314        match mode {
11315            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11316                SoftWrap::None
11317            }
11318            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11319            language_settings::SoftWrap::PreferredLineLength => {
11320                SoftWrap::Column(settings.preferred_line_length)
11321            }
11322            language_settings::SoftWrap::Bounded => {
11323                SoftWrap::Bounded(settings.preferred_line_length)
11324            }
11325        }
11326    }
11327
11328    pub fn set_soft_wrap_mode(
11329        &mut self,
11330        mode: language_settings::SoftWrap,
11331        cx: &mut ViewContext<Self>,
11332    ) {
11333        self.soft_wrap_mode_override = Some(mode);
11334        cx.notify();
11335    }
11336
11337    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11338        self.text_style_refinement = Some(style);
11339    }
11340
11341    /// called by the Element so we know what style we were most recently rendered with.
11342    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11343        let rem_size = cx.rem_size();
11344        self.display_map.update(cx, |map, cx| {
11345            map.set_font(
11346                style.text.font(),
11347                style.text.font_size.to_pixels(rem_size),
11348                cx,
11349            )
11350        });
11351        self.style = Some(style);
11352    }
11353
11354    pub fn style(&self) -> Option<&EditorStyle> {
11355        self.style.as_ref()
11356    }
11357
11358    // Called by the element. This method is not designed to be called outside of the editor
11359    // element's layout code because it does not notify when rewrapping is computed synchronously.
11360    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11361        self.display_map
11362            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11363    }
11364
11365    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11366        if self.soft_wrap_mode_override.is_some() {
11367            self.soft_wrap_mode_override.take();
11368        } else {
11369            let soft_wrap = match self.soft_wrap_mode(cx) {
11370                SoftWrap::GitDiff => return,
11371                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11372                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11373                    language_settings::SoftWrap::None
11374                }
11375            };
11376            self.soft_wrap_mode_override = Some(soft_wrap);
11377        }
11378        cx.notify();
11379    }
11380
11381    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11382        let Some(workspace) = self.workspace() else {
11383            return;
11384        };
11385        let fs = workspace.read(cx).app_state().fs.clone();
11386        let current_show = TabBarSettings::get_global(cx).show;
11387        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11388            setting.show = Some(!current_show);
11389        });
11390    }
11391
11392    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11393        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11394            self.buffer
11395                .read(cx)
11396                .settings_at(0, cx)
11397                .indent_guides
11398                .enabled
11399        });
11400        self.show_indent_guides = Some(!currently_enabled);
11401        cx.notify();
11402    }
11403
11404    fn should_show_indent_guides(&self) -> Option<bool> {
11405        self.show_indent_guides
11406    }
11407
11408    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11409        let mut editor_settings = EditorSettings::get_global(cx).clone();
11410        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11411        EditorSettings::override_global(editor_settings, cx);
11412    }
11413
11414    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11415        self.use_relative_line_numbers
11416            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11417    }
11418
11419    pub fn toggle_relative_line_numbers(
11420        &mut self,
11421        _: &ToggleRelativeLineNumbers,
11422        cx: &mut ViewContext<Self>,
11423    ) {
11424        let is_relative = self.should_use_relative_line_numbers(cx);
11425        self.set_relative_line_number(Some(!is_relative), cx)
11426    }
11427
11428    pub fn set_relative_line_number(
11429        &mut self,
11430        is_relative: Option<bool>,
11431        cx: &mut ViewContext<Self>,
11432    ) {
11433        self.use_relative_line_numbers = is_relative;
11434        cx.notify();
11435    }
11436
11437    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11438        self.show_gutter = show_gutter;
11439        cx.notify();
11440    }
11441
11442    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11443        self.show_line_numbers = Some(show_line_numbers);
11444        cx.notify();
11445    }
11446
11447    pub fn set_show_git_diff_gutter(
11448        &mut self,
11449        show_git_diff_gutter: bool,
11450        cx: &mut ViewContext<Self>,
11451    ) {
11452        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11453        cx.notify();
11454    }
11455
11456    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11457        self.show_code_actions = Some(show_code_actions);
11458        cx.notify();
11459    }
11460
11461    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11462        self.show_runnables = Some(show_runnables);
11463        cx.notify();
11464    }
11465
11466    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11467        if self.display_map.read(cx).masked != masked {
11468            self.display_map.update(cx, |map, _| map.masked = masked);
11469        }
11470        cx.notify()
11471    }
11472
11473    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11474        self.show_wrap_guides = Some(show_wrap_guides);
11475        cx.notify();
11476    }
11477
11478    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11479        self.show_indent_guides = Some(show_indent_guides);
11480        cx.notify();
11481    }
11482
11483    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11484        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11485            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11486                if let Some(dir) = file.abs_path(cx).parent() {
11487                    return Some(dir.to_owned());
11488                }
11489            }
11490
11491            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11492                return Some(project_path.path.to_path_buf());
11493            }
11494        }
11495
11496        None
11497    }
11498
11499    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11500        self.active_excerpt(cx)?
11501            .1
11502            .read(cx)
11503            .file()
11504            .and_then(|f| f.as_local())
11505    }
11506
11507    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11508        if let Some(target) = self.target_file(cx) {
11509            cx.reveal_path(&target.abs_path(cx));
11510        }
11511    }
11512
11513    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11514        if let Some(file) = self.target_file(cx) {
11515            if let Some(path) = file.abs_path(cx).to_str() {
11516                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11517            }
11518        }
11519    }
11520
11521    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11522        if let Some(file) = self.target_file(cx) {
11523            if let Some(path) = file.path().to_str() {
11524                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11525            }
11526        }
11527    }
11528
11529    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11530        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11531
11532        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11533            self.start_git_blame(true, cx);
11534        }
11535
11536        cx.notify();
11537    }
11538
11539    pub fn toggle_git_blame_inline(
11540        &mut self,
11541        _: &ToggleGitBlameInline,
11542        cx: &mut ViewContext<Self>,
11543    ) {
11544        self.toggle_git_blame_inline_internal(true, cx);
11545        cx.notify();
11546    }
11547
11548    pub fn git_blame_inline_enabled(&self) -> bool {
11549        self.git_blame_inline_enabled
11550    }
11551
11552    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11553        self.show_selection_menu = self
11554            .show_selection_menu
11555            .map(|show_selections_menu| !show_selections_menu)
11556            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11557
11558        cx.notify();
11559    }
11560
11561    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11562        self.show_selection_menu
11563            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11564    }
11565
11566    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11567        if let Some(project) = self.project.as_ref() {
11568            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11569                return;
11570            };
11571
11572            if buffer.read(cx).file().is_none() {
11573                return;
11574            }
11575
11576            let focused = self.focus_handle(cx).contains_focused(cx);
11577
11578            let project = project.clone();
11579            let blame =
11580                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11581            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11582            self.blame = Some(blame);
11583        }
11584    }
11585
11586    fn toggle_git_blame_inline_internal(
11587        &mut self,
11588        user_triggered: bool,
11589        cx: &mut ViewContext<Self>,
11590    ) {
11591        if self.git_blame_inline_enabled {
11592            self.git_blame_inline_enabled = false;
11593            self.show_git_blame_inline = false;
11594            self.show_git_blame_inline_delay_task.take();
11595        } else {
11596            self.git_blame_inline_enabled = true;
11597            self.start_git_blame_inline(user_triggered, cx);
11598        }
11599
11600        cx.notify();
11601    }
11602
11603    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11604        self.start_git_blame(user_triggered, cx);
11605
11606        if ProjectSettings::get_global(cx)
11607            .git
11608            .inline_blame_delay()
11609            .is_some()
11610        {
11611            self.start_inline_blame_timer(cx);
11612        } else {
11613            self.show_git_blame_inline = true
11614        }
11615    }
11616
11617    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11618        self.blame.as_ref()
11619    }
11620
11621    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11622        self.show_git_blame_gutter && self.has_blame_entries(cx)
11623    }
11624
11625    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11626        self.show_git_blame_inline
11627            && self.focus_handle.is_focused(cx)
11628            && !self.newest_selection_head_on_empty_line(cx)
11629            && self.has_blame_entries(cx)
11630    }
11631
11632    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11633        self.blame()
11634            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11635    }
11636
11637    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11638        let cursor_anchor = self.selections.newest_anchor().head();
11639
11640        let snapshot = self.buffer.read(cx).snapshot(cx);
11641        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11642
11643        snapshot.line_len(buffer_row) == 0
11644    }
11645
11646    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11647        let buffer_and_selection = maybe!({
11648            let selection = self.selections.newest::<Point>(cx);
11649            let selection_range = selection.range();
11650
11651            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11652                (buffer, selection_range.start.row..selection_range.end.row)
11653            } else {
11654                let buffer_ranges = self
11655                    .buffer()
11656                    .read(cx)
11657                    .range_to_buffer_ranges(selection_range, cx);
11658
11659                let (buffer, range, _) = if selection.reversed {
11660                    buffer_ranges.first()
11661                } else {
11662                    buffer_ranges.last()
11663                }?;
11664
11665                let snapshot = buffer.read(cx).snapshot();
11666                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11667                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11668                (buffer.clone(), selection)
11669            };
11670
11671            Some((buffer, selection))
11672        });
11673
11674        let Some((buffer, selection)) = buffer_and_selection else {
11675            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11676        };
11677
11678        let Some(project) = self.project.as_ref() else {
11679            return Task::ready(Err(anyhow!("editor does not have project")));
11680        };
11681
11682        project.update(cx, |project, cx| {
11683            project.get_permalink_to_line(&buffer, selection, cx)
11684        })
11685    }
11686
11687    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11688        let permalink_task = self.get_permalink_to_line(cx);
11689        let workspace = self.workspace();
11690
11691        cx.spawn(|_, mut cx| async move {
11692            match permalink_task.await {
11693                Ok(permalink) => {
11694                    cx.update(|cx| {
11695                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11696                    })
11697                    .ok();
11698                }
11699                Err(err) => {
11700                    let message = format!("Failed to copy permalink: {err}");
11701
11702                    Err::<(), anyhow::Error>(err).log_err();
11703
11704                    if let Some(workspace) = workspace {
11705                        workspace
11706                            .update(&mut cx, |workspace, cx| {
11707                                struct CopyPermalinkToLine;
11708
11709                                workspace.show_toast(
11710                                    Toast::new(
11711                                        NotificationId::unique::<CopyPermalinkToLine>(),
11712                                        message,
11713                                    ),
11714                                    cx,
11715                                )
11716                            })
11717                            .ok();
11718                    }
11719                }
11720            }
11721        })
11722        .detach();
11723    }
11724
11725    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11726        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11727        if let Some(file) = self.target_file(cx) {
11728            if let Some(path) = file.path().to_str() {
11729                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11730            }
11731        }
11732    }
11733
11734    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11735        let permalink_task = self.get_permalink_to_line(cx);
11736        let workspace = self.workspace();
11737
11738        cx.spawn(|_, mut cx| async move {
11739            match permalink_task.await {
11740                Ok(permalink) => {
11741                    cx.update(|cx| {
11742                        cx.open_url(permalink.as_ref());
11743                    })
11744                    .ok();
11745                }
11746                Err(err) => {
11747                    let message = format!("Failed to open permalink: {err}");
11748
11749                    Err::<(), anyhow::Error>(err).log_err();
11750
11751                    if let Some(workspace) = workspace {
11752                        workspace
11753                            .update(&mut cx, |workspace, cx| {
11754                                struct OpenPermalinkToLine;
11755
11756                                workspace.show_toast(
11757                                    Toast::new(
11758                                        NotificationId::unique::<OpenPermalinkToLine>(),
11759                                        message,
11760                                    ),
11761                                    cx,
11762                                )
11763                            })
11764                            .ok();
11765                    }
11766                }
11767            }
11768        })
11769        .detach();
11770    }
11771
11772    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11773    /// last highlight added will be used.
11774    ///
11775    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11776    pub fn highlight_rows<T: 'static>(
11777        &mut self,
11778        range: Range<Anchor>,
11779        color: Hsla,
11780        should_autoscroll: bool,
11781        cx: &mut ViewContext<Self>,
11782    ) {
11783        let snapshot = self.buffer().read(cx).snapshot(cx);
11784        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11785        let ix = row_highlights.binary_search_by(|highlight| {
11786            Ordering::Equal
11787                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11788                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11789        });
11790
11791        if let Err(mut ix) = ix {
11792            let index = post_inc(&mut self.highlight_order);
11793
11794            // If this range intersects with the preceding highlight, then merge it with
11795            // the preceding highlight. Otherwise insert a new highlight.
11796            let mut merged = false;
11797            if ix > 0 {
11798                let prev_highlight = &mut row_highlights[ix - 1];
11799                if prev_highlight
11800                    .range
11801                    .end
11802                    .cmp(&range.start, &snapshot)
11803                    .is_ge()
11804                {
11805                    ix -= 1;
11806                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11807                        prev_highlight.range.end = range.end;
11808                    }
11809                    merged = true;
11810                    prev_highlight.index = index;
11811                    prev_highlight.color = color;
11812                    prev_highlight.should_autoscroll = should_autoscroll;
11813                }
11814            }
11815
11816            if !merged {
11817                row_highlights.insert(
11818                    ix,
11819                    RowHighlight {
11820                        range: range.clone(),
11821                        index,
11822                        color,
11823                        should_autoscroll,
11824                    },
11825                );
11826            }
11827
11828            // If any of the following highlights intersect with this one, merge them.
11829            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11830                let highlight = &row_highlights[ix];
11831                if next_highlight
11832                    .range
11833                    .start
11834                    .cmp(&highlight.range.end, &snapshot)
11835                    .is_le()
11836                {
11837                    if next_highlight
11838                        .range
11839                        .end
11840                        .cmp(&highlight.range.end, &snapshot)
11841                        .is_gt()
11842                    {
11843                        row_highlights[ix].range.end = next_highlight.range.end;
11844                    }
11845                    row_highlights.remove(ix + 1);
11846                } else {
11847                    break;
11848                }
11849            }
11850        }
11851    }
11852
11853    /// Remove any highlighted row ranges of the given type that intersect the
11854    /// given ranges.
11855    pub fn remove_highlighted_rows<T: 'static>(
11856        &mut self,
11857        ranges_to_remove: Vec<Range<Anchor>>,
11858        cx: &mut ViewContext<Self>,
11859    ) {
11860        let snapshot = self.buffer().read(cx).snapshot(cx);
11861        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11862        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11863        row_highlights.retain(|highlight| {
11864            while let Some(range_to_remove) = ranges_to_remove.peek() {
11865                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11866                    Ordering::Less | Ordering::Equal => {
11867                        ranges_to_remove.next();
11868                    }
11869                    Ordering::Greater => {
11870                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11871                            Ordering::Less | Ordering::Equal => {
11872                                return false;
11873                            }
11874                            Ordering::Greater => break,
11875                        }
11876                    }
11877                }
11878            }
11879
11880            true
11881        })
11882    }
11883
11884    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11885    pub fn clear_row_highlights<T: 'static>(&mut self) {
11886        self.highlighted_rows.remove(&TypeId::of::<T>());
11887    }
11888
11889    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11890    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11891        self.highlighted_rows
11892            .get(&TypeId::of::<T>())
11893            .map_or(&[] as &[_], |vec| vec.as_slice())
11894            .iter()
11895            .map(|highlight| (highlight.range.clone(), highlight.color))
11896    }
11897
11898    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11899    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11900    /// Allows to ignore certain kinds of highlights.
11901    pub fn highlighted_display_rows(
11902        &mut self,
11903        cx: &mut WindowContext,
11904    ) -> BTreeMap<DisplayRow, Hsla> {
11905        let snapshot = self.snapshot(cx);
11906        let mut used_highlight_orders = HashMap::default();
11907        self.highlighted_rows
11908            .iter()
11909            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11910            .fold(
11911                BTreeMap::<DisplayRow, Hsla>::new(),
11912                |mut unique_rows, highlight| {
11913                    let start = highlight.range.start.to_display_point(&snapshot);
11914                    let end = highlight.range.end.to_display_point(&snapshot);
11915                    let start_row = start.row().0;
11916                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11917                        && end.column() == 0
11918                    {
11919                        end.row().0.saturating_sub(1)
11920                    } else {
11921                        end.row().0
11922                    };
11923                    for row in start_row..=end_row {
11924                        let used_index =
11925                            used_highlight_orders.entry(row).or_insert(highlight.index);
11926                        if highlight.index >= *used_index {
11927                            *used_index = highlight.index;
11928                            unique_rows.insert(DisplayRow(row), highlight.color);
11929                        }
11930                    }
11931                    unique_rows
11932                },
11933            )
11934    }
11935
11936    pub fn highlighted_display_row_for_autoscroll(
11937        &self,
11938        snapshot: &DisplaySnapshot,
11939    ) -> Option<DisplayRow> {
11940        self.highlighted_rows
11941            .values()
11942            .flat_map(|highlighted_rows| highlighted_rows.iter())
11943            .filter_map(|highlight| {
11944                if highlight.should_autoscroll {
11945                    Some(highlight.range.start.to_display_point(snapshot).row())
11946                } else {
11947                    None
11948                }
11949            })
11950            .min()
11951    }
11952
11953    pub fn set_search_within_ranges(
11954        &mut self,
11955        ranges: &[Range<Anchor>],
11956        cx: &mut ViewContext<Self>,
11957    ) {
11958        self.highlight_background::<SearchWithinRange>(
11959            ranges,
11960            |colors| colors.editor_document_highlight_read_background,
11961            cx,
11962        )
11963    }
11964
11965    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11966        self.breadcrumb_header = Some(new_header);
11967    }
11968
11969    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11970        self.clear_background_highlights::<SearchWithinRange>(cx);
11971    }
11972
11973    pub fn highlight_background<T: 'static>(
11974        &mut self,
11975        ranges: &[Range<Anchor>],
11976        color_fetcher: fn(&ThemeColors) -> Hsla,
11977        cx: &mut ViewContext<Self>,
11978    ) {
11979        self.background_highlights
11980            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11981        self.scrollbar_marker_state.dirty = true;
11982        cx.notify();
11983    }
11984
11985    pub fn clear_background_highlights<T: 'static>(
11986        &mut self,
11987        cx: &mut ViewContext<Self>,
11988    ) -> Option<BackgroundHighlight> {
11989        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11990        if !text_highlights.1.is_empty() {
11991            self.scrollbar_marker_state.dirty = true;
11992            cx.notify();
11993        }
11994        Some(text_highlights)
11995    }
11996
11997    pub fn highlight_gutter<T: 'static>(
11998        &mut self,
11999        ranges: &[Range<Anchor>],
12000        color_fetcher: fn(&AppContext) -> Hsla,
12001        cx: &mut ViewContext<Self>,
12002    ) {
12003        self.gutter_highlights
12004            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12005        cx.notify();
12006    }
12007
12008    pub fn clear_gutter_highlights<T: 'static>(
12009        &mut self,
12010        cx: &mut ViewContext<Self>,
12011    ) -> Option<GutterHighlight> {
12012        cx.notify();
12013        self.gutter_highlights.remove(&TypeId::of::<T>())
12014    }
12015
12016    #[cfg(feature = "test-support")]
12017    pub fn all_text_background_highlights(
12018        &mut self,
12019        cx: &mut ViewContext<Self>,
12020    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12021        let snapshot = self.snapshot(cx);
12022        let buffer = &snapshot.buffer_snapshot;
12023        let start = buffer.anchor_before(0);
12024        let end = buffer.anchor_after(buffer.len());
12025        let theme = cx.theme().colors();
12026        self.background_highlights_in_range(start..end, &snapshot, theme)
12027    }
12028
12029    #[cfg(feature = "test-support")]
12030    pub fn search_background_highlights(
12031        &mut self,
12032        cx: &mut ViewContext<Self>,
12033    ) -> Vec<Range<Point>> {
12034        let snapshot = self.buffer().read(cx).snapshot(cx);
12035
12036        let highlights = self
12037            .background_highlights
12038            .get(&TypeId::of::<items::BufferSearchHighlights>());
12039
12040        if let Some((_color, ranges)) = highlights {
12041            ranges
12042                .iter()
12043                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12044                .collect_vec()
12045        } else {
12046            vec![]
12047        }
12048    }
12049
12050    fn document_highlights_for_position<'a>(
12051        &'a self,
12052        position: Anchor,
12053        buffer: &'a MultiBufferSnapshot,
12054    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12055        let read_highlights = self
12056            .background_highlights
12057            .get(&TypeId::of::<DocumentHighlightRead>())
12058            .map(|h| &h.1);
12059        let write_highlights = self
12060            .background_highlights
12061            .get(&TypeId::of::<DocumentHighlightWrite>())
12062            .map(|h| &h.1);
12063        let left_position = position.bias_left(buffer);
12064        let right_position = position.bias_right(buffer);
12065        read_highlights
12066            .into_iter()
12067            .chain(write_highlights)
12068            .flat_map(move |ranges| {
12069                let start_ix = match ranges.binary_search_by(|probe| {
12070                    let cmp = probe.end.cmp(&left_position, buffer);
12071                    if cmp.is_ge() {
12072                        Ordering::Greater
12073                    } else {
12074                        Ordering::Less
12075                    }
12076                }) {
12077                    Ok(i) | Err(i) => i,
12078                };
12079
12080                ranges[start_ix..]
12081                    .iter()
12082                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12083            })
12084    }
12085
12086    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12087        self.background_highlights
12088            .get(&TypeId::of::<T>())
12089            .map_or(false, |(_, highlights)| !highlights.is_empty())
12090    }
12091
12092    pub fn background_highlights_in_range(
12093        &self,
12094        search_range: Range<Anchor>,
12095        display_snapshot: &DisplaySnapshot,
12096        theme: &ThemeColors,
12097    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12098        let mut results = Vec::new();
12099        for (color_fetcher, ranges) in self.background_highlights.values() {
12100            let color = color_fetcher(theme);
12101            let start_ix = match ranges.binary_search_by(|probe| {
12102                let cmp = probe
12103                    .end
12104                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12105                if cmp.is_gt() {
12106                    Ordering::Greater
12107                } else {
12108                    Ordering::Less
12109                }
12110            }) {
12111                Ok(i) | Err(i) => i,
12112            };
12113            for range in &ranges[start_ix..] {
12114                if range
12115                    .start
12116                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12117                    .is_ge()
12118                {
12119                    break;
12120                }
12121
12122                let start = range.start.to_display_point(display_snapshot);
12123                let end = range.end.to_display_point(display_snapshot);
12124                results.push((start..end, color))
12125            }
12126        }
12127        results
12128    }
12129
12130    pub fn background_highlight_row_ranges<T: 'static>(
12131        &self,
12132        search_range: Range<Anchor>,
12133        display_snapshot: &DisplaySnapshot,
12134        count: usize,
12135    ) -> Vec<RangeInclusive<DisplayPoint>> {
12136        let mut results = Vec::new();
12137        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12138            return vec![];
12139        };
12140
12141        let start_ix = match ranges.binary_search_by(|probe| {
12142            let cmp = probe
12143                .end
12144                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12145            if cmp.is_gt() {
12146                Ordering::Greater
12147            } else {
12148                Ordering::Less
12149            }
12150        }) {
12151            Ok(i) | Err(i) => i,
12152        };
12153        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12154            if let (Some(start_display), Some(end_display)) = (start, end) {
12155                results.push(
12156                    start_display.to_display_point(display_snapshot)
12157                        ..=end_display.to_display_point(display_snapshot),
12158                );
12159            }
12160        };
12161        let mut start_row: Option<Point> = None;
12162        let mut end_row: Option<Point> = None;
12163        if ranges.len() > count {
12164            return Vec::new();
12165        }
12166        for range in &ranges[start_ix..] {
12167            if range
12168                .start
12169                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12170                .is_ge()
12171            {
12172                break;
12173            }
12174            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12175            if let Some(current_row) = &end_row {
12176                if end.row == current_row.row {
12177                    continue;
12178                }
12179            }
12180            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12181            if start_row.is_none() {
12182                assert_eq!(end_row, None);
12183                start_row = Some(start);
12184                end_row = Some(end);
12185                continue;
12186            }
12187            if let Some(current_end) = end_row.as_mut() {
12188                if start.row > current_end.row + 1 {
12189                    push_region(start_row, end_row);
12190                    start_row = Some(start);
12191                    end_row = Some(end);
12192                } else {
12193                    // Merge two hunks.
12194                    *current_end = end;
12195                }
12196            } else {
12197                unreachable!();
12198            }
12199        }
12200        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12201        push_region(start_row, end_row);
12202        results
12203    }
12204
12205    pub fn gutter_highlights_in_range(
12206        &self,
12207        search_range: Range<Anchor>,
12208        display_snapshot: &DisplaySnapshot,
12209        cx: &AppContext,
12210    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12211        let mut results = Vec::new();
12212        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12213            let color = color_fetcher(cx);
12214            let start_ix = match ranges.binary_search_by(|probe| {
12215                let cmp = probe
12216                    .end
12217                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12218                if cmp.is_gt() {
12219                    Ordering::Greater
12220                } else {
12221                    Ordering::Less
12222                }
12223            }) {
12224                Ok(i) | Err(i) => i,
12225            };
12226            for range in &ranges[start_ix..] {
12227                if range
12228                    .start
12229                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12230                    .is_ge()
12231                {
12232                    break;
12233                }
12234
12235                let start = range.start.to_display_point(display_snapshot);
12236                let end = range.end.to_display_point(display_snapshot);
12237                results.push((start..end, color))
12238            }
12239        }
12240        results
12241    }
12242
12243    /// Get the text ranges corresponding to the redaction query
12244    pub fn redacted_ranges(
12245        &self,
12246        search_range: Range<Anchor>,
12247        display_snapshot: &DisplaySnapshot,
12248        cx: &WindowContext,
12249    ) -> Vec<Range<DisplayPoint>> {
12250        display_snapshot
12251            .buffer_snapshot
12252            .redacted_ranges(search_range, |file| {
12253                if let Some(file) = file {
12254                    file.is_private()
12255                        && EditorSettings::get(
12256                            Some(SettingsLocation {
12257                                worktree_id: file.worktree_id(cx),
12258                                path: file.path().as_ref(),
12259                            }),
12260                            cx,
12261                        )
12262                        .redact_private_values
12263                } else {
12264                    false
12265                }
12266            })
12267            .map(|range| {
12268                range.start.to_display_point(display_snapshot)
12269                    ..range.end.to_display_point(display_snapshot)
12270            })
12271            .collect()
12272    }
12273
12274    pub fn highlight_text<T: 'static>(
12275        &mut self,
12276        ranges: Vec<Range<Anchor>>,
12277        style: HighlightStyle,
12278        cx: &mut ViewContext<Self>,
12279    ) {
12280        self.display_map.update(cx, |map, _| {
12281            map.highlight_text(TypeId::of::<T>(), ranges, style)
12282        });
12283        cx.notify();
12284    }
12285
12286    pub(crate) fn highlight_inlays<T: 'static>(
12287        &mut self,
12288        highlights: Vec<InlayHighlight>,
12289        style: HighlightStyle,
12290        cx: &mut ViewContext<Self>,
12291    ) {
12292        self.display_map.update(cx, |map, _| {
12293            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12294        });
12295        cx.notify();
12296    }
12297
12298    pub fn text_highlights<'a, T: 'static>(
12299        &'a self,
12300        cx: &'a AppContext,
12301    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12302        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12303    }
12304
12305    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12306        let cleared = self
12307            .display_map
12308            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12309        if cleared {
12310            cx.notify();
12311        }
12312    }
12313
12314    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12315        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12316            && self.focus_handle.is_focused(cx)
12317    }
12318
12319    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12320        self.show_cursor_when_unfocused = is_enabled;
12321        cx.notify();
12322    }
12323
12324    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12325        cx.notify();
12326    }
12327
12328    fn on_buffer_event(
12329        &mut self,
12330        multibuffer: Model<MultiBuffer>,
12331        event: &multi_buffer::Event,
12332        cx: &mut ViewContext<Self>,
12333    ) {
12334        match event {
12335            multi_buffer::Event::Edited {
12336                singleton_buffer_edited,
12337            } => {
12338                self.scrollbar_marker_state.dirty = true;
12339                self.active_indent_guides_state.dirty = true;
12340                self.refresh_active_diagnostics(cx);
12341                self.refresh_code_actions(cx);
12342                if self.has_active_inline_completion(cx) {
12343                    self.update_visible_inline_completion(cx);
12344                }
12345                cx.emit(EditorEvent::BufferEdited);
12346                cx.emit(SearchEvent::MatchesInvalidated);
12347                if *singleton_buffer_edited {
12348                    if let Some(project) = &self.project {
12349                        let project = project.read(cx);
12350                        #[allow(clippy::mutable_key_type)]
12351                        let languages_affected = multibuffer
12352                            .read(cx)
12353                            .all_buffers()
12354                            .into_iter()
12355                            .filter_map(|buffer| {
12356                                let buffer = buffer.read(cx);
12357                                let language = buffer.language()?;
12358                                if project.is_local()
12359                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12360                                {
12361                                    None
12362                                } else {
12363                                    Some(language)
12364                                }
12365                            })
12366                            .cloned()
12367                            .collect::<HashSet<_>>();
12368                        if !languages_affected.is_empty() {
12369                            self.refresh_inlay_hints(
12370                                InlayHintRefreshReason::BufferEdited(languages_affected),
12371                                cx,
12372                            );
12373                        }
12374                    }
12375                }
12376
12377                let Some(project) = &self.project else { return };
12378                let (telemetry, is_via_ssh) = {
12379                    let project = project.read(cx);
12380                    let telemetry = project.client().telemetry().clone();
12381                    let is_via_ssh = project.is_via_ssh();
12382                    (telemetry, is_via_ssh)
12383                };
12384                refresh_linked_ranges(self, cx);
12385                telemetry.log_edit_event("editor", is_via_ssh);
12386            }
12387            multi_buffer::Event::ExcerptsAdded {
12388                buffer,
12389                predecessor,
12390                excerpts,
12391            } => {
12392                self.tasks_update_task = Some(self.refresh_runnables(cx));
12393                cx.emit(EditorEvent::ExcerptsAdded {
12394                    buffer: buffer.clone(),
12395                    predecessor: *predecessor,
12396                    excerpts: excerpts.clone(),
12397                });
12398                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12399            }
12400            multi_buffer::Event::ExcerptsRemoved { ids } => {
12401                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12402                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12403            }
12404            multi_buffer::Event::ExcerptsEdited { ids } => {
12405                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12406            }
12407            multi_buffer::Event::ExcerptsExpanded { ids } => {
12408                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12409            }
12410            multi_buffer::Event::Reparsed(buffer_id) => {
12411                self.tasks_update_task = Some(self.refresh_runnables(cx));
12412
12413                cx.emit(EditorEvent::Reparsed(*buffer_id));
12414            }
12415            multi_buffer::Event::LanguageChanged(buffer_id) => {
12416                linked_editing_ranges::refresh_linked_ranges(self, cx);
12417                cx.emit(EditorEvent::Reparsed(*buffer_id));
12418                cx.notify();
12419            }
12420            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12421            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12422            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12423                cx.emit(EditorEvent::TitleChanged)
12424            }
12425            multi_buffer::Event::DiffBaseChanged => {
12426                self.scrollbar_marker_state.dirty = true;
12427                cx.emit(EditorEvent::DiffBaseChanged);
12428                cx.notify();
12429            }
12430            multi_buffer::Event::DiffUpdated { buffer } => {
12431                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12432                cx.notify();
12433            }
12434            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12435            multi_buffer::Event::DiagnosticsUpdated => {
12436                self.refresh_active_diagnostics(cx);
12437                self.scrollbar_marker_state.dirty = true;
12438                cx.notify();
12439            }
12440            _ => {}
12441        };
12442    }
12443
12444    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12445        cx.notify();
12446    }
12447
12448    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12449        self.tasks_update_task = Some(self.refresh_runnables(cx));
12450        self.refresh_inline_completion(true, false, cx);
12451        self.refresh_inlay_hints(
12452            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12453                self.selections.newest_anchor().head(),
12454                &self.buffer.read(cx).snapshot(cx),
12455                cx,
12456            )),
12457            cx,
12458        );
12459
12460        let old_cursor_shape = self.cursor_shape;
12461
12462        {
12463            let editor_settings = EditorSettings::get_global(cx);
12464            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12465            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12466            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12467        }
12468
12469        if old_cursor_shape != self.cursor_shape {
12470            cx.emit(EditorEvent::CursorShapeChanged);
12471        }
12472
12473        let project_settings = ProjectSettings::get_global(cx);
12474        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12475
12476        if self.mode == EditorMode::Full {
12477            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12478            if self.git_blame_inline_enabled != inline_blame_enabled {
12479                self.toggle_git_blame_inline_internal(false, cx);
12480            }
12481        }
12482
12483        cx.notify();
12484    }
12485
12486    pub fn set_searchable(&mut self, searchable: bool) {
12487        self.searchable = searchable;
12488    }
12489
12490    pub fn searchable(&self) -> bool {
12491        self.searchable
12492    }
12493
12494    fn open_proposed_changes_editor(
12495        &mut self,
12496        _: &OpenProposedChangesEditor,
12497        cx: &mut ViewContext<Self>,
12498    ) {
12499        let Some(workspace) = self.workspace() else {
12500            cx.propagate();
12501            return;
12502        };
12503
12504        let selections = self.selections.all::<usize>(cx);
12505        let buffer = self.buffer.read(cx);
12506        let mut new_selections_by_buffer = HashMap::default();
12507        for selection in selections {
12508            for (buffer, range, _) in
12509                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12510            {
12511                let mut range = range.to_point(buffer.read(cx));
12512                range.start.column = 0;
12513                range.end.column = buffer.read(cx).line_len(range.end.row);
12514                new_selections_by_buffer
12515                    .entry(buffer)
12516                    .or_insert(Vec::new())
12517                    .push(range)
12518            }
12519        }
12520
12521        let proposed_changes_buffers = new_selections_by_buffer
12522            .into_iter()
12523            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12524            .collect::<Vec<_>>();
12525        let proposed_changes_editor = cx.new_view(|cx| {
12526            ProposedChangesEditor::new(
12527                "Proposed changes",
12528                proposed_changes_buffers,
12529                self.project.clone(),
12530                cx,
12531            )
12532        });
12533
12534        cx.window_context().defer(move |cx| {
12535            workspace.update(cx, |workspace, cx| {
12536                workspace.active_pane().update(cx, |pane, cx| {
12537                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12538                });
12539            });
12540        });
12541    }
12542
12543    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12544        self.open_excerpts_common(true, cx)
12545    }
12546
12547    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12548        self.open_excerpts_common(false, cx)
12549    }
12550
12551    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12552        let selections = self.selections.all::<usize>(cx);
12553        let buffer = self.buffer.read(cx);
12554        if buffer.is_singleton() {
12555            cx.propagate();
12556            return;
12557        }
12558
12559        let Some(workspace) = self.workspace() else {
12560            cx.propagate();
12561            return;
12562        };
12563
12564        let mut new_selections_by_buffer = HashMap::default();
12565        for selection in selections {
12566            for (mut buffer_handle, mut range, _) in
12567                buffer.range_to_buffer_ranges(selection.range(), cx)
12568            {
12569                // When editing branch buffers, jump to the corresponding location
12570                // in their base buffer.
12571                let buffer = buffer_handle.read(cx);
12572                if let Some(base_buffer) = buffer.diff_base_buffer() {
12573                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12574                    buffer_handle = base_buffer;
12575                }
12576
12577                if selection.reversed {
12578                    mem::swap(&mut range.start, &mut range.end);
12579                }
12580                new_selections_by_buffer
12581                    .entry(buffer_handle)
12582                    .or_insert(Vec::new())
12583                    .push(range)
12584            }
12585        }
12586
12587        // We defer the pane interaction because we ourselves are a workspace item
12588        // and activating a new item causes the pane to call a method on us reentrantly,
12589        // which panics if we're on the stack.
12590        cx.window_context().defer(move |cx| {
12591            workspace.update(cx, |workspace, cx| {
12592                let pane = if split {
12593                    workspace.adjacent_pane(cx)
12594                } else {
12595                    workspace.active_pane().clone()
12596                };
12597
12598                for (buffer, ranges) in new_selections_by_buffer {
12599                    let editor =
12600                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12601                    editor.update(cx, |editor, cx| {
12602                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12603                            s.select_ranges(ranges);
12604                        });
12605                    });
12606                }
12607            })
12608        });
12609    }
12610
12611    fn jump(
12612        &mut self,
12613        path: ProjectPath,
12614        position: Point,
12615        anchor: language::Anchor,
12616        offset_from_top: u32,
12617        cx: &mut ViewContext<Self>,
12618    ) {
12619        let workspace = self.workspace();
12620        cx.spawn(|_, mut cx| async move {
12621            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12622            let editor = workspace.update(&mut cx, |workspace, cx| {
12623                // Reset the preview item id before opening the new item
12624                workspace.active_pane().update(cx, |pane, cx| {
12625                    pane.set_preview_item_id(None, cx);
12626                });
12627                workspace.open_path_preview(path, None, true, true, cx)
12628            })?;
12629            let editor = editor
12630                .await?
12631                .downcast::<Editor>()
12632                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12633                .downgrade();
12634            editor.update(&mut cx, |editor, cx| {
12635                let buffer = editor
12636                    .buffer()
12637                    .read(cx)
12638                    .as_singleton()
12639                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12640                let buffer = buffer.read(cx);
12641                let cursor = if buffer.can_resolve(&anchor) {
12642                    language::ToPoint::to_point(&anchor, buffer)
12643                } else {
12644                    buffer.clip_point(position, Bias::Left)
12645                };
12646
12647                let nav_history = editor.nav_history.take();
12648                editor.change_selections(
12649                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12650                    cx,
12651                    |s| {
12652                        s.select_ranges([cursor..cursor]);
12653                    },
12654                );
12655                editor.nav_history = nav_history;
12656
12657                anyhow::Ok(())
12658            })??;
12659
12660            anyhow::Ok(())
12661        })
12662        .detach_and_log_err(cx);
12663    }
12664
12665    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12666        let snapshot = self.buffer.read(cx).read(cx);
12667        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12668        Some(
12669            ranges
12670                .iter()
12671                .map(move |range| {
12672                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12673                })
12674                .collect(),
12675        )
12676    }
12677
12678    fn selection_replacement_ranges(
12679        &self,
12680        range: Range<OffsetUtf16>,
12681        cx: &mut AppContext,
12682    ) -> Vec<Range<OffsetUtf16>> {
12683        let selections = self.selections.all::<OffsetUtf16>(cx);
12684        let newest_selection = selections
12685            .iter()
12686            .max_by_key(|selection| selection.id)
12687            .unwrap();
12688        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12689        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12690        let snapshot = self.buffer.read(cx).read(cx);
12691        selections
12692            .into_iter()
12693            .map(|mut selection| {
12694                selection.start.0 =
12695                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12696                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12697                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12698                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12699            })
12700            .collect()
12701    }
12702
12703    fn report_editor_event(
12704        &self,
12705        operation: &'static str,
12706        file_extension: Option<String>,
12707        cx: &AppContext,
12708    ) {
12709        if cfg!(any(test, feature = "test-support")) {
12710            return;
12711        }
12712
12713        let Some(project) = &self.project else { return };
12714
12715        // If None, we are in a file without an extension
12716        let file = self
12717            .buffer
12718            .read(cx)
12719            .as_singleton()
12720            .and_then(|b| b.read(cx).file());
12721        let file_extension = file_extension.or(file
12722            .as_ref()
12723            .and_then(|file| Path::new(file.file_name(cx)).extension())
12724            .and_then(|e| e.to_str())
12725            .map(|a| a.to_string()));
12726
12727        let vim_mode = cx
12728            .global::<SettingsStore>()
12729            .raw_user_settings()
12730            .get("vim_mode")
12731            == Some(&serde_json::Value::Bool(true));
12732
12733        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12734            == language::language_settings::InlineCompletionProvider::Copilot;
12735        let copilot_enabled_for_language = self
12736            .buffer
12737            .read(cx)
12738            .settings_at(0, cx)
12739            .show_inline_completions;
12740
12741        let project = project.read(cx);
12742        let telemetry = project.client().telemetry().clone();
12743        telemetry.report_editor_event(
12744            file_extension,
12745            vim_mode,
12746            operation,
12747            copilot_enabled,
12748            copilot_enabled_for_language,
12749            project.is_via_ssh(),
12750        )
12751    }
12752
12753    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12754    /// with each line being an array of {text, highlight} objects.
12755    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12756        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12757            return;
12758        };
12759
12760        #[derive(Serialize)]
12761        struct Chunk<'a> {
12762            text: String,
12763            highlight: Option<&'a str>,
12764        }
12765
12766        let snapshot = buffer.read(cx).snapshot();
12767        let range = self
12768            .selected_text_range(false, cx)
12769            .and_then(|selection| {
12770                if selection.range.is_empty() {
12771                    None
12772                } else {
12773                    Some(selection.range)
12774                }
12775            })
12776            .unwrap_or_else(|| 0..snapshot.len());
12777
12778        let chunks = snapshot.chunks(range, true);
12779        let mut lines = Vec::new();
12780        let mut line: VecDeque<Chunk> = VecDeque::new();
12781
12782        let Some(style) = self.style.as_ref() else {
12783            return;
12784        };
12785
12786        for chunk in chunks {
12787            let highlight = chunk
12788                .syntax_highlight_id
12789                .and_then(|id| id.name(&style.syntax));
12790            let mut chunk_lines = chunk.text.split('\n').peekable();
12791            while let Some(text) = chunk_lines.next() {
12792                let mut merged_with_last_token = false;
12793                if let Some(last_token) = line.back_mut() {
12794                    if last_token.highlight == highlight {
12795                        last_token.text.push_str(text);
12796                        merged_with_last_token = true;
12797                    }
12798                }
12799
12800                if !merged_with_last_token {
12801                    line.push_back(Chunk {
12802                        text: text.into(),
12803                        highlight,
12804                    });
12805                }
12806
12807                if chunk_lines.peek().is_some() {
12808                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12809                        line.pop_front();
12810                    }
12811                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12812                        line.pop_back();
12813                    }
12814
12815                    lines.push(mem::take(&mut line));
12816                }
12817            }
12818        }
12819
12820        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12821            return;
12822        };
12823        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12824    }
12825
12826    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12827        &self.inlay_hint_cache
12828    }
12829
12830    pub fn replay_insert_event(
12831        &mut self,
12832        text: &str,
12833        relative_utf16_range: Option<Range<isize>>,
12834        cx: &mut ViewContext<Self>,
12835    ) {
12836        if !self.input_enabled {
12837            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12838            return;
12839        }
12840        if let Some(relative_utf16_range) = relative_utf16_range {
12841            let selections = self.selections.all::<OffsetUtf16>(cx);
12842            self.change_selections(None, cx, |s| {
12843                let new_ranges = selections.into_iter().map(|range| {
12844                    let start = OffsetUtf16(
12845                        range
12846                            .head()
12847                            .0
12848                            .saturating_add_signed(relative_utf16_range.start),
12849                    );
12850                    let end = OffsetUtf16(
12851                        range
12852                            .head()
12853                            .0
12854                            .saturating_add_signed(relative_utf16_range.end),
12855                    );
12856                    start..end
12857                });
12858                s.select_ranges(new_ranges);
12859            });
12860        }
12861
12862        self.handle_input(text, cx);
12863    }
12864
12865    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12866        let Some(provider) = self.semantics_provider.as_ref() else {
12867            return false;
12868        };
12869
12870        let mut supports = false;
12871        self.buffer().read(cx).for_each_buffer(|buffer| {
12872            supports |= provider.supports_inlay_hints(buffer, cx);
12873        });
12874        supports
12875    }
12876
12877    pub fn focus(&self, cx: &mut WindowContext) {
12878        cx.focus(&self.focus_handle)
12879    }
12880
12881    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12882        self.focus_handle.is_focused(cx)
12883    }
12884
12885    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12886        cx.emit(EditorEvent::Focused);
12887
12888        if let Some(descendant) = self
12889            .last_focused_descendant
12890            .take()
12891            .and_then(|descendant| descendant.upgrade())
12892        {
12893            cx.focus(&descendant);
12894        } else {
12895            if let Some(blame) = self.blame.as_ref() {
12896                blame.update(cx, GitBlame::focus)
12897            }
12898
12899            self.blink_manager.update(cx, BlinkManager::enable);
12900            self.show_cursor_names(cx);
12901            self.buffer.update(cx, |buffer, cx| {
12902                buffer.finalize_last_transaction(cx);
12903                if self.leader_peer_id.is_none() {
12904                    buffer.set_active_selections(
12905                        &self.selections.disjoint_anchors(),
12906                        self.selections.line_mode,
12907                        self.cursor_shape,
12908                        cx,
12909                    );
12910                }
12911            });
12912        }
12913    }
12914
12915    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12916        cx.emit(EditorEvent::FocusedIn)
12917    }
12918
12919    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12920        if event.blurred != self.focus_handle {
12921            self.last_focused_descendant = Some(event.blurred);
12922        }
12923    }
12924
12925    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12926        self.blink_manager.update(cx, BlinkManager::disable);
12927        self.buffer
12928            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12929
12930        if let Some(blame) = self.blame.as_ref() {
12931            blame.update(cx, GitBlame::blur)
12932        }
12933        if !self.hover_state.focused(cx) {
12934            hide_hover(self, cx);
12935        }
12936
12937        self.hide_context_menu(cx);
12938        cx.emit(EditorEvent::Blurred);
12939        cx.notify();
12940    }
12941
12942    pub fn register_action<A: Action>(
12943        &mut self,
12944        listener: impl Fn(&A, &mut WindowContext) + 'static,
12945    ) -> Subscription {
12946        let id = self.next_editor_action_id.post_inc();
12947        let listener = Arc::new(listener);
12948        self.editor_actions.borrow_mut().insert(
12949            id,
12950            Box::new(move |cx| {
12951                let cx = cx.window_context();
12952                let listener = listener.clone();
12953                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12954                    let action = action.downcast_ref().unwrap();
12955                    if phase == DispatchPhase::Bubble {
12956                        listener(action, cx)
12957                    }
12958                })
12959            }),
12960        );
12961
12962        let editor_actions = self.editor_actions.clone();
12963        Subscription::new(move || {
12964            editor_actions.borrow_mut().remove(&id);
12965        })
12966    }
12967
12968    pub fn file_header_size(&self) -> u32 {
12969        FILE_HEADER_HEIGHT
12970    }
12971
12972    pub fn revert(
12973        &mut self,
12974        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12975        cx: &mut ViewContext<Self>,
12976    ) {
12977        self.buffer().update(cx, |multi_buffer, cx| {
12978            for (buffer_id, changes) in revert_changes {
12979                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12980                    buffer.update(cx, |buffer, cx| {
12981                        buffer.edit(
12982                            changes.into_iter().map(|(range, text)| {
12983                                (range, text.to_string().map(Arc::<str>::from))
12984                            }),
12985                            None,
12986                            cx,
12987                        );
12988                    });
12989                }
12990            }
12991        });
12992        self.change_selections(None, cx, |selections| selections.refresh());
12993    }
12994
12995    pub fn to_pixel_point(
12996        &mut self,
12997        source: multi_buffer::Anchor,
12998        editor_snapshot: &EditorSnapshot,
12999        cx: &mut ViewContext<Self>,
13000    ) -> Option<gpui::Point<Pixels>> {
13001        let source_point = source.to_display_point(editor_snapshot);
13002        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13003    }
13004
13005    pub fn display_to_pixel_point(
13006        &mut self,
13007        source: DisplayPoint,
13008        editor_snapshot: &EditorSnapshot,
13009        cx: &mut ViewContext<Self>,
13010    ) -> Option<gpui::Point<Pixels>> {
13011        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13012        let text_layout_details = self.text_layout_details(cx);
13013        let scroll_top = text_layout_details
13014            .scroll_anchor
13015            .scroll_position(editor_snapshot)
13016            .y;
13017
13018        if source.row().as_f32() < scroll_top.floor() {
13019            return None;
13020        }
13021        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13022        let source_y = line_height * (source.row().as_f32() - scroll_top);
13023        Some(gpui::Point::new(source_x, source_y))
13024    }
13025
13026    pub fn has_active_completions_menu(&self) -> bool {
13027        self.context_menu.read().as_ref().map_or(false, |menu| {
13028            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13029        })
13030    }
13031
13032    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13033        self.addons
13034            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13035    }
13036
13037    pub fn unregister_addon<T: Addon>(&mut self) {
13038        self.addons.remove(&std::any::TypeId::of::<T>());
13039    }
13040
13041    pub fn addon<T: Addon>(&self) -> Option<&T> {
13042        let type_id = std::any::TypeId::of::<T>();
13043        self.addons
13044            .get(&type_id)
13045            .and_then(|item| item.to_any().downcast_ref::<T>())
13046    }
13047}
13048
13049fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13050    let tab_size = tab_size.get() as usize;
13051    let mut width = offset;
13052
13053    for ch in text.chars() {
13054        width += if ch == '\t' {
13055            tab_size - (width % tab_size)
13056        } else {
13057            1
13058        };
13059    }
13060
13061    width - offset
13062}
13063
13064#[cfg(test)]
13065mod tests {
13066    use super::*;
13067
13068    #[test]
13069    fn test_string_size_with_expanded_tabs() {
13070        let nz = |val| NonZeroU32::new(val).unwrap();
13071        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13072        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13073        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13074        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13075        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13076        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13077        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13078        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13079    }
13080}
13081
13082/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13083struct WordBreakingTokenizer<'a> {
13084    input: &'a str,
13085}
13086
13087impl<'a> WordBreakingTokenizer<'a> {
13088    fn new(input: &'a str) -> Self {
13089        Self { input }
13090    }
13091}
13092
13093fn is_char_ideographic(ch: char) -> bool {
13094    use unicode_script::Script::*;
13095    use unicode_script::UnicodeScript;
13096    matches!(ch.script(), Han | Tangut | Yi)
13097}
13098
13099fn is_grapheme_ideographic(text: &str) -> bool {
13100    text.chars().any(is_char_ideographic)
13101}
13102
13103fn is_grapheme_whitespace(text: &str) -> bool {
13104    text.chars().any(|x| x.is_whitespace())
13105}
13106
13107fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13108    text.chars().next().map_or(false, |ch| {
13109        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13110    })
13111}
13112
13113#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13114struct WordBreakToken<'a> {
13115    token: &'a str,
13116    grapheme_len: usize,
13117    is_whitespace: bool,
13118}
13119
13120impl<'a> Iterator for WordBreakingTokenizer<'a> {
13121    /// Yields a span, the count of graphemes in the token, and whether it was
13122    /// whitespace. Note that it also breaks at word boundaries.
13123    type Item = WordBreakToken<'a>;
13124
13125    fn next(&mut self) -> Option<Self::Item> {
13126        use unicode_segmentation::UnicodeSegmentation;
13127        if self.input.is_empty() {
13128            return None;
13129        }
13130
13131        let mut iter = self.input.graphemes(true).peekable();
13132        let mut offset = 0;
13133        let mut graphemes = 0;
13134        if let Some(first_grapheme) = iter.next() {
13135            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13136            offset += first_grapheme.len();
13137            graphemes += 1;
13138            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13139                if let Some(grapheme) = iter.peek().copied() {
13140                    if should_stay_with_preceding_ideograph(grapheme) {
13141                        offset += grapheme.len();
13142                        graphemes += 1;
13143                    }
13144                }
13145            } else {
13146                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13147                let mut next_word_bound = words.peek().copied();
13148                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13149                    next_word_bound = words.next();
13150                }
13151                while let Some(grapheme) = iter.peek().copied() {
13152                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13153                        break;
13154                    };
13155                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13156                        break;
13157                    };
13158                    offset += grapheme.len();
13159                    graphemes += 1;
13160                    iter.next();
13161                }
13162            }
13163            let token = &self.input[..offset];
13164            self.input = &self.input[offset..];
13165            if is_whitespace {
13166                Some(WordBreakToken {
13167                    token: " ",
13168                    grapheme_len: 1,
13169                    is_whitespace: true,
13170                })
13171            } else {
13172                Some(WordBreakToken {
13173                    token,
13174                    grapheme_len: graphemes,
13175                    is_whitespace: false,
13176                })
13177            }
13178        } else {
13179            None
13180        }
13181    }
13182}
13183
13184#[test]
13185fn test_word_breaking_tokenizer() {
13186    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13187        ("", &[]),
13188        ("  ", &[(" ", 1, true)]),
13189        ("Ʒ", &[("Ʒ", 1, false)]),
13190        ("Ǽ", &[("Ǽ", 1, false)]),
13191        ("", &[("", 1, false)]),
13192        ("⋑⋑", &[("⋑⋑", 2, false)]),
13193        (
13194            "原理,进而",
13195            &[
13196                ("", 1, false),
13197                ("理,", 2, false),
13198                ("", 1, false),
13199                ("", 1, false),
13200            ],
13201        ),
13202        (
13203            "hello world",
13204            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13205        ),
13206        (
13207            "hello, world",
13208            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13209        ),
13210        (
13211            "  hello world",
13212            &[
13213                (" ", 1, true),
13214                ("hello", 5, false),
13215                (" ", 1, true),
13216                ("world", 5, false),
13217            ],
13218        ),
13219        (
13220            "这是什么 \n 钢笔",
13221            &[
13222                ("", 1, false),
13223                ("", 1, false),
13224                ("", 1, false),
13225                ("", 1, false),
13226                (" ", 1, true),
13227                ("", 1, false),
13228                ("", 1, false),
13229            ],
13230        ),
13231        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13232    ];
13233
13234    for (input, result) in tests {
13235        assert_eq!(
13236            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13237            result
13238                .iter()
13239                .copied()
13240                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13241                    token,
13242                    grapheme_len,
13243                    is_whitespace,
13244                })
13245                .collect::<Vec<_>>()
13246        );
13247    }
13248}
13249
13250fn wrap_with_prefix(
13251    line_prefix: String,
13252    unwrapped_text: String,
13253    wrap_column: usize,
13254    tab_size: NonZeroU32,
13255) -> String {
13256    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13257    let mut wrapped_text = String::new();
13258    let mut current_line = line_prefix.clone();
13259
13260    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13261    let mut current_line_len = line_prefix_len;
13262    for WordBreakToken {
13263        token,
13264        grapheme_len,
13265        is_whitespace,
13266    } in tokenizer
13267    {
13268        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13269            wrapped_text.push_str(current_line.trim_end());
13270            wrapped_text.push('\n');
13271            current_line.truncate(line_prefix.len());
13272            current_line_len = line_prefix_len;
13273            if !is_whitespace {
13274                current_line.push_str(token);
13275                current_line_len += grapheme_len;
13276            }
13277        } else if !is_whitespace {
13278            current_line.push_str(token);
13279            current_line_len += grapheme_len;
13280        } else if current_line_len != line_prefix_len {
13281            current_line.push(' ');
13282            current_line_len += 1;
13283        }
13284    }
13285
13286    if !current_line.is_empty() {
13287        wrapped_text.push_str(&current_line);
13288    }
13289    wrapped_text
13290}
13291
13292#[test]
13293fn test_wrap_with_prefix() {
13294    assert_eq!(
13295        wrap_with_prefix(
13296            "# ".to_string(),
13297            "abcdefg".to_string(),
13298            4,
13299            NonZeroU32::new(4).unwrap()
13300        ),
13301        "# abcdefg"
13302    );
13303    assert_eq!(
13304        wrap_with_prefix(
13305            "".to_string(),
13306            "\thello world".to_string(),
13307            8,
13308            NonZeroU32::new(4).unwrap()
13309        ),
13310        "hello\nworld"
13311    );
13312    assert_eq!(
13313        wrap_with_prefix(
13314            "// ".to_string(),
13315            "xx \nyy zz aa bb cc".to_string(),
13316            12,
13317            NonZeroU32::new(4).unwrap()
13318        ),
13319        "// xx yy zz\n// aa bb cc"
13320    );
13321    assert_eq!(
13322        wrap_with_prefix(
13323            String::new(),
13324            "这是什么 \n 钢笔".to_string(),
13325            3,
13326            NonZeroU32::new(4).unwrap()
13327        ),
13328        "这是什\n么 钢\n"
13329    );
13330}
13331
13332fn hunks_for_selections(
13333    multi_buffer_snapshot: &MultiBufferSnapshot,
13334    selections: &[Selection<Anchor>],
13335) -> Vec<MultiBufferDiffHunk> {
13336    let buffer_rows_for_selections = selections.iter().map(|selection| {
13337        let head = selection.head();
13338        let tail = selection.tail();
13339        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13340        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13341        if start > end {
13342            end..start
13343        } else {
13344            start..end
13345        }
13346    });
13347
13348    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13349}
13350
13351pub fn hunks_for_rows(
13352    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13353    multi_buffer_snapshot: &MultiBufferSnapshot,
13354) -> Vec<MultiBufferDiffHunk> {
13355    let mut hunks = Vec::new();
13356    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13357        HashMap::default();
13358    for selected_multi_buffer_rows in rows {
13359        let query_rows =
13360            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13361        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13362            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13363            // when the caret is just above or just below the deleted hunk.
13364            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13365            let related_to_selection = if allow_adjacent {
13366                hunk.row_range.overlaps(&query_rows)
13367                    || hunk.row_range.start == query_rows.end
13368                    || hunk.row_range.end == query_rows.start
13369            } else {
13370                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13371                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13372                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13373                    || selected_multi_buffer_rows.end == hunk.row_range.start
13374            };
13375            if related_to_selection {
13376                if !processed_buffer_rows
13377                    .entry(hunk.buffer_id)
13378                    .or_default()
13379                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13380                {
13381                    continue;
13382                }
13383                hunks.push(hunk);
13384            }
13385        }
13386    }
13387
13388    hunks
13389}
13390
13391pub trait CollaborationHub {
13392    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13393    fn user_participant_indices<'a>(
13394        &self,
13395        cx: &'a AppContext,
13396    ) -> &'a HashMap<u64, ParticipantIndex>;
13397    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13398}
13399
13400impl CollaborationHub for Model<Project> {
13401    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13402        self.read(cx).collaborators()
13403    }
13404
13405    fn user_participant_indices<'a>(
13406        &self,
13407        cx: &'a AppContext,
13408    ) -> &'a HashMap<u64, ParticipantIndex> {
13409        self.read(cx).user_store().read(cx).participant_indices()
13410    }
13411
13412    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13413        let this = self.read(cx);
13414        let user_ids = this.collaborators().values().map(|c| c.user_id);
13415        this.user_store().read_with(cx, |user_store, cx| {
13416            user_store.participant_names(user_ids, cx)
13417        })
13418    }
13419}
13420
13421pub trait SemanticsProvider {
13422    fn hover(
13423        &self,
13424        buffer: &Model<Buffer>,
13425        position: text::Anchor,
13426        cx: &mut AppContext,
13427    ) -> Option<Task<Vec<project::Hover>>>;
13428
13429    fn inlay_hints(
13430        &self,
13431        buffer_handle: Model<Buffer>,
13432        range: Range<text::Anchor>,
13433        cx: &mut AppContext,
13434    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13435
13436    fn resolve_inlay_hint(
13437        &self,
13438        hint: InlayHint,
13439        buffer_handle: Model<Buffer>,
13440        server_id: LanguageServerId,
13441        cx: &mut AppContext,
13442    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13443
13444    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13445
13446    fn document_highlights(
13447        &self,
13448        buffer: &Model<Buffer>,
13449        position: text::Anchor,
13450        cx: &mut AppContext,
13451    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13452
13453    fn definitions(
13454        &self,
13455        buffer: &Model<Buffer>,
13456        position: text::Anchor,
13457        kind: GotoDefinitionKind,
13458        cx: &mut AppContext,
13459    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13460
13461    fn range_for_rename(
13462        &self,
13463        buffer: &Model<Buffer>,
13464        position: text::Anchor,
13465        cx: &mut AppContext,
13466    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13467
13468    fn perform_rename(
13469        &self,
13470        buffer: &Model<Buffer>,
13471        position: text::Anchor,
13472        new_name: String,
13473        cx: &mut AppContext,
13474    ) -> Option<Task<Result<ProjectTransaction>>>;
13475}
13476
13477pub trait CompletionProvider {
13478    fn completions(
13479        &self,
13480        buffer: &Model<Buffer>,
13481        buffer_position: text::Anchor,
13482        trigger: CompletionContext,
13483        cx: &mut ViewContext<Editor>,
13484    ) -> Task<Result<Vec<Completion>>>;
13485
13486    fn resolve_completions(
13487        &self,
13488        buffer: Model<Buffer>,
13489        completion_indices: Vec<usize>,
13490        completions: Arc<RwLock<Box<[Completion]>>>,
13491        cx: &mut ViewContext<Editor>,
13492    ) -> Task<Result<bool>>;
13493
13494    fn apply_additional_edits_for_completion(
13495        &self,
13496        buffer: Model<Buffer>,
13497        completion: Completion,
13498        push_to_history: bool,
13499        cx: &mut ViewContext<Editor>,
13500    ) -> Task<Result<Option<language::Transaction>>>;
13501
13502    fn is_completion_trigger(
13503        &self,
13504        buffer: &Model<Buffer>,
13505        position: language::Anchor,
13506        text: &str,
13507        trigger_in_words: bool,
13508        cx: &mut ViewContext<Editor>,
13509    ) -> bool;
13510
13511    fn sort_completions(&self) -> bool {
13512        true
13513    }
13514}
13515
13516pub trait CodeActionProvider {
13517    fn code_actions(
13518        &self,
13519        buffer: &Model<Buffer>,
13520        range: Range<text::Anchor>,
13521        cx: &mut WindowContext,
13522    ) -> Task<Result<Vec<CodeAction>>>;
13523
13524    fn apply_code_action(
13525        &self,
13526        buffer_handle: Model<Buffer>,
13527        action: CodeAction,
13528        excerpt_id: ExcerptId,
13529        push_to_history: bool,
13530        cx: &mut WindowContext,
13531    ) -> Task<Result<ProjectTransaction>>;
13532}
13533
13534impl CodeActionProvider for Model<Project> {
13535    fn code_actions(
13536        &self,
13537        buffer: &Model<Buffer>,
13538        range: Range<text::Anchor>,
13539        cx: &mut WindowContext,
13540    ) -> Task<Result<Vec<CodeAction>>> {
13541        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13542    }
13543
13544    fn apply_code_action(
13545        &self,
13546        buffer_handle: Model<Buffer>,
13547        action: CodeAction,
13548        _excerpt_id: ExcerptId,
13549        push_to_history: bool,
13550        cx: &mut WindowContext,
13551    ) -> Task<Result<ProjectTransaction>> {
13552        self.update(cx, |project, cx| {
13553            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13554        })
13555    }
13556}
13557
13558fn snippet_completions(
13559    project: &Project,
13560    buffer: &Model<Buffer>,
13561    buffer_position: text::Anchor,
13562    cx: &mut AppContext,
13563) -> Vec<Completion> {
13564    let language = buffer.read(cx).language_at(buffer_position);
13565    let language_name = language.as_ref().map(|language| language.lsp_id());
13566    let snippet_store = project.snippets().read(cx);
13567    let snippets = snippet_store.snippets_for(language_name, cx);
13568
13569    if snippets.is_empty() {
13570        return vec![];
13571    }
13572    let snapshot = buffer.read(cx).text_snapshot();
13573    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13574
13575    let scope = language.map(|language| language.default_scope());
13576    let classifier = CharClassifier::new(scope).for_completion(true);
13577    let mut last_word = chars
13578        .take_while(|c| classifier.is_word(*c))
13579        .collect::<String>();
13580    last_word = last_word.chars().rev().collect();
13581    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13582    let to_lsp = |point: &text::Anchor| {
13583        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13584        point_to_lsp(end)
13585    };
13586    let lsp_end = to_lsp(&buffer_position);
13587    snippets
13588        .into_iter()
13589        .filter_map(|snippet| {
13590            let matching_prefix = snippet
13591                .prefix
13592                .iter()
13593                .find(|prefix| prefix.starts_with(&last_word))?;
13594            let start = as_offset - last_word.len();
13595            let start = snapshot.anchor_before(start);
13596            let range = start..buffer_position;
13597            let lsp_start = to_lsp(&start);
13598            let lsp_range = lsp::Range {
13599                start: lsp_start,
13600                end: lsp_end,
13601            };
13602            Some(Completion {
13603                old_range: range,
13604                new_text: snippet.body.clone(),
13605                label: CodeLabel {
13606                    text: matching_prefix.clone(),
13607                    runs: vec![],
13608                    filter_range: 0..matching_prefix.len(),
13609                },
13610                server_id: LanguageServerId(usize::MAX),
13611                documentation: snippet.description.clone().map(Documentation::SingleLine),
13612                lsp_completion: lsp::CompletionItem {
13613                    label: snippet.prefix.first().unwrap().clone(),
13614                    kind: Some(CompletionItemKind::SNIPPET),
13615                    label_details: snippet.description.as_ref().map(|description| {
13616                        lsp::CompletionItemLabelDetails {
13617                            detail: Some(description.clone()),
13618                            description: None,
13619                        }
13620                    }),
13621                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13622                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13623                        lsp::InsertReplaceEdit {
13624                            new_text: snippet.body.clone(),
13625                            insert: lsp_range,
13626                            replace: lsp_range,
13627                        },
13628                    )),
13629                    filter_text: Some(snippet.body.clone()),
13630                    sort_text: Some(char::MAX.to_string()),
13631                    ..Default::default()
13632                },
13633                confirm: None,
13634            })
13635        })
13636        .collect()
13637}
13638
13639impl CompletionProvider for Model<Project> {
13640    fn completions(
13641        &self,
13642        buffer: &Model<Buffer>,
13643        buffer_position: text::Anchor,
13644        options: CompletionContext,
13645        cx: &mut ViewContext<Editor>,
13646    ) -> Task<Result<Vec<Completion>>> {
13647        self.update(cx, |project, cx| {
13648            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13649            let project_completions = project.completions(buffer, buffer_position, options, cx);
13650            cx.background_executor().spawn(async move {
13651                let mut completions = project_completions.await?;
13652                //let snippets = snippets.into_iter().;
13653                completions.extend(snippets);
13654                Ok(completions)
13655            })
13656        })
13657    }
13658
13659    fn resolve_completions(
13660        &self,
13661        buffer: Model<Buffer>,
13662        completion_indices: Vec<usize>,
13663        completions: Arc<RwLock<Box<[Completion]>>>,
13664        cx: &mut ViewContext<Editor>,
13665    ) -> Task<Result<bool>> {
13666        self.update(cx, |project, cx| {
13667            project.resolve_completions(buffer, completion_indices, completions, cx)
13668        })
13669    }
13670
13671    fn apply_additional_edits_for_completion(
13672        &self,
13673        buffer: Model<Buffer>,
13674        completion: Completion,
13675        push_to_history: bool,
13676        cx: &mut ViewContext<Editor>,
13677    ) -> Task<Result<Option<language::Transaction>>> {
13678        self.update(cx, |project, cx| {
13679            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13680        })
13681    }
13682
13683    fn is_completion_trigger(
13684        &self,
13685        buffer: &Model<Buffer>,
13686        position: language::Anchor,
13687        text: &str,
13688        trigger_in_words: bool,
13689        cx: &mut ViewContext<Editor>,
13690    ) -> bool {
13691        if !EditorSettings::get_global(cx).show_completions_on_input {
13692            return false;
13693        }
13694
13695        let mut chars = text.chars();
13696        let char = if let Some(char) = chars.next() {
13697            char
13698        } else {
13699            return false;
13700        };
13701        if chars.next().is_some() {
13702            return false;
13703        }
13704
13705        let buffer = buffer.read(cx);
13706        let classifier = buffer
13707            .snapshot()
13708            .char_classifier_at(position)
13709            .for_completion(true);
13710        if trigger_in_words && classifier.is_word(char) {
13711            return true;
13712        }
13713
13714        buffer
13715            .completion_triggers()
13716            .iter()
13717            .any(|string| string == text)
13718    }
13719}
13720
13721impl SemanticsProvider for Model<Project> {
13722    fn hover(
13723        &self,
13724        buffer: &Model<Buffer>,
13725        position: text::Anchor,
13726        cx: &mut AppContext,
13727    ) -> Option<Task<Vec<project::Hover>>> {
13728        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13729    }
13730
13731    fn document_highlights(
13732        &self,
13733        buffer: &Model<Buffer>,
13734        position: text::Anchor,
13735        cx: &mut AppContext,
13736    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13737        Some(self.update(cx, |project, cx| {
13738            project.document_highlights(buffer, position, cx)
13739        }))
13740    }
13741
13742    fn definitions(
13743        &self,
13744        buffer: &Model<Buffer>,
13745        position: text::Anchor,
13746        kind: GotoDefinitionKind,
13747        cx: &mut AppContext,
13748    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13749        Some(self.update(cx, |project, cx| match kind {
13750            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13751            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13752            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13753            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13754        }))
13755    }
13756
13757    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13758        // TODO: make this work for remote projects
13759        self.read(cx)
13760            .language_servers_for_buffer(buffer.read(cx), cx)
13761            .any(
13762                |(_, server)| match server.capabilities().inlay_hint_provider {
13763                    Some(lsp::OneOf::Left(enabled)) => enabled,
13764                    Some(lsp::OneOf::Right(_)) => true,
13765                    None => false,
13766                },
13767            )
13768    }
13769
13770    fn inlay_hints(
13771        &self,
13772        buffer_handle: Model<Buffer>,
13773        range: Range<text::Anchor>,
13774        cx: &mut AppContext,
13775    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13776        Some(self.update(cx, |project, cx| {
13777            project.inlay_hints(buffer_handle, range, cx)
13778        }))
13779    }
13780
13781    fn resolve_inlay_hint(
13782        &self,
13783        hint: InlayHint,
13784        buffer_handle: Model<Buffer>,
13785        server_id: LanguageServerId,
13786        cx: &mut AppContext,
13787    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13788        Some(self.update(cx, |project, cx| {
13789            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13790        }))
13791    }
13792
13793    fn range_for_rename(
13794        &self,
13795        buffer: &Model<Buffer>,
13796        position: text::Anchor,
13797        cx: &mut AppContext,
13798    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13799        Some(self.update(cx, |project, cx| {
13800            project.prepare_rename(buffer.clone(), position, cx)
13801        }))
13802    }
13803
13804    fn perform_rename(
13805        &self,
13806        buffer: &Model<Buffer>,
13807        position: text::Anchor,
13808        new_name: String,
13809        cx: &mut AppContext,
13810    ) -> Option<Task<Result<ProjectTransaction>>> {
13811        Some(self.update(cx, |project, cx| {
13812            project.perform_rename(buffer.clone(), position, new_name, cx)
13813        }))
13814    }
13815}
13816
13817fn inlay_hint_settings(
13818    location: Anchor,
13819    snapshot: &MultiBufferSnapshot,
13820    cx: &mut ViewContext<'_, Editor>,
13821) -> InlayHintSettings {
13822    let file = snapshot.file_at(location);
13823    let language = snapshot.language_at(location).map(|l| l.name());
13824    language_settings(language, file, cx).inlay_hints
13825}
13826
13827fn consume_contiguous_rows(
13828    contiguous_row_selections: &mut Vec<Selection<Point>>,
13829    selection: &Selection<Point>,
13830    display_map: &DisplaySnapshot,
13831    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13832) -> (MultiBufferRow, MultiBufferRow) {
13833    contiguous_row_selections.push(selection.clone());
13834    let start_row = MultiBufferRow(selection.start.row);
13835    let mut end_row = ending_row(selection, display_map);
13836
13837    while let Some(next_selection) = selections.peek() {
13838        if next_selection.start.row <= end_row.0 {
13839            end_row = ending_row(next_selection, display_map);
13840            contiguous_row_selections.push(selections.next().unwrap().clone());
13841        } else {
13842            break;
13843        }
13844    }
13845    (start_row, end_row)
13846}
13847
13848fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13849    if next_selection.end.column > 0 || next_selection.is_empty() {
13850        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13851    } else {
13852        MultiBufferRow(next_selection.end.row)
13853    }
13854}
13855
13856impl EditorSnapshot {
13857    pub fn remote_selections_in_range<'a>(
13858        &'a self,
13859        range: &'a Range<Anchor>,
13860        collaboration_hub: &dyn CollaborationHub,
13861        cx: &'a AppContext,
13862    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13863        let participant_names = collaboration_hub.user_names(cx);
13864        let participant_indices = collaboration_hub.user_participant_indices(cx);
13865        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13866        let collaborators_by_replica_id = collaborators_by_peer_id
13867            .iter()
13868            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13869            .collect::<HashMap<_, _>>();
13870        self.buffer_snapshot
13871            .selections_in_range(range, false)
13872            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13873                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13874                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13875                let user_name = participant_names.get(&collaborator.user_id).cloned();
13876                Some(RemoteSelection {
13877                    replica_id,
13878                    selection,
13879                    cursor_shape,
13880                    line_mode,
13881                    participant_index,
13882                    peer_id: collaborator.peer_id,
13883                    user_name,
13884                })
13885            })
13886    }
13887
13888    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13889        self.display_snapshot.buffer_snapshot.language_at(position)
13890    }
13891
13892    pub fn is_focused(&self) -> bool {
13893        self.is_focused
13894    }
13895
13896    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13897        self.placeholder_text.as_ref()
13898    }
13899
13900    pub fn scroll_position(&self) -> gpui::Point<f32> {
13901        self.scroll_anchor.scroll_position(&self.display_snapshot)
13902    }
13903
13904    fn gutter_dimensions(
13905        &self,
13906        font_id: FontId,
13907        font_size: Pixels,
13908        em_width: Pixels,
13909        em_advance: Pixels,
13910        max_line_number_width: Pixels,
13911        cx: &AppContext,
13912    ) -> GutterDimensions {
13913        if !self.show_gutter {
13914            return GutterDimensions::default();
13915        }
13916        let descent = cx.text_system().descent(font_id, font_size);
13917
13918        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13919            matches!(
13920                ProjectSettings::get_global(cx).git.git_gutter,
13921                Some(GitGutterSetting::TrackedFiles)
13922            )
13923        });
13924        let gutter_settings = EditorSettings::get_global(cx).gutter;
13925        let show_line_numbers = self
13926            .show_line_numbers
13927            .unwrap_or(gutter_settings.line_numbers);
13928        let line_gutter_width = if show_line_numbers {
13929            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13930            let min_width_for_number_on_gutter = em_advance * 4.0;
13931            max_line_number_width.max(min_width_for_number_on_gutter)
13932        } else {
13933            0.0.into()
13934        };
13935
13936        let show_code_actions = self
13937            .show_code_actions
13938            .unwrap_or(gutter_settings.code_actions);
13939
13940        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13941
13942        let git_blame_entries_width =
13943            self.git_blame_gutter_max_author_length
13944                .map(|max_author_length| {
13945                    // Length of the author name, but also space for the commit hash,
13946                    // the spacing and the timestamp.
13947                    let max_char_count = max_author_length
13948                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13949                        + 7 // length of commit sha
13950                        + 14 // length of max relative timestamp ("60 minutes ago")
13951                        + 4; // gaps and margins
13952
13953                    em_advance * max_char_count
13954                });
13955
13956        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13957        left_padding += if show_code_actions || show_runnables {
13958            em_width * 3.0
13959        } else if show_git_gutter && show_line_numbers {
13960            em_width * 2.0
13961        } else if show_git_gutter || show_line_numbers {
13962            em_width
13963        } else {
13964            px(0.)
13965        };
13966
13967        let right_padding = if gutter_settings.folds && show_line_numbers {
13968            em_width * 4.0
13969        } else if gutter_settings.folds {
13970            em_width * 3.0
13971        } else if show_line_numbers {
13972            em_width
13973        } else {
13974            px(0.)
13975        };
13976
13977        GutterDimensions {
13978            left_padding,
13979            right_padding,
13980            width: line_gutter_width + left_padding + right_padding,
13981            margin: -descent,
13982            git_blame_entries_width,
13983        }
13984    }
13985
13986    pub fn render_fold_toggle(
13987        &self,
13988        buffer_row: MultiBufferRow,
13989        row_contains_cursor: bool,
13990        editor: View<Editor>,
13991        cx: &mut WindowContext,
13992    ) -> Option<AnyElement> {
13993        let folded = self.is_line_folded(buffer_row);
13994
13995        if let Some(crease) = self
13996            .crease_snapshot
13997            .query_row(buffer_row, &self.buffer_snapshot)
13998        {
13999            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14000                if folded {
14001                    editor.update(cx, |editor, cx| {
14002                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14003                    });
14004                } else {
14005                    editor.update(cx, |editor, cx| {
14006                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14007                    });
14008                }
14009            });
14010
14011            Some((crease.render_toggle)(
14012                buffer_row,
14013                folded,
14014                toggle_callback,
14015                cx,
14016            ))
14017        } else if folded
14018            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14019        {
14020            Some(
14021                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14022                    .selected(folded)
14023                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14024                        if folded {
14025                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14026                        } else {
14027                            this.fold_at(&FoldAt { buffer_row }, cx);
14028                        }
14029                    }))
14030                    .into_any_element(),
14031            )
14032        } else {
14033            None
14034        }
14035    }
14036
14037    pub fn render_crease_trailer(
14038        &self,
14039        buffer_row: MultiBufferRow,
14040        cx: &mut WindowContext,
14041    ) -> Option<AnyElement> {
14042        let folded = self.is_line_folded(buffer_row);
14043        let crease = self
14044            .crease_snapshot
14045            .query_row(buffer_row, &self.buffer_snapshot)?;
14046        Some((crease.render_trailer)(buffer_row, folded, cx))
14047    }
14048}
14049
14050impl Deref for EditorSnapshot {
14051    type Target = DisplaySnapshot;
14052
14053    fn deref(&self) -> &Self::Target {
14054        &self.display_snapshot
14055    }
14056}
14057
14058#[derive(Clone, Debug, PartialEq, Eq)]
14059pub enum EditorEvent {
14060    InputIgnored {
14061        text: Arc<str>,
14062    },
14063    InputHandled {
14064        utf16_range_to_replace: Option<Range<isize>>,
14065        text: Arc<str>,
14066    },
14067    ExcerptsAdded {
14068        buffer: Model<Buffer>,
14069        predecessor: ExcerptId,
14070        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14071    },
14072    ExcerptsRemoved {
14073        ids: Vec<ExcerptId>,
14074    },
14075    ExcerptsEdited {
14076        ids: Vec<ExcerptId>,
14077    },
14078    ExcerptsExpanded {
14079        ids: Vec<ExcerptId>,
14080    },
14081    BufferEdited,
14082    Edited {
14083        transaction_id: clock::Lamport,
14084    },
14085    Reparsed(BufferId),
14086    Focused,
14087    FocusedIn,
14088    Blurred,
14089    DirtyChanged,
14090    Saved,
14091    TitleChanged,
14092    DiffBaseChanged,
14093    SelectionsChanged {
14094        local: bool,
14095    },
14096    ScrollPositionChanged {
14097        local: bool,
14098        autoscroll: bool,
14099    },
14100    Closed,
14101    TransactionUndone {
14102        transaction_id: clock::Lamport,
14103    },
14104    TransactionBegun {
14105        transaction_id: clock::Lamport,
14106    },
14107    Reloaded,
14108    CursorShapeChanged,
14109}
14110
14111impl EventEmitter<EditorEvent> for Editor {}
14112
14113impl FocusableView for Editor {
14114    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14115        self.focus_handle.clone()
14116    }
14117}
14118
14119impl Render for Editor {
14120    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14121        let settings = ThemeSettings::get_global(cx);
14122
14123        let mut text_style = match self.mode {
14124            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14125                color: cx.theme().colors().editor_foreground,
14126                font_family: settings.ui_font.family.clone(),
14127                font_features: settings.ui_font.features.clone(),
14128                font_fallbacks: settings.ui_font.fallbacks.clone(),
14129                font_size: rems(0.875).into(),
14130                font_weight: settings.ui_font.weight,
14131                line_height: relative(settings.buffer_line_height.value()),
14132                ..Default::default()
14133            },
14134            EditorMode::Full => TextStyle {
14135                color: cx.theme().colors().editor_foreground,
14136                font_family: settings.buffer_font.family.clone(),
14137                font_features: settings.buffer_font.features.clone(),
14138                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14139                font_size: settings.buffer_font_size(cx).into(),
14140                font_weight: settings.buffer_font.weight,
14141                line_height: relative(settings.buffer_line_height.value()),
14142                ..Default::default()
14143            },
14144        };
14145        if let Some(text_style_refinement) = &self.text_style_refinement {
14146            text_style.refine(text_style_refinement)
14147        }
14148
14149        let background = match self.mode {
14150            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14151            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14152            EditorMode::Full => cx.theme().colors().editor_background,
14153        };
14154
14155        EditorElement::new(
14156            cx.view(),
14157            EditorStyle {
14158                background,
14159                local_player: cx.theme().players().local(),
14160                text: text_style,
14161                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14162                syntax: cx.theme().syntax().clone(),
14163                status: cx.theme().status().clone(),
14164                inlay_hints_style: make_inlay_hints_style(cx),
14165                suggestions_style: HighlightStyle {
14166                    color: Some(cx.theme().status().predictive),
14167                    ..HighlightStyle::default()
14168                },
14169                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14170            },
14171        )
14172    }
14173}
14174
14175impl ViewInputHandler for Editor {
14176    fn text_for_range(
14177        &mut self,
14178        range_utf16: Range<usize>,
14179        cx: &mut ViewContext<Self>,
14180    ) -> Option<String> {
14181        Some(
14182            self.buffer
14183                .read(cx)
14184                .read(cx)
14185                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14186                .collect(),
14187        )
14188    }
14189
14190    fn selected_text_range(
14191        &mut self,
14192        ignore_disabled_input: bool,
14193        cx: &mut ViewContext<Self>,
14194    ) -> Option<UTF16Selection> {
14195        // Prevent the IME menu from appearing when holding down an alphabetic key
14196        // while input is disabled.
14197        if !ignore_disabled_input && !self.input_enabled {
14198            return None;
14199        }
14200
14201        let selection = self.selections.newest::<OffsetUtf16>(cx);
14202        let range = selection.range();
14203
14204        Some(UTF16Selection {
14205            range: range.start.0..range.end.0,
14206            reversed: selection.reversed,
14207        })
14208    }
14209
14210    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14211        let snapshot = self.buffer.read(cx).read(cx);
14212        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14213        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14214    }
14215
14216    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14217        self.clear_highlights::<InputComposition>(cx);
14218        self.ime_transaction.take();
14219    }
14220
14221    fn replace_text_in_range(
14222        &mut self,
14223        range_utf16: Option<Range<usize>>,
14224        text: &str,
14225        cx: &mut ViewContext<Self>,
14226    ) {
14227        if !self.input_enabled {
14228            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14229            return;
14230        }
14231
14232        self.transact(cx, |this, cx| {
14233            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14234                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14235                Some(this.selection_replacement_ranges(range_utf16, cx))
14236            } else {
14237                this.marked_text_ranges(cx)
14238            };
14239
14240            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14241                let newest_selection_id = this.selections.newest_anchor().id;
14242                this.selections
14243                    .all::<OffsetUtf16>(cx)
14244                    .iter()
14245                    .zip(ranges_to_replace.iter())
14246                    .find_map(|(selection, range)| {
14247                        if selection.id == newest_selection_id {
14248                            Some(
14249                                (range.start.0 as isize - selection.head().0 as isize)
14250                                    ..(range.end.0 as isize - selection.head().0 as isize),
14251                            )
14252                        } else {
14253                            None
14254                        }
14255                    })
14256            });
14257
14258            cx.emit(EditorEvent::InputHandled {
14259                utf16_range_to_replace: range_to_replace,
14260                text: text.into(),
14261            });
14262
14263            if let Some(new_selected_ranges) = new_selected_ranges {
14264                this.change_selections(None, cx, |selections| {
14265                    selections.select_ranges(new_selected_ranges)
14266                });
14267                this.backspace(&Default::default(), cx);
14268            }
14269
14270            this.handle_input(text, cx);
14271        });
14272
14273        if let Some(transaction) = self.ime_transaction {
14274            self.buffer.update(cx, |buffer, cx| {
14275                buffer.group_until_transaction(transaction, cx);
14276            });
14277        }
14278
14279        self.unmark_text(cx);
14280    }
14281
14282    fn replace_and_mark_text_in_range(
14283        &mut self,
14284        range_utf16: Option<Range<usize>>,
14285        text: &str,
14286        new_selected_range_utf16: Option<Range<usize>>,
14287        cx: &mut ViewContext<Self>,
14288    ) {
14289        if !self.input_enabled {
14290            return;
14291        }
14292
14293        let transaction = self.transact(cx, |this, cx| {
14294            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14295                let snapshot = this.buffer.read(cx).read(cx);
14296                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14297                    for marked_range in &mut marked_ranges {
14298                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14299                        marked_range.start.0 += relative_range_utf16.start;
14300                        marked_range.start =
14301                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14302                        marked_range.end =
14303                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14304                    }
14305                }
14306                Some(marked_ranges)
14307            } else if let Some(range_utf16) = range_utf16 {
14308                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14309                Some(this.selection_replacement_ranges(range_utf16, cx))
14310            } else {
14311                None
14312            };
14313
14314            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14315                let newest_selection_id = this.selections.newest_anchor().id;
14316                this.selections
14317                    .all::<OffsetUtf16>(cx)
14318                    .iter()
14319                    .zip(ranges_to_replace.iter())
14320                    .find_map(|(selection, range)| {
14321                        if selection.id == newest_selection_id {
14322                            Some(
14323                                (range.start.0 as isize - selection.head().0 as isize)
14324                                    ..(range.end.0 as isize - selection.head().0 as isize),
14325                            )
14326                        } else {
14327                            None
14328                        }
14329                    })
14330            });
14331
14332            cx.emit(EditorEvent::InputHandled {
14333                utf16_range_to_replace: range_to_replace,
14334                text: text.into(),
14335            });
14336
14337            if let Some(ranges) = ranges_to_replace {
14338                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14339            }
14340
14341            let marked_ranges = {
14342                let snapshot = this.buffer.read(cx).read(cx);
14343                this.selections
14344                    .disjoint_anchors()
14345                    .iter()
14346                    .map(|selection| {
14347                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14348                    })
14349                    .collect::<Vec<_>>()
14350            };
14351
14352            if text.is_empty() {
14353                this.unmark_text(cx);
14354            } else {
14355                this.highlight_text::<InputComposition>(
14356                    marked_ranges.clone(),
14357                    HighlightStyle {
14358                        underline: Some(UnderlineStyle {
14359                            thickness: px(1.),
14360                            color: None,
14361                            wavy: false,
14362                        }),
14363                        ..Default::default()
14364                    },
14365                    cx,
14366                );
14367            }
14368
14369            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14370            let use_autoclose = this.use_autoclose;
14371            let use_auto_surround = this.use_auto_surround;
14372            this.set_use_autoclose(false);
14373            this.set_use_auto_surround(false);
14374            this.handle_input(text, cx);
14375            this.set_use_autoclose(use_autoclose);
14376            this.set_use_auto_surround(use_auto_surround);
14377
14378            if let Some(new_selected_range) = new_selected_range_utf16 {
14379                let snapshot = this.buffer.read(cx).read(cx);
14380                let new_selected_ranges = marked_ranges
14381                    .into_iter()
14382                    .map(|marked_range| {
14383                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14384                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14385                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14386                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14387                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14388                    })
14389                    .collect::<Vec<_>>();
14390
14391                drop(snapshot);
14392                this.change_selections(None, cx, |selections| {
14393                    selections.select_ranges(new_selected_ranges)
14394                });
14395            }
14396        });
14397
14398        self.ime_transaction = self.ime_transaction.or(transaction);
14399        if let Some(transaction) = self.ime_transaction {
14400            self.buffer.update(cx, |buffer, cx| {
14401                buffer.group_until_transaction(transaction, cx);
14402            });
14403        }
14404
14405        if self.text_highlights::<InputComposition>(cx).is_none() {
14406            self.ime_transaction.take();
14407        }
14408    }
14409
14410    fn bounds_for_range(
14411        &mut self,
14412        range_utf16: Range<usize>,
14413        element_bounds: gpui::Bounds<Pixels>,
14414        cx: &mut ViewContext<Self>,
14415    ) -> Option<gpui::Bounds<Pixels>> {
14416        let text_layout_details = self.text_layout_details(cx);
14417        let style = &text_layout_details.editor_style;
14418        let font_id = cx.text_system().resolve_font(&style.text.font());
14419        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14420        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14421
14422        let em_width = cx
14423            .text_system()
14424            .typographic_bounds(font_id, font_size, 'm')
14425            .unwrap()
14426            .size
14427            .width;
14428
14429        let snapshot = self.snapshot(cx);
14430        let scroll_position = snapshot.scroll_position();
14431        let scroll_left = scroll_position.x * em_width;
14432
14433        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14434        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14435            + self.gutter_dimensions.width;
14436        let y = line_height * (start.row().as_f32() - scroll_position.y);
14437
14438        Some(Bounds {
14439            origin: element_bounds.origin + point(x, y),
14440            size: size(em_width, line_height),
14441        })
14442    }
14443}
14444
14445trait SelectionExt {
14446    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14447    fn spanned_rows(
14448        &self,
14449        include_end_if_at_line_start: bool,
14450        map: &DisplaySnapshot,
14451    ) -> Range<MultiBufferRow>;
14452}
14453
14454impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14455    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14456        let start = self
14457            .start
14458            .to_point(&map.buffer_snapshot)
14459            .to_display_point(map);
14460        let end = self
14461            .end
14462            .to_point(&map.buffer_snapshot)
14463            .to_display_point(map);
14464        if self.reversed {
14465            end..start
14466        } else {
14467            start..end
14468        }
14469    }
14470
14471    fn spanned_rows(
14472        &self,
14473        include_end_if_at_line_start: bool,
14474        map: &DisplaySnapshot,
14475    ) -> Range<MultiBufferRow> {
14476        let start = self.start.to_point(&map.buffer_snapshot);
14477        let mut end = self.end.to_point(&map.buffer_snapshot);
14478        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14479            end.row -= 1;
14480        }
14481
14482        let buffer_start = map.prev_line_boundary(start).0;
14483        let buffer_end = map.next_line_boundary(end).0;
14484        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14485    }
14486}
14487
14488impl<T: InvalidationRegion> InvalidationStack<T> {
14489    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14490    where
14491        S: Clone + ToOffset,
14492    {
14493        while let Some(region) = self.last() {
14494            let all_selections_inside_invalidation_ranges =
14495                if selections.len() == region.ranges().len() {
14496                    selections
14497                        .iter()
14498                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14499                        .all(|(selection, invalidation_range)| {
14500                            let head = selection.head().to_offset(buffer);
14501                            invalidation_range.start <= head && invalidation_range.end >= head
14502                        })
14503                } else {
14504                    false
14505                };
14506
14507            if all_selections_inside_invalidation_ranges {
14508                break;
14509            } else {
14510                self.pop();
14511            }
14512        }
14513    }
14514}
14515
14516impl<T> Default for InvalidationStack<T> {
14517    fn default() -> Self {
14518        Self(Default::default())
14519    }
14520}
14521
14522impl<T> Deref for InvalidationStack<T> {
14523    type Target = Vec<T>;
14524
14525    fn deref(&self) -> &Self::Target {
14526        &self.0
14527    }
14528}
14529
14530impl<T> DerefMut for InvalidationStack<T> {
14531    fn deref_mut(&mut self) -> &mut Self::Target {
14532        &mut self.0
14533    }
14534}
14535
14536impl InvalidationRegion for SnippetState {
14537    fn ranges(&self) -> &[Range<Anchor>] {
14538        &self.ranges[self.active_index]
14539    }
14540}
14541
14542pub fn diagnostic_block_renderer(
14543    diagnostic: Diagnostic,
14544    max_message_rows: Option<u8>,
14545    allow_closing: bool,
14546    _is_valid: bool,
14547) -> RenderBlock {
14548    let (text_without_backticks, code_ranges) =
14549        highlight_diagnostic_message(&diagnostic, max_message_rows);
14550
14551    Box::new(move |cx: &mut BlockContext| {
14552        let group_id: SharedString = cx.block_id.to_string().into();
14553
14554        let mut text_style = cx.text_style().clone();
14555        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14556        let theme_settings = ThemeSettings::get_global(cx);
14557        text_style.font_family = theme_settings.buffer_font.family.clone();
14558        text_style.font_style = theme_settings.buffer_font.style;
14559        text_style.font_features = theme_settings.buffer_font.features.clone();
14560        text_style.font_weight = theme_settings.buffer_font.weight;
14561
14562        let multi_line_diagnostic = diagnostic.message.contains('\n');
14563
14564        let buttons = |diagnostic: &Diagnostic| {
14565            if multi_line_diagnostic {
14566                v_flex()
14567            } else {
14568                h_flex()
14569            }
14570            .when(allow_closing, |div| {
14571                div.children(diagnostic.is_primary.then(|| {
14572                    IconButton::new("close-block", IconName::XCircle)
14573                        .icon_color(Color::Muted)
14574                        .size(ButtonSize::Compact)
14575                        .style(ButtonStyle::Transparent)
14576                        .visible_on_hover(group_id.clone())
14577                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14578                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14579                }))
14580            })
14581            .child(
14582                IconButton::new("copy-block", IconName::Copy)
14583                    .icon_color(Color::Muted)
14584                    .size(ButtonSize::Compact)
14585                    .style(ButtonStyle::Transparent)
14586                    .visible_on_hover(group_id.clone())
14587                    .on_click({
14588                        let message = diagnostic.message.clone();
14589                        move |_click, cx| {
14590                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14591                        }
14592                    })
14593                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14594            )
14595        };
14596
14597        let icon_size = buttons(&diagnostic)
14598            .into_any_element()
14599            .layout_as_root(AvailableSpace::min_size(), cx);
14600
14601        h_flex()
14602            .id(cx.block_id)
14603            .group(group_id.clone())
14604            .relative()
14605            .size_full()
14606            .pl(cx.gutter_dimensions.width)
14607            .w(cx.max_width - cx.gutter_dimensions.full_width())
14608            .child(
14609                div()
14610                    .flex()
14611                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14612                    .flex_shrink(),
14613            )
14614            .child(buttons(&diagnostic))
14615            .child(div().flex().flex_shrink_0().child(
14616                StyledText::new(text_without_backticks.clone()).with_highlights(
14617                    &text_style,
14618                    code_ranges.iter().map(|range| {
14619                        (
14620                            range.clone(),
14621                            HighlightStyle {
14622                                font_weight: Some(FontWeight::BOLD),
14623                                ..Default::default()
14624                            },
14625                        )
14626                    }),
14627                ),
14628            ))
14629            .into_any_element()
14630    })
14631}
14632
14633pub fn highlight_diagnostic_message(
14634    diagnostic: &Diagnostic,
14635    mut max_message_rows: Option<u8>,
14636) -> (SharedString, Vec<Range<usize>>) {
14637    let mut text_without_backticks = String::new();
14638    let mut code_ranges = Vec::new();
14639
14640    if let Some(source) = &diagnostic.source {
14641        text_without_backticks.push_str(source);
14642        code_ranges.push(0..source.len());
14643        text_without_backticks.push_str(": ");
14644    }
14645
14646    let mut prev_offset = 0;
14647    let mut in_code_block = false;
14648    let has_row_limit = max_message_rows.is_some();
14649    let mut newline_indices = diagnostic
14650        .message
14651        .match_indices('\n')
14652        .filter(|_| has_row_limit)
14653        .map(|(ix, _)| ix)
14654        .fuse()
14655        .peekable();
14656
14657    for (quote_ix, _) in diagnostic
14658        .message
14659        .match_indices('`')
14660        .chain([(diagnostic.message.len(), "")])
14661    {
14662        let mut first_newline_ix = None;
14663        let mut last_newline_ix = None;
14664        while let Some(newline_ix) = newline_indices.peek() {
14665            if *newline_ix < quote_ix {
14666                if first_newline_ix.is_none() {
14667                    first_newline_ix = Some(*newline_ix);
14668                }
14669                last_newline_ix = Some(*newline_ix);
14670
14671                if let Some(rows_left) = &mut max_message_rows {
14672                    if *rows_left == 0 {
14673                        break;
14674                    } else {
14675                        *rows_left -= 1;
14676                    }
14677                }
14678                let _ = newline_indices.next();
14679            } else {
14680                break;
14681            }
14682        }
14683        let prev_len = text_without_backticks.len();
14684        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14685        text_without_backticks.push_str(new_text);
14686        if in_code_block {
14687            code_ranges.push(prev_len..text_without_backticks.len());
14688        }
14689        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14690        in_code_block = !in_code_block;
14691        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14692            text_without_backticks.push_str("...");
14693            break;
14694        }
14695    }
14696
14697    (text_without_backticks.into(), code_ranges)
14698}
14699
14700fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14701    match severity {
14702        DiagnosticSeverity::ERROR => colors.error,
14703        DiagnosticSeverity::WARNING => colors.warning,
14704        DiagnosticSeverity::INFORMATION => colors.info,
14705        DiagnosticSeverity::HINT => colors.info,
14706        _ => colors.ignored,
14707    }
14708}
14709
14710pub fn styled_runs_for_code_label<'a>(
14711    label: &'a CodeLabel,
14712    syntax_theme: &'a theme::SyntaxTheme,
14713) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14714    let fade_out = HighlightStyle {
14715        fade_out: Some(0.35),
14716        ..Default::default()
14717    };
14718
14719    let mut prev_end = label.filter_range.end;
14720    label
14721        .runs
14722        .iter()
14723        .enumerate()
14724        .flat_map(move |(ix, (range, highlight_id))| {
14725            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14726                style
14727            } else {
14728                return Default::default();
14729            };
14730            let mut muted_style = style;
14731            muted_style.highlight(fade_out);
14732
14733            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14734            if range.start >= label.filter_range.end {
14735                if range.start > prev_end {
14736                    runs.push((prev_end..range.start, fade_out));
14737                }
14738                runs.push((range.clone(), muted_style));
14739            } else if range.end <= label.filter_range.end {
14740                runs.push((range.clone(), style));
14741            } else {
14742                runs.push((range.start..label.filter_range.end, style));
14743                runs.push((label.filter_range.end..range.end, muted_style));
14744            }
14745            prev_end = cmp::max(prev_end, range.end);
14746
14747            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14748                runs.push((prev_end..label.text.len(), fade_out));
14749            }
14750
14751            runs
14752        })
14753}
14754
14755pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14756    let mut prev_index = 0;
14757    let mut prev_codepoint: Option<char> = None;
14758    text.char_indices()
14759        .chain([(text.len(), '\0')])
14760        .filter_map(move |(index, codepoint)| {
14761            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14762            let is_boundary = index == text.len()
14763                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14764                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14765            if is_boundary {
14766                let chunk = &text[prev_index..index];
14767                prev_index = index;
14768                Some(chunk)
14769            } else {
14770                None
14771            }
14772        })
14773}
14774
14775pub trait RangeToAnchorExt: Sized {
14776    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14777
14778    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14779        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14780        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14781    }
14782}
14783
14784impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14785    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14786        let start_offset = self.start.to_offset(snapshot);
14787        let end_offset = self.end.to_offset(snapshot);
14788        if start_offset == end_offset {
14789            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14790        } else {
14791            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14792        }
14793    }
14794}
14795
14796pub trait RowExt {
14797    fn as_f32(&self) -> f32;
14798
14799    fn next_row(&self) -> Self;
14800
14801    fn previous_row(&self) -> Self;
14802
14803    fn minus(&self, other: Self) -> u32;
14804}
14805
14806impl RowExt for DisplayRow {
14807    fn as_f32(&self) -> f32 {
14808        self.0 as f32
14809    }
14810
14811    fn next_row(&self) -> Self {
14812        Self(self.0 + 1)
14813    }
14814
14815    fn previous_row(&self) -> Self {
14816        Self(self.0.saturating_sub(1))
14817    }
14818
14819    fn minus(&self, other: Self) -> u32 {
14820        self.0 - other.0
14821    }
14822}
14823
14824impl RowExt for MultiBufferRow {
14825    fn as_f32(&self) -> f32 {
14826        self.0 as f32
14827    }
14828
14829    fn next_row(&self) -> Self {
14830        Self(self.0 + 1)
14831    }
14832
14833    fn previous_row(&self) -> Self {
14834        Self(self.0.saturating_sub(1))
14835    }
14836
14837    fn minus(&self, other: Self) -> u32 {
14838        self.0 - other.0
14839    }
14840}
14841
14842trait RowRangeExt {
14843    type Row;
14844
14845    fn len(&self) -> usize;
14846
14847    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14848}
14849
14850impl RowRangeExt for Range<MultiBufferRow> {
14851    type Row = MultiBufferRow;
14852
14853    fn len(&self) -> usize {
14854        (self.end.0 - self.start.0) as usize
14855    }
14856
14857    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14858        (self.start.0..self.end.0).map(MultiBufferRow)
14859    }
14860}
14861
14862impl RowRangeExt for Range<DisplayRow> {
14863    type Row = DisplayRow;
14864
14865    fn len(&self) -> usize {
14866        (self.end.0 - self.start.0) as usize
14867    }
14868
14869    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14870        (self.start.0..self.end.0).map(DisplayRow)
14871    }
14872}
14873
14874fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14875    if hunk.diff_base_byte_range.is_empty() {
14876        DiffHunkStatus::Added
14877    } else if hunk.row_range.is_empty() {
14878        DiffHunkStatus::Removed
14879    } else {
14880        DiffHunkStatus::Modified
14881    }
14882}
14883
14884/// If select range has more than one line, we
14885/// just point the cursor to range.start.
14886fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14887    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14888        range
14889    } else {
14890        range.start..range.start
14891    }
14892}