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::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion_provider::*;
   90pub use items::MAX_TAB_TITLE_LEN;
   91use itertools::Itertools;
   92use language::{
   93    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   94    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   95    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   96    Point, Selection, SelectionGoal, TransactionId,
   97};
   98use language::{
   99    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  100};
  101use linked_editing_ranges::refresh_linked_ranges;
  102pub use proposed_changes_editor::{
  103    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  104};
  105use similar::{ChangeTag, TextDiff};
  106use std::iter::Peekable;
  107use task::{ResolvedTask, TaskTemplate, TaskVariables};
  108
  109use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  110pub use lsp::CompletionContext;
  111use lsp::{
  112    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  113    LanguageServerId,
  114};
  115use mouse_context_menu::MouseContextMenu;
  116use movement::TextLayoutDetails;
  117pub use multi_buffer::{
  118    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  119    ToPoint,
  120};
  121use multi_buffer::{
  122    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  123};
  124use ordered_float::OrderedFloat;
  125use parking_lot::{Mutex, RwLock};
  126use project::{
  127    lsp_store::{FormatTarget, FormatTrigger},
  128    project_settings::{GitGutterSetting, ProjectSettings},
  129    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  130    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  131};
  132use rand::prelude::*;
  133use rpc::{proto::*, ErrorExt};
  134use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  135use selections_collection::{
  136    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  137};
  138use serde::{Deserialize, Serialize};
  139use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  140use smallvec::SmallVec;
  141use snippet::Snippet;
  142use std::{
  143    any::TypeId,
  144    borrow::Cow,
  145    cell::RefCell,
  146    cmp::{self, Ordering, Reverse},
  147    mem,
  148    num::NonZeroU32,
  149    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  150    path::{Path, PathBuf},
  151    rc::Rc,
  152    sync::Arc,
  153    time::{Duration, Instant},
  154};
  155pub use sum_tree::Bias;
  156use sum_tree::TreeMap;
  157use text::{BufferId, OffsetUtf16, Rope};
  158use theme::{
  159    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  160    ThemeColors, ThemeSettings,
  161};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    ListItem, Popover, PopoverMenuHandle, Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::find_url;
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188#[doc(hidden)]
  189pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  190
  191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  193
  194pub fn render_parsed_markdown(
  195    element_id: impl Into<ElementId>,
  196    parsed: &language::ParsedMarkdown,
  197    editor_style: &EditorStyle,
  198    workspace: Option<WeakView<Workspace>>,
  199    cx: &mut WindowContext,
  200) -> InteractiveText {
  201    let code_span_background_color = cx
  202        .theme()
  203        .colors()
  204        .editor_document_highlight_read_background;
  205
  206    let highlights = gpui::combine_highlights(
  207        parsed.highlights.iter().filter_map(|(range, highlight)| {
  208            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  209            Some((range.clone(), highlight))
  210        }),
  211        parsed
  212            .regions
  213            .iter()
  214            .zip(&parsed.region_ranges)
  215            .filter_map(|(region, range)| {
  216                if region.code {
  217                    Some((
  218                        range.clone(),
  219                        HighlightStyle {
  220                            background_color: Some(code_span_background_color),
  221                            ..Default::default()
  222                        },
  223                    ))
  224                } else {
  225                    None
  226                }
  227            }),
  228    );
  229
  230    let mut links = Vec::new();
  231    let mut link_ranges = Vec::new();
  232    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  233        if let Some(link) = region.link.clone() {
  234            links.push(link);
  235            link_ranges.push(range.clone());
  236        }
  237    }
  238
  239    InteractiveText::new(
  240        element_id,
  241        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  242    )
  243    .on_click(link_ranges, move |clicked_range_ix, cx| {
  244        match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace.open_abs_path(path.clone(), false, cx).detach();
  250                    });
  251                }
  252            }
  253        }
  254    })
  255}
  256
  257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  258pub(crate) enum InlayId {
  259    Suggestion(usize),
  260    Hint(usize),
  261}
  262
  263impl InlayId {
  264    fn id(&self) -> usize {
  265        match self {
  266            Self::Suggestion(id) => *id,
  267            Self::Hint(id) => *id,
  268        }
  269    }
  270}
  271
  272enum DiffRowHighlight {}
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Copy, Clone, PartialEq, Eq)]
  278pub enum Direction {
  279    Prev,
  280    Next,
  281}
  282
  283#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  284pub enum Navigated {
  285    Yes,
  286    No,
  287}
  288
  289impl Navigated {
  290    pub fn from_bool(yes: bool) -> Navigated {
  291        if yes {
  292            Navigated::Yes
  293        } else {
  294            Navigated::No
  295        }
  296    }
  297}
  298
  299pub fn init_settings(cx: &mut AppContext) {
  300    EditorSettings::register(cx);
  301}
  302
  303pub fn init(cx: &mut AppContext) {
  304    init_settings(cx);
  305
  306    workspace::register_project_item::<Editor>(cx);
  307    workspace::FollowableViewRegistry::register::<Editor>(cx);
  308    workspace::register_serializable_item::<Editor>(cx);
  309
  310    cx.observe_new_views(
  311        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  312            workspace.register_action(Editor::new_file);
  313            workspace.register_action(Editor::new_file_vertical);
  314            workspace.register_action(Editor::new_file_horizontal);
  315        },
  316    )
  317    .detach();
  318
  319    cx.on_action(move |_: &workspace::NewFile, cx| {
  320        let app_state = workspace::AppState::global(cx);
  321        if let Some(app_state) = app_state.upgrade() {
  322            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  323                Editor::new_file(workspace, &Default::default(), cx)
  324            })
  325            .detach();
  326        }
  327    });
  328    cx.on_action(move |_: &workspace::NewWindow, cx| {
  329        let app_state = workspace::AppState::global(cx);
  330        if let Some(app_state) = app_state.upgrade() {
  331            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  332                Editor::new_file(workspace, &Default::default(), cx)
  333            })
  334            .detach();
  335        }
  336    });
  337}
  338
  339pub struct SearchWithinRange;
  340
  341trait InvalidationRegion {
  342    fn ranges(&self) -> &[Range<Anchor>];
  343}
  344
  345#[derive(Clone, Debug, PartialEq)]
  346pub enum SelectPhase {
  347    Begin {
  348        position: DisplayPoint,
  349        add: bool,
  350        click_count: usize,
  351    },
  352    BeginColumnar {
  353        position: DisplayPoint,
  354        reset: bool,
  355        goal_column: u32,
  356    },
  357    Extend {
  358        position: DisplayPoint,
  359        click_count: usize,
  360    },
  361    Update {
  362        position: DisplayPoint,
  363        goal_column: u32,
  364        scroll_delta: gpui::Point<f32>,
  365    },
  366    End,
  367}
  368
  369#[derive(Clone, Debug)]
  370pub enum SelectMode {
  371    Character,
  372    Word(Range<Anchor>),
  373    Line(Range<Anchor>),
  374    All,
  375}
  376
  377#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  378pub enum EditorMode {
  379    SingleLine { auto_width: bool },
  380    AutoHeight { max_lines: usize },
  381    Full,
  382}
  383
  384#[derive(Copy, Clone, Debug)]
  385pub enum SoftWrap {
  386    /// Prefer not to wrap at all.
  387    ///
  388    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  389    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  390    GitDiff,
  391    /// Prefer a single line generally, unless an overly long line is encountered.
  392    None,
  393    /// Soft wrap lines that exceed the editor width.
  394    EditorWidth,
  395    /// Soft wrap lines at the preferred line length.
  396    Column(u32),
  397    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  398    Bounded(u32),
  399}
  400
  401#[derive(Clone)]
  402pub struct EditorStyle {
  403    pub background: Hsla,
  404    pub local_player: PlayerColor,
  405    pub text: TextStyle,
  406    pub scrollbar_width: Pixels,
  407    pub syntax: Arc<SyntaxTheme>,
  408    pub status: StatusColors,
  409    pub inlay_hints_style: HighlightStyle,
  410    pub suggestions_style: HighlightStyle,
  411    pub unnecessary_code_fade: f32,
  412}
  413
  414impl Default for EditorStyle {
  415    fn default() -> Self {
  416        Self {
  417            background: Hsla::default(),
  418            local_player: PlayerColor::default(),
  419            text: TextStyle::default(),
  420            scrollbar_width: Pixels::default(),
  421            syntax: Default::default(),
  422            // HACK: Status colors don't have a real default.
  423            // We should look into removing the status colors from the editor
  424            // style and retrieve them directly from the theme.
  425            status: StatusColors::dark(),
  426            inlay_hints_style: HighlightStyle::default(),
  427            suggestions_style: HighlightStyle::default(),
  428            unnecessary_code_fade: Default::default(),
  429        }
  430    }
  431}
  432
  433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  434    let show_background = language_settings::language_settings(None, None, cx)
  435        .inlay_hints
  436        .show_background;
  437
  438    HighlightStyle {
  439        color: Some(cx.theme().status().hint),
  440        background_color: show_background.then(|| cx.theme().status().hint_background),
  441        ..HighlightStyle::default()
  442    }
  443}
  444
  445type CompletionId = usize;
  446
  447#[derive(Clone, Debug)]
  448struct CompletionState {
  449    // render_inlay_ids represents the inlay hints that are inserted
  450    // for rendering the inline completions. They may be discontinuous
  451    // in the event that the completion provider returns some intersection
  452    // with the existing content.
  453    render_inlay_ids: Vec<InlayId>,
  454    // text is the resulting rope that is inserted when the user accepts a completion.
  455    text: Rope,
  456    // position is the position of the cursor when the completion was triggered.
  457    position: multi_buffer::Anchor,
  458    // delete_range is the range of text that this completion state covers.
  459    // if the completion is accepted, this range should be deleted.
  460    delete_range: Option<Range<multi_buffer::Anchor>>,
  461}
  462
  463#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  464struct EditorActionId(usize);
  465
  466impl EditorActionId {
  467    pub fn post_inc(&mut self) -> Self {
  468        let answer = self.0;
  469
  470        *self = Self(answer + 1);
  471
  472        Self(answer)
  473    }
  474}
  475
  476// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  477// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  478
  479type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  480type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  481
  482#[derive(Default)]
  483struct ScrollbarMarkerState {
  484    scrollbar_size: Size<Pixels>,
  485    dirty: bool,
  486    markers: Arc<[PaintQuad]>,
  487    pending_refresh: Option<Task<Result<()>>>,
  488}
  489
  490impl ScrollbarMarkerState {
  491    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  492        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  493    }
  494}
  495
  496#[derive(Clone, Debug)]
  497struct RunnableTasks {
  498    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  499    offset: MultiBufferOffset,
  500    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  501    column: u32,
  502    // Values of all named captures, including those starting with '_'
  503    extra_variables: HashMap<String, String>,
  504    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  505    context_range: Range<BufferOffset>,
  506}
  507
  508impl RunnableTasks {
  509    fn resolve<'a>(
  510        &'a self,
  511        cx: &'a task::TaskContext,
  512    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  513        self.templates.iter().filter_map(|(kind, template)| {
  514            template
  515                .resolve_task(&kind.to_id_base(), cx)
  516                .map(|task| (kind.clone(), task))
  517        })
  518    }
  519}
  520
  521#[derive(Clone)]
  522struct ResolvedTasks {
  523    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  524    position: Anchor,
  525}
  526#[derive(Copy, Clone, Debug)]
  527struct MultiBufferOffset(usize);
  528#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  529struct BufferOffset(usize);
  530
  531// Addons allow storing per-editor state in other crates (e.g. Vim)
  532pub trait Addon: 'static {
  533    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  534
  535    fn to_any(&self) -> &dyn std::any::Any;
  536}
  537
  538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  539///
  540/// See the [module level documentation](self) for more information.
  541pub struct Editor {
  542    focus_handle: FocusHandle,
  543    last_focused_descendant: Option<WeakFocusHandle>,
  544    /// The text buffer being edited
  545    buffer: Model<MultiBuffer>,
  546    /// Map of how text in the buffer should be displayed.
  547    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  548    pub display_map: Model<DisplayMap>,
  549    pub selections: SelectionsCollection,
  550    pub scroll_manager: ScrollManager,
  551    /// When inline assist editors are linked, they all render cursors because
  552    /// typing enters text into each of them, even the ones that aren't focused.
  553    pub(crate) show_cursor_when_unfocused: bool,
  554    columnar_selection_tail: Option<Anchor>,
  555    add_selections_state: Option<AddSelectionsState>,
  556    select_next_state: Option<SelectNextState>,
  557    select_prev_state: Option<SelectNextState>,
  558    selection_history: SelectionHistory,
  559    autoclose_regions: Vec<AutocloseRegion>,
  560    snippet_stack: InvalidationStack<SnippetState>,
  561    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  562    ime_transaction: Option<TransactionId>,
  563    active_diagnostics: Option<ActiveDiagnosticGroup>,
  564    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  565
  566    project: Option<Model<Project>>,
  567    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  568    completion_provider: Option<Box<dyn CompletionProvider>>,
  569    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  570    blink_manager: Model<BlinkManager>,
  571    show_cursor_names: bool,
  572    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  573    pub show_local_selections: bool,
  574    mode: EditorMode,
  575    show_breadcrumbs: bool,
  576    show_gutter: bool,
  577    show_line_numbers: Option<bool>,
  578    use_relative_line_numbers: Option<bool>,
  579    show_git_diff_gutter: Option<bool>,
  580    show_code_actions: Option<bool>,
  581    show_runnables: Option<bool>,
  582    show_wrap_guides: Option<bool>,
  583    show_indent_guides: Option<bool>,
  584    placeholder_text: Option<Arc<str>>,
  585    highlight_order: usize,
  586    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  587    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  588    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  589    scrollbar_marker_state: ScrollbarMarkerState,
  590    active_indent_guides_state: ActiveIndentGuidesState,
  591    nav_history: Option<ItemNavHistory>,
  592    context_menu: RwLock<Option<ContextMenu>>,
  593    mouse_context_menu: Option<MouseContextMenu>,
  594    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  595    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  596    signature_help_state: SignatureHelpState,
  597    auto_signature_help: Option<bool>,
  598    find_all_references_task_sources: Vec<Anchor>,
  599    next_completion_id: CompletionId,
  600    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  601    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  602    code_actions_task: Option<Task<Result<()>>>,
  603    document_highlights_task: Option<Task<()>>,
  604    linked_editing_range_task: Option<Task<Option<()>>>,
  605    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  606    pending_rename: Option<RenameState>,
  607    searchable: bool,
  608    cursor_shape: CursorShape,
  609    current_line_highlight: Option<CurrentLineHighlight>,
  610    collapse_matches: bool,
  611    autoindent_mode: Option<AutoindentMode>,
  612    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  613    input_enabled: bool,
  614    use_modal_editing: bool,
  615    read_only: bool,
  616    leader_peer_id: Option<PeerId>,
  617    remote_id: Option<ViewId>,
  618    hover_state: HoverState,
  619    gutter_hovered: bool,
  620    hovered_link_state: Option<HoveredLinkState>,
  621    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  622    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  623    active_inline_completion: Option<CompletionState>,
  624    // enable_inline_completions is a switch that Vim can use to disable
  625    // inline completions based on its mode.
  626    enable_inline_completions: bool,
  627    show_inline_completions_override: Option<bool>,
  628    inlay_hint_cache: InlayHintCache,
  629    expanded_hunks: ExpandedHunks,
  630    next_inlay_id: usize,
  631    _subscriptions: Vec<Subscription>,
  632    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  633    gutter_dimensions: GutterDimensions,
  634    style: Option<EditorStyle>,
  635    text_style_refinement: Option<TextStyleRefinement>,
  636    next_editor_action_id: EditorActionId,
  637    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  638    use_autoclose: bool,
  639    use_auto_surround: bool,
  640    auto_replace_emoji_shortcode: bool,
  641    show_git_blame_gutter: bool,
  642    show_git_blame_inline: bool,
  643    show_git_blame_inline_delay_task: Option<Task<()>>,
  644    git_blame_inline_enabled: bool,
  645    serialize_dirty_buffers: bool,
  646    show_selection_menu: Option<bool>,
  647    blame: Option<Model<GitBlame>>,
  648    blame_subscription: Option<Subscription>,
  649    custom_context_menu: Option<
  650        Box<
  651            dyn 'static
  652                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  653        >,
  654    >,
  655    last_bounds: Option<Bounds<Pixels>>,
  656    expect_bounds_change: Option<Bounds<Pixels>>,
  657    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  658    tasks_update_task: Option<Task<()>>,
  659    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  660    breadcrumb_header: Option<String>,
  661    focused_block: Option<FocusedBlock>,
  662    next_scroll_position: NextScrollCursorCenterTopBottom,
  663    addons: HashMap<TypeId, Box<dyn Addon>>,
  664    _scroll_cursor_center_top_bottom_task: Task<()>,
  665}
  666
  667#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  668enum NextScrollCursorCenterTopBottom {
  669    #[default]
  670    Center,
  671    Top,
  672    Bottom,
  673}
  674
  675impl NextScrollCursorCenterTopBottom {
  676    fn next(&self) -> Self {
  677        match self {
  678            Self::Center => Self::Top,
  679            Self::Top => Self::Bottom,
  680            Self::Bottom => Self::Center,
  681        }
  682    }
  683}
  684
  685#[derive(Clone)]
  686pub struct EditorSnapshot {
  687    pub mode: EditorMode,
  688    show_gutter: bool,
  689    show_line_numbers: Option<bool>,
  690    show_git_diff_gutter: Option<bool>,
  691    show_code_actions: Option<bool>,
  692    show_runnables: Option<bool>,
  693    git_blame_gutter_max_author_length: Option<usize>,
  694    pub display_snapshot: DisplaySnapshot,
  695    pub placeholder_text: Option<Arc<str>>,
  696    is_focused: bool,
  697    scroll_anchor: ScrollAnchor,
  698    ongoing_scroll: OngoingScroll,
  699    current_line_highlight: CurrentLineHighlight,
  700    gutter_hovered: bool,
  701}
  702
  703const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  704
  705#[derive(Default, Debug, Clone, Copy)]
  706pub struct GutterDimensions {
  707    pub left_padding: Pixels,
  708    pub right_padding: Pixels,
  709    pub width: Pixels,
  710    pub margin: Pixels,
  711    pub git_blame_entries_width: Option<Pixels>,
  712}
  713
  714impl GutterDimensions {
  715    /// The full width of the space taken up by the gutter.
  716    pub fn full_width(&self) -> Pixels {
  717        self.margin + self.width
  718    }
  719
  720    /// The width of the space reserved for the fold indicators,
  721    /// use alongside 'justify_end' and `gutter_width` to
  722    /// right align content with the line numbers
  723    pub fn fold_area_width(&self) -> Pixels {
  724        self.margin + self.right_padding
  725    }
  726}
  727
  728#[derive(Debug)]
  729pub struct RemoteSelection {
  730    pub replica_id: ReplicaId,
  731    pub selection: Selection<Anchor>,
  732    pub cursor_shape: CursorShape,
  733    pub peer_id: PeerId,
  734    pub line_mode: bool,
  735    pub participant_index: Option<ParticipantIndex>,
  736    pub user_name: Option<SharedString>,
  737}
  738
  739#[derive(Clone, Debug)]
  740struct SelectionHistoryEntry {
  741    selections: Arc<[Selection<Anchor>]>,
  742    select_next_state: Option<SelectNextState>,
  743    select_prev_state: Option<SelectNextState>,
  744    add_selections_state: Option<AddSelectionsState>,
  745}
  746
  747enum SelectionHistoryMode {
  748    Normal,
  749    Undoing,
  750    Redoing,
  751}
  752
  753#[derive(Clone, PartialEq, Eq, Hash)]
  754struct HoveredCursor {
  755    replica_id: u16,
  756    selection_id: usize,
  757}
  758
  759impl Default for SelectionHistoryMode {
  760    fn default() -> Self {
  761        Self::Normal
  762    }
  763}
  764
  765#[derive(Default)]
  766struct SelectionHistory {
  767    #[allow(clippy::type_complexity)]
  768    selections_by_transaction:
  769        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  770    mode: SelectionHistoryMode,
  771    undo_stack: VecDeque<SelectionHistoryEntry>,
  772    redo_stack: VecDeque<SelectionHistoryEntry>,
  773}
  774
  775impl SelectionHistory {
  776    fn insert_transaction(
  777        &mut self,
  778        transaction_id: TransactionId,
  779        selections: Arc<[Selection<Anchor>]>,
  780    ) {
  781        self.selections_by_transaction
  782            .insert(transaction_id, (selections, None));
  783    }
  784
  785    #[allow(clippy::type_complexity)]
  786    fn transaction(
  787        &self,
  788        transaction_id: TransactionId,
  789    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  790        self.selections_by_transaction.get(&transaction_id)
  791    }
  792
  793    #[allow(clippy::type_complexity)]
  794    fn transaction_mut(
  795        &mut self,
  796        transaction_id: TransactionId,
  797    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  798        self.selections_by_transaction.get_mut(&transaction_id)
  799    }
  800
  801    fn push(&mut self, entry: SelectionHistoryEntry) {
  802        if !entry.selections.is_empty() {
  803            match self.mode {
  804                SelectionHistoryMode::Normal => {
  805                    self.push_undo(entry);
  806                    self.redo_stack.clear();
  807                }
  808                SelectionHistoryMode::Undoing => self.push_redo(entry),
  809                SelectionHistoryMode::Redoing => self.push_undo(entry),
  810            }
  811        }
  812    }
  813
  814    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  815        if self
  816            .undo_stack
  817            .back()
  818            .map_or(true, |e| e.selections != entry.selections)
  819        {
  820            self.undo_stack.push_back(entry);
  821            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  822                self.undo_stack.pop_front();
  823            }
  824        }
  825    }
  826
  827    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  828        if self
  829            .redo_stack
  830            .back()
  831            .map_or(true, |e| e.selections != entry.selections)
  832        {
  833            self.redo_stack.push_back(entry);
  834            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  835                self.redo_stack.pop_front();
  836            }
  837        }
  838    }
  839}
  840
  841struct RowHighlight {
  842    index: usize,
  843    range: Range<Anchor>,
  844    color: Hsla,
  845    should_autoscroll: bool,
  846}
  847
  848#[derive(Clone, Debug)]
  849struct AddSelectionsState {
  850    above: bool,
  851    stack: Vec<usize>,
  852}
  853
  854#[derive(Clone)]
  855struct SelectNextState {
  856    query: AhoCorasick,
  857    wordwise: bool,
  858    done: bool,
  859}
  860
  861impl std::fmt::Debug for SelectNextState {
  862    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  863        f.debug_struct(std::any::type_name::<Self>())
  864            .field("wordwise", &self.wordwise)
  865            .field("done", &self.done)
  866            .finish()
  867    }
  868}
  869
  870#[derive(Debug)]
  871struct AutocloseRegion {
  872    selection_id: usize,
  873    range: Range<Anchor>,
  874    pair: BracketPair,
  875}
  876
  877#[derive(Debug)]
  878struct SnippetState {
  879    ranges: Vec<Vec<Range<Anchor>>>,
  880    active_index: usize,
  881}
  882
  883#[doc(hidden)]
  884pub struct RenameState {
  885    pub range: Range<Anchor>,
  886    pub old_name: Arc<str>,
  887    pub editor: View<Editor>,
  888    block_id: CustomBlockId,
  889}
  890
  891struct InvalidationStack<T>(Vec<T>);
  892
  893struct RegisteredInlineCompletionProvider {
  894    provider: Arc<dyn InlineCompletionProviderHandle>,
  895    _subscription: Subscription,
  896}
  897
  898enum ContextMenu {
  899    Completions(CompletionsMenu),
  900    CodeActions(CodeActionsMenu),
  901}
  902
  903impl ContextMenu {
  904    fn select_first(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_prev(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_next(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn select_last(
  953        &mut self,
  954        provider: Option<&dyn CompletionProvider>,
  955        cx: &mut ViewContext<Editor>,
  956    ) -> bool {
  957        if self.visible() {
  958            match self {
  959                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  960                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  961            }
  962            true
  963        } else {
  964            false
  965        }
  966    }
  967
  968    fn visible(&self) -> bool {
  969        match self {
  970            ContextMenu::Completions(menu) => menu.visible(),
  971            ContextMenu::CodeActions(menu) => menu.visible(),
  972        }
  973    }
  974
  975    fn render(
  976        &self,
  977        cursor_position: DisplayPoint,
  978        style: &EditorStyle,
  979        max_height: Pixels,
  980        workspace: Option<WeakView<Workspace>>,
  981        cx: &mut ViewContext<Editor>,
  982    ) -> (ContextMenuOrigin, AnyElement) {
  983        match self {
  984            ContextMenu::Completions(menu) => (
  985                ContextMenuOrigin::EditorPoint(cursor_position),
  986                menu.render(style, max_height, workspace, cx),
  987            ),
  988            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  989        }
  990    }
  991}
  992
  993enum ContextMenuOrigin {
  994    EditorPoint(DisplayPoint),
  995    GutterIndicator(DisplayRow),
  996}
  997
  998#[derive(Clone)]
  999struct CompletionsMenu {
 1000    id: CompletionId,
 1001    sort_completions: bool,
 1002    initial_position: Anchor,
 1003    buffer: Model<Buffer>,
 1004    completions: Arc<RwLock<Box<[Completion]>>>,
 1005    match_candidates: Arc<[StringMatchCandidate]>,
 1006    matches: Arc<[StringMatch]>,
 1007    selected_item: usize,
 1008    scroll_handle: UniformListScrollHandle,
 1009    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
 1010}
 1011
 1012impl CompletionsMenu {
 1013    fn select_first(
 1014        &mut self,
 1015        provider: Option<&dyn CompletionProvider>,
 1016        cx: &mut ViewContext<Editor>,
 1017    ) {
 1018        self.selected_item = 0;
 1019        self.scroll_handle
 1020            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 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
 1036            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1037        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1038        cx.notify();
 1039    }
 1040
 1041    fn select_next(
 1042        &mut self,
 1043        provider: Option<&dyn CompletionProvider>,
 1044        cx: &mut ViewContext<Editor>,
 1045    ) {
 1046        if self.selected_item + 1 < self.matches.len() {
 1047            self.selected_item += 1;
 1048        } else {
 1049            self.selected_item = 0;
 1050        }
 1051        self.scroll_handle
 1052            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1053        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1054        cx.notify();
 1055    }
 1056
 1057    fn select_last(
 1058        &mut self,
 1059        provider: Option<&dyn CompletionProvider>,
 1060        cx: &mut ViewContext<Editor>,
 1061    ) {
 1062        self.selected_item = self.matches.len() - 1;
 1063        self.scroll_handle
 1064            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1065        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1066        cx.notify();
 1067    }
 1068
 1069    fn pre_resolve_completion_documentation(
 1070        buffer: Model<Buffer>,
 1071        completions: Arc<RwLock<Box<[Completion]>>>,
 1072        matches: Arc<[StringMatch]>,
 1073        editor: &Editor,
 1074        cx: &mut ViewContext<Editor>,
 1075    ) -> Task<()> {
 1076        let settings = EditorSettings::get_global(cx);
 1077        if !settings.show_completion_documentation {
 1078            return Task::ready(());
 1079        }
 1080
 1081        let Some(provider) = editor.completion_provider.as_ref() else {
 1082            return Task::ready(());
 1083        };
 1084
 1085        let resolve_task = provider.resolve_completions(
 1086            buffer,
 1087            matches.iter().map(|m| m.candidate_id).collect(),
 1088            completions.clone(),
 1089            cx,
 1090        );
 1091
 1092        cx.spawn(move |this, mut cx| async move {
 1093            if let Some(true) = resolve_task.await.log_err() {
 1094                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1095            }
 1096        })
 1097    }
 1098
 1099    fn attempt_resolve_selected_completion_documentation(
 1100        &mut self,
 1101        provider: Option<&dyn CompletionProvider>,
 1102        cx: &mut ViewContext<Editor>,
 1103    ) {
 1104        let settings = EditorSettings::get_global(cx);
 1105        if !settings.show_completion_documentation {
 1106            return;
 1107        }
 1108
 1109        let completion_index = self.matches[self.selected_item].candidate_id;
 1110        let Some(provider) = provider else {
 1111            return;
 1112        };
 1113
 1114        let resolve_task = provider.resolve_completions(
 1115            self.buffer.clone(),
 1116            vec![completion_index],
 1117            self.completions.clone(),
 1118            cx,
 1119        );
 1120
 1121        let delay_ms =
 1122            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1123        let delay = Duration::from_millis(delay_ms);
 1124
 1125        self.selected_completion_documentation_resolve_debounce
 1126            .lock()
 1127            .fire_new(delay, cx, |_, cx| {
 1128                cx.spawn(move |this, mut cx| async move {
 1129                    if let Some(true) = resolve_task.await.log_err() {
 1130                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1131                    }
 1132                })
 1133            });
 1134    }
 1135
 1136    fn visible(&self) -> bool {
 1137        !self.matches.is_empty()
 1138    }
 1139
 1140    fn render(
 1141        &self,
 1142        style: &EditorStyle,
 1143        max_height: Pixels,
 1144        workspace: Option<WeakView<Workspace>>,
 1145        cx: &mut ViewContext<Editor>,
 1146    ) -> AnyElement {
 1147        let settings = EditorSettings::get_global(cx);
 1148        let show_completion_documentation = settings.show_completion_documentation;
 1149
 1150        let widest_completion_ix = self
 1151            .matches
 1152            .iter()
 1153            .enumerate()
 1154            .max_by_key(|(_, mat)| {
 1155                let completions = self.completions.read();
 1156                let completion = &completions[mat.candidate_id];
 1157                let documentation = &completion.documentation;
 1158
 1159                let mut len = completion.label.text.chars().count();
 1160                if let Some(Documentation::SingleLine(text)) = documentation {
 1161                    if show_completion_documentation {
 1162                        len += text.chars().count();
 1163                    }
 1164                }
 1165
 1166                len
 1167            })
 1168            .map(|(ix, _)| ix);
 1169
 1170        let completions = self.completions.clone();
 1171        let matches = self.matches.clone();
 1172        let selected_item = self.selected_item;
 1173        let style = style.clone();
 1174
 1175        let multiline_docs = if show_completion_documentation {
 1176            let mat = &self.matches[selected_item];
 1177            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1178                Some(Documentation::MultiLinePlainText(text)) => {
 1179                    Some(div().child(SharedString::from(text.clone())))
 1180                }
 1181                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1182                    Some(div().child(render_parsed_markdown(
 1183                        "completions_markdown",
 1184                        parsed,
 1185                        &style,
 1186                        workspace,
 1187                        cx,
 1188                    )))
 1189                }
 1190                _ => None,
 1191            };
 1192            multiline_docs.map(|div| {
 1193                div.id("multiline_docs")
 1194                    .max_h(max_height)
 1195                    .flex_1()
 1196                    .px_1p5()
 1197                    .py_1()
 1198                    .min_w(px(260.))
 1199                    .max_w(px(640.))
 1200                    .w(px(500.))
 1201                    .overflow_y_scroll()
 1202                    .occlude()
 1203            })
 1204        } else {
 1205            None
 1206        };
 1207
 1208        let list = uniform_list(
 1209            cx.view().clone(),
 1210            "completions",
 1211            matches.len(),
 1212            move |_editor, range, cx| {
 1213                let start_ix = range.start;
 1214                let completions_guard = completions.read();
 1215
 1216                matches[range]
 1217                    .iter()
 1218                    .enumerate()
 1219                    .map(|(ix, mat)| {
 1220                        let item_ix = start_ix + ix;
 1221                        let candidate_id = mat.candidate_id;
 1222                        let completion = &completions_guard[candidate_id];
 1223
 1224                        let documentation = if show_completion_documentation {
 1225                            &completion.documentation
 1226                        } else {
 1227                            &None
 1228                        };
 1229
 1230                        let highlights = gpui::combine_highlights(
 1231                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1232                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1233                                |(range, mut highlight)| {
 1234                                    // Ignore font weight for syntax highlighting, as we'll use it
 1235                                    // for fuzzy matches.
 1236                                    highlight.font_weight = None;
 1237
 1238                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1239                                        highlight.strikethrough = Some(StrikethroughStyle {
 1240                                            thickness: 1.0.into(),
 1241                                            ..Default::default()
 1242                                        });
 1243                                        highlight.color = Some(cx.theme().colors().text_muted);
 1244                                    }
 1245
 1246                                    (range, highlight)
 1247                                },
 1248                            ),
 1249                        );
 1250                        let completion_label = StyledText::new(completion.label.text.clone())
 1251                            .with_highlights(&style.text, highlights);
 1252                        let documentation_label =
 1253                            if let Some(Documentation::SingleLine(text)) = documentation {
 1254                                if text.trim().is_empty() {
 1255                                    None
 1256                                } else {
 1257                                    Some(
 1258                                        Label::new(text.clone())
 1259                                            .ml_4()
 1260                                            .size(LabelSize::Small)
 1261                                            .color(Color::Muted),
 1262                                    )
 1263                                }
 1264                            } else {
 1265                                None
 1266                            };
 1267
 1268                        let color_swatch = completion
 1269                            .color()
 1270                            .map(|color| div().size_4().bg(color).rounded_sm());
 1271
 1272                        div().min_w(px(220.)).max_w(px(540.)).child(
 1273                            ListItem::new(mat.candidate_id)
 1274                                .inset(true)
 1275                                .selected(item_ix == selected_item)
 1276                                .on_click(cx.listener(move |editor, _event, cx| {
 1277                                    cx.stop_propagation();
 1278                                    if let Some(task) = editor.confirm_completion(
 1279                                        &ConfirmCompletion {
 1280                                            item_ix: Some(item_ix),
 1281                                        },
 1282                                        cx,
 1283                                    ) {
 1284                                        task.detach_and_log_err(cx)
 1285                                    }
 1286                                }))
 1287                                .start_slot::<Div>(color_swatch)
 1288                                .child(h_flex().overflow_hidden().child(completion_label))
 1289                                .end_slot::<Label>(documentation_label),
 1290                        )
 1291                    })
 1292                    .collect()
 1293            },
 1294        )
 1295        .occlude()
 1296        .max_h(max_height)
 1297        .track_scroll(self.scroll_handle.clone())
 1298        .with_width_from_item(widest_completion_ix)
 1299        .with_sizing_behavior(ListSizingBehavior::Infer);
 1300
 1301        Popover::new()
 1302            .child(list)
 1303            .when_some(multiline_docs, |popover, multiline_docs| {
 1304                popover.aside(multiline_docs)
 1305            })
 1306            .into_any_element()
 1307    }
 1308
 1309    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1310        let mut matches = if let Some(query) = query {
 1311            fuzzy::match_strings(
 1312                &self.match_candidates,
 1313                query,
 1314                query.chars().any(|c| c.is_uppercase()),
 1315                100,
 1316                &Default::default(),
 1317                executor,
 1318            )
 1319            .await
 1320        } else {
 1321            self.match_candidates
 1322                .iter()
 1323                .enumerate()
 1324                .map(|(candidate_id, candidate)| StringMatch {
 1325                    candidate_id,
 1326                    score: Default::default(),
 1327                    positions: Default::default(),
 1328                    string: candidate.string.clone(),
 1329                })
 1330                .collect()
 1331        };
 1332
 1333        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1334        if let Some(query) = query {
 1335            if let Some(query_start) = query.chars().next() {
 1336                matches.retain(|string_match| {
 1337                    split_words(&string_match.string).any(|word| {
 1338                        // Check that the first codepoint of the word as lowercase matches the first
 1339                        // codepoint of the query as lowercase
 1340                        word.chars()
 1341                            .flat_map(|codepoint| codepoint.to_lowercase())
 1342                            .zip(query_start.to_lowercase())
 1343                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1344                    })
 1345                });
 1346            }
 1347        }
 1348
 1349        let completions = self.completions.read();
 1350        if self.sort_completions {
 1351            matches.sort_unstable_by_key(|mat| {
 1352                // We do want to strike a balance here between what the language server tells us
 1353                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1354                // `Creat` and there is a local variable called `CreateComponent`).
 1355                // So what we do is: we bucket all matches into two buckets
 1356                // - Strong matches
 1357                // - Weak matches
 1358                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1359                // and the Weak matches are the rest.
 1360                //
 1361                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1362                // matches, we prefer language-server sort_text first.
 1363                //
 1364                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1365                // Rest of the matches(weak) can be sorted as language-server expects.
 1366
 1367                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1368                enum MatchScore<'a> {
 1369                    Strong {
 1370                        score: Reverse<OrderedFloat<f64>>,
 1371                        sort_text: Option<&'a str>,
 1372                        sort_key: (usize, &'a str),
 1373                    },
 1374                    Weak {
 1375                        sort_text: Option<&'a str>,
 1376                        score: Reverse<OrderedFloat<f64>>,
 1377                        sort_key: (usize, &'a str),
 1378                    },
 1379                }
 1380
 1381                let completion = &completions[mat.candidate_id];
 1382                let sort_key = completion.sort_key();
 1383                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1384                let score = Reverse(OrderedFloat(mat.score));
 1385
 1386                if mat.score >= 0.2 {
 1387                    MatchScore::Strong {
 1388                        score,
 1389                        sort_text,
 1390                        sort_key,
 1391                    }
 1392                } else {
 1393                    MatchScore::Weak {
 1394                        sort_text,
 1395                        score,
 1396                        sort_key,
 1397                    }
 1398                }
 1399            });
 1400        }
 1401
 1402        for mat in &mut matches {
 1403            let completion = &completions[mat.candidate_id];
 1404            mat.string.clone_from(&completion.label.text);
 1405            for position in &mut mat.positions {
 1406                *position += completion.label.filter_range.start;
 1407            }
 1408        }
 1409        drop(completions);
 1410
 1411        self.matches = matches.into();
 1412        self.selected_item = 0;
 1413    }
 1414}
 1415
 1416struct AvailableCodeAction {
 1417    excerpt_id: ExcerptId,
 1418    action: CodeAction,
 1419    provider: Arc<dyn CodeActionProvider>,
 1420}
 1421
 1422#[derive(Clone)]
 1423struct CodeActionContents {
 1424    tasks: Option<Arc<ResolvedTasks>>,
 1425    actions: Option<Arc<[AvailableCodeAction]>>,
 1426}
 1427
 1428impl CodeActionContents {
 1429    fn len(&self) -> usize {
 1430        match (&self.tasks, &self.actions) {
 1431            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1432            (Some(tasks), None) => tasks.templates.len(),
 1433            (None, Some(actions)) => actions.len(),
 1434            (None, None) => 0,
 1435        }
 1436    }
 1437
 1438    fn is_empty(&self) -> bool {
 1439        match (&self.tasks, &self.actions) {
 1440            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1441            (Some(tasks), None) => tasks.templates.is_empty(),
 1442            (None, Some(actions)) => actions.is_empty(),
 1443            (None, None) => true,
 1444        }
 1445    }
 1446
 1447    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1448        self.tasks
 1449            .iter()
 1450            .flat_map(|tasks| {
 1451                tasks
 1452                    .templates
 1453                    .iter()
 1454                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1455            })
 1456            .chain(self.actions.iter().flat_map(|actions| {
 1457                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1458                    excerpt_id: available.excerpt_id,
 1459                    action: available.action.clone(),
 1460                    provider: available.provider.clone(),
 1461                })
 1462            }))
 1463    }
 1464    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1465        match (&self.tasks, &self.actions) {
 1466            (Some(tasks), Some(actions)) => {
 1467                if index < tasks.templates.len() {
 1468                    tasks
 1469                        .templates
 1470                        .get(index)
 1471                        .cloned()
 1472                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1473                } else {
 1474                    actions.get(index - tasks.templates.len()).map(|available| {
 1475                        CodeActionsItem::CodeAction {
 1476                            excerpt_id: available.excerpt_id,
 1477                            action: available.action.clone(),
 1478                            provider: available.provider.clone(),
 1479                        }
 1480                    })
 1481                }
 1482            }
 1483            (Some(tasks), None) => tasks
 1484                .templates
 1485                .get(index)
 1486                .cloned()
 1487                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1488            (None, Some(actions)) => {
 1489                actions
 1490                    .get(index)
 1491                    .map(|available| CodeActionsItem::CodeAction {
 1492                        excerpt_id: available.excerpt_id,
 1493                        action: available.action.clone(),
 1494                        provider: available.provider.clone(),
 1495                    })
 1496            }
 1497            (None, None) => None,
 1498        }
 1499    }
 1500}
 1501
 1502#[allow(clippy::large_enum_variant)]
 1503#[derive(Clone)]
 1504enum CodeActionsItem {
 1505    Task(TaskSourceKind, ResolvedTask),
 1506    CodeAction {
 1507        excerpt_id: ExcerptId,
 1508        action: CodeAction,
 1509        provider: Arc<dyn CodeActionProvider>,
 1510    },
 1511}
 1512
 1513impl CodeActionsItem {
 1514    fn as_task(&self) -> Option<&ResolvedTask> {
 1515        let Self::Task(_, task) = self else {
 1516            return None;
 1517        };
 1518        Some(task)
 1519    }
 1520    fn as_code_action(&self) -> Option<&CodeAction> {
 1521        let Self::CodeAction { action, .. } = self else {
 1522            return None;
 1523        };
 1524        Some(action)
 1525    }
 1526    fn label(&self) -> String {
 1527        match self {
 1528            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1529            Self::Task(_, task) => task.resolved_label.clone(),
 1530        }
 1531    }
 1532}
 1533
 1534struct CodeActionsMenu {
 1535    actions: CodeActionContents,
 1536    buffer: Model<Buffer>,
 1537    selected_item: usize,
 1538    scroll_handle: UniformListScrollHandle,
 1539    deployed_from_indicator: Option<DisplayRow>,
 1540}
 1541
 1542impl CodeActionsMenu {
 1543    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1544        self.selected_item = 0;
 1545        self.scroll_handle
 1546            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1547        cx.notify()
 1548    }
 1549
 1550    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1551        if self.selected_item > 0 {
 1552            self.selected_item -= 1;
 1553        } else {
 1554            self.selected_item = self.actions.len() - 1;
 1555        }
 1556        self.scroll_handle
 1557            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1558        cx.notify();
 1559    }
 1560
 1561    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1562        if self.selected_item + 1 < self.actions.len() {
 1563            self.selected_item += 1;
 1564        } else {
 1565            self.selected_item = 0;
 1566        }
 1567        self.scroll_handle
 1568            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1569        cx.notify();
 1570    }
 1571
 1572    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1573        self.selected_item = self.actions.len() - 1;
 1574        self.scroll_handle
 1575            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1576        cx.notify()
 1577    }
 1578
 1579    fn visible(&self) -> bool {
 1580        !self.actions.is_empty()
 1581    }
 1582
 1583    fn render(
 1584        &self,
 1585        cursor_position: DisplayPoint,
 1586        _style: &EditorStyle,
 1587        max_height: Pixels,
 1588        cx: &mut ViewContext<Editor>,
 1589    ) -> (ContextMenuOrigin, AnyElement) {
 1590        let actions = self.actions.clone();
 1591        let selected_item = self.selected_item;
 1592        let element = uniform_list(
 1593            cx.view().clone(),
 1594            "code_actions_menu",
 1595            self.actions.len(),
 1596            move |_this, range, cx| {
 1597                actions
 1598                    .iter()
 1599                    .skip(range.start)
 1600                    .take(range.end - range.start)
 1601                    .enumerate()
 1602                    .map(|(ix, action)| {
 1603                        let item_ix = range.start + ix;
 1604                        let selected = selected_item == item_ix;
 1605                        let colors = cx.theme().colors();
 1606                        div()
 1607                            .px_1()
 1608                            .rounded_md()
 1609                            .text_color(colors.text)
 1610                            .when(selected, |style| {
 1611                                style
 1612                                    .bg(colors.element_active)
 1613                                    .text_color(colors.text_accent)
 1614                            })
 1615                            .hover(|style| {
 1616                                style
 1617                                    .bg(colors.element_hover)
 1618                                    .text_color(colors.text_accent)
 1619                            })
 1620                            .whitespace_nowrap()
 1621                            .when_some(action.as_code_action(), |this, action| {
 1622                                this.on_mouse_down(
 1623                                    MouseButton::Left,
 1624                                    cx.listener(move |editor, _, cx| {
 1625                                        cx.stop_propagation();
 1626                                        if let Some(task) = editor.confirm_code_action(
 1627                                            &ConfirmCodeAction {
 1628                                                item_ix: Some(item_ix),
 1629                                            },
 1630                                            cx,
 1631                                        ) {
 1632                                            task.detach_and_log_err(cx)
 1633                                        }
 1634                                    }),
 1635                                )
 1636                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1637                                .child(SharedString::from(action.lsp_action.title.clone()))
 1638                            })
 1639                            .when_some(action.as_task(), |this, task| {
 1640                                this.on_mouse_down(
 1641                                    MouseButton::Left,
 1642                                    cx.listener(move |editor, _, cx| {
 1643                                        cx.stop_propagation();
 1644                                        if let Some(task) = editor.confirm_code_action(
 1645                                            &ConfirmCodeAction {
 1646                                                item_ix: Some(item_ix),
 1647                                            },
 1648                                            cx,
 1649                                        ) {
 1650                                            task.detach_and_log_err(cx)
 1651                                        }
 1652                                    }),
 1653                                )
 1654                                .child(SharedString::from(task.resolved_label.clone()))
 1655                            })
 1656                    })
 1657                    .collect()
 1658            },
 1659        )
 1660        .elevation_1(cx)
 1661        .p_1()
 1662        .max_h(max_height)
 1663        .occlude()
 1664        .track_scroll(self.scroll_handle.clone())
 1665        .with_width_from_item(
 1666            self.actions
 1667                .iter()
 1668                .enumerate()
 1669                .max_by_key(|(_, action)| match action {
 1670                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1671                    CodeActionsItem::CodeAction { action, .. } => {
 1672                        action.lsp_action.title.chars().count()
 1673                    }
 1674                })
 1675                .map(|(ix, _)| ix),
 1676        )
 1677        .with_sizing_behavior(ListSizingBehavior::Infer)
 1678        .into_any_element();
 1679
 1680        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1681            ContextMenuOrigin::GutterIndicator(row)
 1682        } else {
 1683            ContextMenuOrigin::EditorPoint(cursor_position)
 1684        };
 1685
 1686        (cursor_position, element)
 1687    }
 1688}
 1689
 1690#[derive(Debug)]
 1691struct ActiveDiagnosticGroup {
 1692    primary_range: Range<Anchor>,
 1693    primary_message: String,
 1694    group_id: usize,
 1695    blocks: HashMap<CustomBlockId, Diagnostic>,
 1696    is_valid: bool,
 1697}
 1698
 1699#[derive(Serialize, Deserialize, Clone, Debug)]
 1700pub struct ClipboardSelection {
 1701    pub len: usize,
 1702    pub is_entire_line: bool,
 1703    pub first_line_indent: u32,
 1704}
 1705
 1706#[derive(Debug)]
 1707pub(crate) struct NavigationData {
 1708    cursor_anchor: Anchor,
 1709    cursor_position: Point,
 1710    scroll_anchor: ScrollAnchor,
 1711    scroll_top_row: u32,
 1712}
 1713
 1714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1715pub enum GotoDefinitionKind {
 1716    Symbol,
 1717    Declaration,
 1718    Type,
 1719    Implementation,
 1720}
 1721
 1722#[derive(Debug, Clone)]
 1723enum InlayHintRefreshReason {
 1724    Toggle(bool),
 1725    SettingsChange(InlayHintSettings),
 1726    NewLinesShown,
 1727    BufferEdited(HashSet<Arc<Language>>),
 1728    RefreshRequested,
 1729    ExcerptsRemoved(Vec<ExcerptId>),
 1730}
 1731
 1732impl InlayHintRefreshReason {
 1733    fn description(&self) -> &'static str {
 1734        match self {
 1735            Self::Toggle(_) => "toggle",
 1736            Self::SettingsChange(_) => "settings change",
 1737            Self::NewLinesShown => "new lines shown",
 1738            Self::BufferEdited(_) => "buffer edited",
 1739            Self::RefreshRequested => "refresh requested",
 1740            Self::ExcerptsRemoved(_) => "excerpts removed",
 1741        }
 1742    }
 1743}
 1744
 1745pub(crate) struct FocusedBlock {
 1746    id: BlockId,
 1747    focus_handle: WeakFocusHandle,
 1748}
 1749
 1750impl Editor {
 1751    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1752        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1753        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1754        Self::new(
 1755            EditorMode::SingleLine { auto_width: false },
 1756            buffer,
 1757            None,
 1758            false,
 1759            cx,
 1760        )
 1761    }
 1762
 1763    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1764        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1765        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1766        Self::new(EditorMode::Full, buffer, None, false, cx)
 1767    }
 1768
 1769    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1770        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1771        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1772        Self::new(
 1773            EditorMode::SingleLine { auto_width: true },
 1774            buffer,
 1775            None,
 1776            false,
 1777            cx,
 1778        )
 1779    }
 1780
 1781    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1782        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1783        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1784        Self::new(
 1785            EditorMode::AutoHeight { max_lines },
 1786            buffer,
 1787            None,
 1788            false,
 1789            cx,
 1790        )
 1791    }
 1792
 1793    pub fn for_buffer(
 1794        buffer: Model<Buffer>,
 1795        project: Option<Model<Project>>,
 1796        cx: &mut ViewContext<Self>,
 1797    ) -> Self {
 1798        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1799        Self::new(EditorMode::Full, buffer, project, false, cx)
 1800    }
 1801
 1802    pub fn for_multibuffer(
 1803        buffer: Model<MultiBuffer>,
 1804        project: Option<Model<Project>>,
 1805        show_excerpt_controls: bool,
 1806        cx: &mut ViewContext<Self>,
 1807    ) -> Self {
 1808        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1809    }
 1810
 1811    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1812        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1813        let mut clone = Self::new(
 1814            self.mode,
 1815            self.buffer.clone(),
 1816            self.project.clone(),
 1817            show_excerpt_controls,
 1818            cx,
 1819        );
 1820        self.display_map.update(cx, |display_map, cx| {
 1821            let snapshot = display_map.snapshot(cx);
 1822            clone.display_map.update(cx, |display_map, cx| {
 1823                display_map.set_state(&snapshot, cx);
 1824            });
 1825        });
 1826        clone.selections.clone_state(&self.selections);
 1827        clone.scroll_manager.clone_state(&self.scroll_manager);
 1828        clone.searchable = self.searchable;
 1829        clone
 1830    }
 1831
 1832    pub fn new(
 1833        mode: EditorMode,
 1834        buffer: Model<MultiBuffer>,
 1835        project: Option<Model<Project>>,
 1836        show_excerpt_controls: bool,
 1837        cx: &mut ViewContext<Self>,
 1838    ) -> Self {
 1839        let style = cx.text_style();
 1840        let font_size = style.font_size.to_pixels(cx.rem_size());
 1841        let editor = cx.view().downgrade();
 1842        let fold_placeholder = FoldPlaceholder {
 1843            constrain_width: true,
 1844            render: Arc::new(move |fold_id, fold_range, cx| {
 1845                let editor = editor.clone();
 1846                div()
 1847                    .id(fold_id)
 1848                    .bg(cx.theme().colors().ghost_element_background)
 1849                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1850                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1851                    .rounded_sm()
 1852                    .size_full()
 1853                    .cursor_pointer()
 1854                    .child("")
 1855                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1856                    .on_click(move |_, cx| {
 1857                        editor
 1858                            .update(cx, |editor, cx| {
 1859                                editor.unfold_ranges(
 1860                                    &[fold_range.start..fold_range.end],
 1861                                    true,
 1862                                    false,
 1863                                    cx,
 1864                                );
 1865                                cx.stop_propagation();
 1866                            })
 1867                            .ok();
 1868                    })
 1869                    .into_any()
 1870            }),
 1871            merge_adjacent: true,
 1872            ..Default::default()
 1873        };
 1874        let display_map = cx.new_model(|cx| {
 1875            DisplayMap::new(
 1876                buffer.clone(),
 1877                style.font(),
 1878                font_size,
 1879                None,
 1880                show_excerpt_controls,
 1881                FILE_HEADER_HEIGHT,
 1882                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1883                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1884                fold_placeholder,
 1885                cx,
 1886            )
 1887        });
 1888
 1889        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1890
 1891        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1892
 1893        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1894            .then(|| language_settings::SoftWrap::None);
 1895
 1896        let mut project_subscriptions = Vec::new();
 1897        if mode == EditorMode::Full {
 1898            if let Some(project) = project.as_ref() {
 1899                if buffer.read(cx).is_singleton() {
 1900                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1901                        cx.emit(EditorEvent::TitleChanged);
 1902                    }));
 1903                }
 1904                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1905                    if let project::Event::RefreshInlayHints = event {
 1906                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1907                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1908                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1909                            let focus_handle = editor.focus_handle(cx);
 1910                            if focus_handle.is_focused(cx) {
 1911                                let snapshot = buffer.read(cx).snapshot();
 1912                                for (range, snippet) in snippet_edits {
 1913                                    let editor_range =
 1914                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1915                                    editor
 1916                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1917                                        .ok();
 1918                                }
 1919                            }
 1920                        }
 1921                    }
 1922                }));
 1923                if let Some(task_inventory) = project
 1924                    .read(cx)
 1925                    .task_store()
 1926                    .read(cx)
 1927                    .task_inventory()
 1928                    .cloned()
 1929                {
 1930                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1931                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1932                    }));
 1933                }
 1934            }
 1935        }
 1936
 1937        let inlay_hint_settings = inlay_hint_settings(
 1938            selections.newest_anchor().head(),
 1939            &buffer.read(cx).snapshot(cx),
 1940            cx,
 1941        );
 1942        let focus_handle = cx.focus_handle();
 1943        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1944        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1945            .detach();
 1946        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1947            .detach();
 1948        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1949
 1950        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1951            Some(false)
 1952        } else {
 1953            None
 1954        };
 1955
 1956        let mut code_action_providers = Vec::new();
 1957        if let Some(project) = project.clone() {
 1958            code_action_providers.push(Arc::new(project) as Arc<_>);
 1959        }
 1960
 1961        let mut this = Self {
 1962            focus_handle,
 1963            show_cursor_when_unfocused: false,
 1964            last_focused_descendant: None,
 1965            buffer: buffer.clone(),
 1966            display_map: display_map.clone(),
 1967            selections,
 1968            scroll_manager: ScrollManager::new(cx),
 1969            columnar_selection_tail: None,
 1970            add_selections_state: None,
 1971            select_next_state: None,
 1972            select_prev_state: None,
 1973            selection_history: Default::default(),
 1974            autoclose_regions: Default::default(),
 1975            snippet_stack: Default::default(),
 1976            select_larger_syntax_node_stack: Vec::new(),
 1977            ime_transaction: Default::default(),
 1978            active_diagnostics: None,
 1979            soft_wrap_mode_override,
 1980            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1981            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1982            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1983            project,
 1984            blink_manager: blink_manager.clone(),
 1985            show_local_selections: true,
 1986            mode,
 1987            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1988            show_gutter: mode == EditorMode::Full,
 1989            show_line_numbers: None,
 1990            use_relative_line_numbers: None,
 1991            show_git_diff_gutter: None,
 1992            show_code_actions: None,
 1993            show_runnables: None,
 1994            show_wrap_guides: None,
 1995            show_indent_guides,
 1996            placeholder_text: None,
 1997            highlight_order: 0,
 1998            highlighted_rows: HashMap::default(),
 1999            background_highlights: Default::default(),
 2000            gutter_highlights: TreeMap::default(),
 2001            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2002            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2003            nav_history: None,
 2004            context_menu: RwLock::new(None),
 2005            mouse_context_menu: None,
 2006            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2007            completion_tasks: Default::default(),
 2008            signature_help_state: SignatureHelpState::default(),
 2009            auto_signature_help: None,
 2010            find_all_references_task_sources: Vec::new(),
 2011            next_completion_id: 0,
 2012            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2013            next_inlay_id: 0,
 2014            code_action_providers,
 2015            available_code_actions: Default::default(),
 2016            code_actions_task: Default::default(),
 2017            document_highlights_task: Default::default(),
 2018            linked_editing_range_task: Default::default(),
 2019            pending_rename: Default::default(),
 2020            searchable: true,
 2021            cursor_shape: EditorSettings::get_global(cx)
 2022                .cursor_shape
 2023                .unwrap_or_default(),
 2024            current_line_highlight: None,
 2025            autoindent_mode: Some(AutoindentMode::EachLine),
 2026            collapse_matches: false,
 2027            workspace: None,
 2028            input_enabled: true,
 2029            use_modal_editing: mode == EditorMode::Full,
 2030            read_only: false,
 2031            use_autoclose: true,
 2032            use_auto_surround: true,
 2033            auto_replace_emoji_shortcode: false,
 2034            leader_peer_id: None,
 2035            remote_id: None,
 2036            hover_state: Default::default(),
 2037            hovered_link_state: Default::default(),
 2038            inline_completion_provider: None,
 2039            active_inline_completion: None,
 2040            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2041            expanded_hunks: ExpandedHunks::default(),
 2042            gutter_hovered: false,
 2043            pixel_position_of_newest_cursor: None,
 2044            last_bounds: None,
 2045            expect_bounds_change: None,
 2046            gutter_dimensions: GutterDimensions::default(),
 2047            style: None,
 2048            show_cursor_names: false,
 2049            hovered_cursors: Default::default(),
 2050            next_editor_action_id: EditorActionId::default(),
 2051            editor_actions: Rc::default(),
 2052            show_inline_completions_override: None,
 2053            enable_inline_completions: true,
 2054            custom_context_menu: None,
 2055            show_git_blame_gutter: false,
 2056            show_git_blame_inline: false,
 2057            show_selection_menu: None,
 2058            show_git_blame_inline_delay_task: None,
 2059            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2060            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2061                .session
 2062                .restore_unsaved_buffers,
 2063            blame: None,
 2064            blame_subscription: None,
 2065            tasks: Default::default(),
 2066            _subscriptions: vec![
 2067                cx.observe(&buffer, Self::on_buffer_changed),
 2068                cx.subscribe(&buffer, Self::on_buffer_event),
 2069                cx.observe(&display_map, Self::on_display_map_changed),
 2070                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2071                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2072                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2073                cx.observe_window_activation(|editor, cx| {
 2074                    let active = cx.is_window_active();
 2075                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2076                        if active {
 2077                            blink_manager.enable(cx);
 2078                        } else {
 2079                            blink_manager.disable(cx);
 2080                        }
 2081                    });
 2082                }),
 2083            ],
 2084            tasks_update_task: None,
 2085            linked_edit_ranges: Default::default(),
 2086            previous_search_ranges: None,
 2087            breadcrumb_header: None,
 2088            focused_block: None,
 2089            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2090            addons: HashMap::default(),
 2091            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2092            text_style_refinement: None,
 2093        };
 2094        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2095        this._subscriptions.extend(project_subscriptions);
 2096
 2097        this.end_selection(cx);
 2098        this.scroll_manager.show_scrollbar(cx);
 2099
 2100        if mode == EditorMode::Full {
 2101            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2102            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2103
 2104            if this.git_blame_inline_enabled {
 2105                this.git_blame_inline_enabled = true;
 2106                this.start_git_blame_inline(false, cx);
 2107            }
 2108        }
 2109
 2110        this.report_editor_event("open", None, cx);
 2111        this
 2112    }
 2113
 2114    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2115        self.mouse_context_menu
 2116            .as_ref()
 2117            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2118    }
 2119
 2120    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2121        let mut key_context = KeyContext::new_with_defaults();
 2122        key_context.add("Editor");
 2123        let mode = match self.mode {
 2124            EditorMode::SingleLine { .. } => "single_line",
 2125            EditorMode::AutoHeight { .. } => "auto_height",
 2126            EditorMode::Full => "full",
 2127        };
 2128
 2129        if EditorSettings::jupyter_enabled(cx) {
 2130            key_context.add("jupyter");
 2131        }
 2132
 2133        key_context.set("mode", mode);
 2134        if self.pending_rename.is_some() {
 2135            key_context.add("renaming");
 2136        }
 2137        if self.context_menu_visible() {
 2138            match self.context_menu.read().as_ref() {
 2139                Some(ContextMenu::Completions(_)) => {
 2140                    key_context.add("menu");
 2141                    key_context.add("showing_completions")
 2142                }
 2143                Some(ContextMenu::CodeActions(_)) => {
 2144                    key_context.add("menu");
 2145                    key_context.add("showing_code_actions")
 2146                }
 2147                None => {}
 2148            }
 2149        }
 2150
 2151        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2152        if !self.focus_handle(cx).contains_focused(cx)
 2153            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2154        {
 2155            for addon in self.addons.values() {
 2156                addon.extend_key_context(&mut key_context, cx)
 2157            }
 2158        }
 2159
 2160        if let Some(extension) = self
 2161            .buffer
 2162            .read(cx)
 2163            .as_singleton()
 2164            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2165        {
 2166            key_context.set("extension", extension.to_string());
 2167        }
 2168
 2169        if self.has_active_inline_completion(cx) {
 2170            key_context.add("copilot_suggestion");
 2171            key_context.add("inline_completion");
 2172        }
 2173
 2174        key_context
 2175    }
 2176
 2177    pub fn new_file(
 2178        workspace: &mut Workspace,
 2179        _: &workspace::NewFile,
 2180        cx: &mut ViewContext<Workspace>,
 2181    ) {
 2182        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2183            "Failed to create buffer",
 2184            cx,
 2185            |e, _| match e.error_code() {
 2186                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2187                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2188                e.error_tag("required").unwrap_or("the latest version")
 2189            )),
 2190                _ => None,
 2191            },
 2192        );
 2193    }
 2194
 2195    pub fn new_in_workspace(
 2196        workspace: &mut Workspace,
 2197        cx: &mut ViewContext<Workspace>,
 2198    ) -> Task<Result<View<Editor>>> {
 2199        let project = workspace.project().clone();
 2200        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2201
 2202        cx.spawn(|workspace, mut cx| async move {
 2203            let buffer = create.await?;
 2204            workspace.update(&mut cx, |workspace, cx| {
 2205                let editor =
 2206                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2207                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2208                editor
 2209            })
 2210        })
 2211    }
 2212
 2213    fn new_file_vertical(
 2214        workspace: &mut Workspace,
 2215        _: &workspace::NewFileSplitVertical,
 2216        cx: &mut ViewContext<Workspace>,
 2217    ) {
 2218        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2219    }
 2220
 2221    fn new_file_horizontal(
 2222        workspace: &mut Workspace,
 2223        _: &workspace::NewFileSplitHorizontal,
 2224        cx: &mut ViewContext<Workspace>,
 2225    ) {
 2226        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2227    }
 2228
 2229    fn new_file_in_direction(
 2230        workspace: &mut Workspace,
 2231        direction: SplitDirection,
 2232        cx: &mut ViewContext<Workspace>,
 2233    ) {
 2234        let project = workspace.project().clone();
 2235        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2236
 2237        cx.spawn(|workspace, mut cx| async move {
 2238            let buffer = create.await?;
 2239            workspace.update(&mut cx, move |workspace, cx| {
 2240                workspace.split_item(
 2241                    direction,
 2242                    Box::new(
 2243                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2244                    ),
 2245                    cx,
 2246                )
 2247            })?;
 2248            anyhow::Ok(())
 2249        })
 2250        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2251            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2252                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2253                e.error_tag("required").unwrap_or("the latest version")
 2254            )),
 2255            _ => None,
 2256        });
 2257    }
 2258
 2259    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2260        self.leader_peer_id
 2261    }
 2262
 2263    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2264        &self.buffer
 2265    }
 2266
 2267    pub fn workspace(&self) -> Option<View<Workspace>> {
 2268        self.workspace.as_ref()?.0.upgrade()
 2269    }
 2270
 2271    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2272        self.buffer().read(cx).title(cx)
 2273    }
 2274
 2275    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2276        let git_blame_gutter_max_author_length = self
 2277            .render_git_blame_gutter(cx)
 2278            .then(|| {
 2279                if let Some(blame) = self.blame.as_ref() {
 2280                    let max_author_length =
 2281                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2282                    Some(max_author_length)
 2283                } else {
 2284                    None
 2285                }
 2286            })
 2287            .flatten();
 2288
 2289        EditorSnapshot {
 2290            mode: self.mode,
 2291            show_gutter: self.show_gutter,
 2292            show_line_numbers: self.show_line_numbers,
 2293            show_git_diff_gutter: self.show_git_diff_gutter,
 2294            show_code_actions: self.show_code_actions,
 2295            show_runnables: self.show_runnables,
 2296            git_blame_gutter_max_author_length,
 2297            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2298            scroll_anchor: self.scroll_manager.anchor(),
 2299            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2300            placeholder_text: self.placeholder_text.clone(),
 2301            is_focused: self.focus_handle.is_focused(cx),
 2302            current_line_highlight: self
 2303                .current_line_highlight
 2304                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2305            gutter_hovered: self.gutter_hovered,
 2306        }
 2307    }
 2308
 2309    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2310        self.buffer.read(cx).language_at(point, cx)
 2311    }
 2312
 2313    pub fn file_at<T: ToOffset>(
 2314        &self,
 2315        point: T,
 2316        cx: &AppContext,
 2317    ) -> Option<Arc<dyn language::File>> {
 2318        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2319    }
 2320
 2321    pub fn active_excerpt(
 2322        &self,
 2323        cx: &AppContext,
 2324    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2325        self.buffer
 2326            .read(cx)
 2327            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2328    }
 2329
 2330    pub fn mode(&self) -> EditorMode {
 2331        self.mode
 2332    }
 2333
 2334    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2335        self.collaboration_hub.as_deref()
 2336    }
 2337
 2338    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2339        self.collaboration_hub = Some(hub);
 2340    }
 2341
 2342    pub fn set_custom_context_menu(
 2343        &mut self,
 2344        f: impl 'static
 2345            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2346    ) {
 2347        self.custom_context_menu = Some(Box::new(f))
 2348    }
 2349
 2350    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2351        self.completion_provider = provider;
 2352    }
 2353
 2354    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2355        self.semantics_provider.clone()
 2356    }
 2357
 2358    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2359        self.semantics_provider = provider;
 2360    }
 2361
 2362    pub fn set_inline_completion_provider<T>(
 2363        &mut self,
 2364        provider: Option<Model<T>>,
 2365        cx: &mut ViewContext<Self>,
 2366    ) where
 2367        T: InlineCompletionProvider,
 2368    {
 2369        self.inline_completion_provider =
 2370            provider.map(|provider| RegisteredInlineCompletionProvider {
 2371                _subscription: cx.observe(&provider, |this, _, cx| {
 2372                    if this.focus_handle.is_focused(cx) {
 2373                        this.update_visible_inline_completion(cx);
 2374                    }
 2375                }),
 2376                provider: Arc::new(provider),
 2377            });
 2378        self.refresh_inline_completion(false, false, cx);
 2379    }
 2380
 2381    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2382        self.placeholder_text.as_deref()
 2383    }
 2384
 2385    pub fn set_placeholder_text(
 2386        &mut self,
 2387        placeholder_text: impl Into<Arc<str>>,
 2388        cx: &mut ViewContext<Self>,
 2389    ) {
 2390        let placeholder_text = Some(placeholder_text.into());
 2391        if self.placeholder_text != placeholder_text {
 2392            self.placeholder_text = placeholder_text;
 2393            cx.notify();
 2394        }
 2395    }
 2396
 2397    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2398        self.cursor_shape = cursor_shape;
 2399
 2400        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2401        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2402
 2403        cx.notify();
 2404    }
 2405
 2406    pub fn set_current_line_highlight(
 2407        &mut self,
 2408        current_line_highlight: Option<CurrentLineHighlight>,
 2409    ) {
 2410        self.current_line_highlight = current_line_highlight;
 2411    }
 2412
 2413    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2414        self.collapse_matches = collapse_matches;
 2415    }
 2416
 2417    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2418        if self.collapse_matches {
 2419            return range.start..range.start;
 2420        }
 2421        range.clone()
 2422    }
 2423
 2424    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2425        if self.display_map.read(cx).clip_at_line_ends != clip {
 2426            self.display_map
 2427                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2428        }
 2429    }
 2430
 2431    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2432        self.input_enabled = input_enabled;
 2433    }
 2434
 2435    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2436        self.enable_inline_completions = enabled;
 2437    }
 2438
 2439    pub fn set_autoindent(&mut self, autoindent: bool) {
 2440        if autoindent {
 2441            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2442        } else {
 2443            self.autoindent_mode = None;
 2444        }
 2445    }
 2446
 2447    pub fn read_only(&self, cx: &AppContext) -> bool {
 2448        self.read_only || self.buffer.read(cx).read_only()
 2449    }
 2450
 2451    pub fn set_read_only(&mut self, read_only: bool) {
 2452        self.read_only = read_only;
 2453    }
 2454
 2455    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2456        self.use_autoclose = autoclose;
 2457    }
 2458
 2459    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2460        self.use_auto_surround = auto_surround;
 2461    }
 2462
 2463    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2464        self.auto_replace_emoji_shortcode = auto_replace;
 2465    }
 2466
 2467    pub fn toggle_inline_completions(
 2468        &mut self,
 2469        _: &ToggleInlineCompletions,
 2470        cx: &mut ViewContext<Self>,
 2471    ) {
 2472        if self.show_inline_completions_override.is_some() {
 2473            self.set_show_inline_completions(None, cx);
 2474        } else {
 2475            let cursor = self.selections.newest_anchor().head();
 2476            if let Some((buffer, cursor_buffer_position)) =
 2477                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2478            {
 2479                let show_inline_completions =
 2480                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2481                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2482            }
 2483        }
 2484    }
 2485
 2486    pub fn set_show_inline_completions(
 2487        &mut self,
 2488        show_inline_completions: Option<bool>,
 2489        cx: &mut ViewContext<Self>,
 2490    ) {
 2491        self.show_inline_completions_override = show_inline_completions;
 2492        self.refresh_inline_completion(false, true, cx);
 2493    }
 2494
 2495    fn should_show_inline_completions(
 2496        &self,
 2497        buffer: &Model<Buffer>,
 2498        buffer_position: language::Anchor,
 2499        cx: &AppContext,
 2500    ) -> bool {
 2501        if let Some(provider) = self.inline_completion_provider() {
 2502            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2503                show_inline_completions
 2504            } else {
 2505                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2506            }
 2507        } else {
 2508            false
 2509        }
 2510    }
 2511
 2512    pub fn set_use_modal_editing(&mut self, to: bool) {
 2513        self.use_modal_editing = to;
 2514    }
 2515
 2516    pub fn use_modal_editing(&self) -> bool {
 2517        self.use_modal_editing
 2518    }
 2519
 2520    fn selections_did_change(
 2521        &mut self,
 2522        local: bool,
 2523        old_cursor_position: &Anchor,
 2524        show_completions: bool,
 2525        cx: &mut ViewContext<Self>,
 2526    ) {
 2527        cx.invalidate_character_coordinates();
 2528
 2529        // Copy selections to primary selection buffer
 2530        #[cfg(target_os = "linux")]
 2531        if local {
 2532            let selections = self.selections.all::<usize>(cx);
 2533            let buffer_handle = self.buffer.read(cx).read(cx);
 2534
 2535            let mut text = String::new();
 2536            for (index, selection) in selections.iter().enumerate() {
 2537                let text_for_selection = buffer_handle
 2538                    .text_for_range(selection.start..selection.end)
 2539                    .collect::<String>();
 2540
 2541                text.push_str(&text_for_selection);
 2542                if index != selections.len() - 1 {
 2543                    text.push('\n');
 2544                }
 2545            }
 2546
 2547            if !text.is_empty() {
 2548                cx.write_to_primary(ClipboardItem::new_string(text));
 2549            }
 2550        }
 2551
 2552        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2553            self.buffer.update(cx, |buffer, cx| {
 2554                buffer.set_active_selections(
 2555                    &self.selections.disjoint_anchors(),
 2556                    self.selections.line_mode,
 2557                    self.cursor_shape,
 2558                    cx,
 2559                )
 2560            });
 2561        }
 2562        let display_map = self
 2563            .display_map
 2564            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2565        let buffer = &display_map.buffer_snapshot;
 2566        self.add_selections_state = None;
 2567        self.select_next_state = None;
 2568        self.select_prev_state = None;
 2569        self.select_larger_syntax_node_stack.clear();
 2570        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2571        self.snippet_stack
 2572            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2573        self.take_rename(false, cx);
 2574
 2575        let new_cursor_position = self.selections.newest_anchor().head();
 2576
 2577        self.push_to_nav_history(
 2578            *old_cursor_position,
 2579            Some(new_cursor_position.to_point(buffer)),
 2580            cx,
 2581        );
 2582
 2583        if local {
 2584            let new_cursor_position = self.selections.newest_anchor().head();
 2585            let mut context_menu = self.context_menu.write();
 2586            let completion_menu = match context_menu.as_ref() {
 2587                Some(ContextMenu::Completions(menu)) => Some(menu),
 2588
 2589                _ => {
 2590                    *context_menu = None;
 2591                    None
 2592                }
 2593            };
 2594
 2595            if let Some(completion_menu) = completion_menu {
 2596                let cursor_position = new_cursor_position.to_offset(buffer);
 2597                let (word_range, kind) =
 2598                    buffer.surrounding_word(completion_menu.initial_position, true);
 2599                if kind == Some(CharKind::Word)
 2600                    && word_range.to_inclusive().contains(&cursor_position)
 2601                {
 2602                    let mut completion_menu = completion_menu.clone();
 2603                    drop(context_menu);
 2604
 2605                    let query = Self::completion_query(buffer, cursor_position);
 2606                    cx.spawn(move |this, mut cx| async move {
 2607                        completion_menu
 2608                            .filter(query.as_deref(), cx.background_executor().clone())
 2609                            .await;
 2610
 2611                        this.update(&mut cx, |this, cx| {
 2612                            let mut context_menu = this.context_menu.write();
 2613                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2614                                return;
 2615                            };
 2616
 2617                            if menu.id > completion_menu.id {
 2618                                return;
 2619                            }
 2620
 2621                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2622                            drop(context_menu);
 2623                            cx.notify();
 2624                        })
 2625                    })
 2626                    .detach();
 2627
 2628                    if show_completions {
 2629                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2630                    }
 2631                } else {
 2632                    drop(context_menu);
 2633                    self.hide_context_menu(cx);
 2634                }
 2635            } else {
 2636                drop(context_menu);
 2637            }
 2638
 2639            hide_hover(self, cx);
 2640
 2641            if old_cursor_position.to_display_point(&display_map).row()
 2642                != new_cursor_position.to_display_point(&display_map).row()
 2643            {
 2644                self.available_code_actions.take();
 2645            }
 2646            self.refresh_code_actions(cx);
 2647            self.refresh_document_highlights(cx);
 2648            refresh_matching_bracket_highlights(self, cx);
 2649            self.discard_inline_completion(false, cx);
 2650            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2651            if self.git_blame_inline_enabled {
 2652                self.start_inline_blame_timer(cx);
 2653            }
 2654        }
 2655
 2656        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2657        cx.emit(EditorEvent::SelectionsChanged { local });
 2658
 2659        if self.selections.disjoint_anchors().len() == 1 {
 2660            cx.emit(SearchEvent::ActiveMatchChanged)
 2661        }
 2662        cx.notify();
 2663    }
 2664
 2665    pub fn change_selections<R>(
 2666        &mut self,
 2667        autoscroll: Option<Autoscroll>,
 2668        cx: &mut ViewContext<Self>,
 2669        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2670    ) -> R {
 2671        self.change_selections_inner(autoscroll, true, cx, change)
 2672    }
 2673
 2674    pub fn change_selections_inner<R>(
 2675        &mut self,
 2676        autoscroll: Option<Autoscroll>,
 2677        request_completions: bool,
 2678        cx: &mut ViewContext<Self>,
 2679        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2680    ) -> R {
 2681        let old_cursor_position = self.selections.newest_anchor().head();
 2682        self.push_to_selection_history();
 2683
 2684        let (changed, result) = self.selections.change_with(cx, change);
 2685
 2686        if changed {
 2687            if let Some(autoscroll) = autoscroll {
 2688                self.request_autoscroll(autoscroll, cx);
 2689            }
 2690            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2691
 2692            if self.should_open_signature_help_automatically(
 2693                &old_cursor_position,
 2694                self.signature_help_state.backspace_pressed(),
 2695                cx,
 2696            ) {
 2697                self.show_signature_help(&ShowSignatureHelp, cx);
 2698            }
 2699            self.signature_help_state.set_backspace_pressed(false);
 2700        }
 2701
 2702        result
 2703    }
 2704
 2705    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2706    where
 2707        I: IntoIterator<Item = (Range<S>, T)>,
 2708        S: ToOffset,
 2709        T: Into<Arc<str>>,
 2710    {
 2711        if self.read_only(cx) {
 2712            return;
 2713        }
 2714
 2715        self.buffer
 2716            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2717    }
 2718
 2719    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2720    where
 2721        I: IntoIterator<Item = (Range<S>, T)>,
 2722        S: ToOffset,
 2723        T: Into<Arc<str>>,
 2724    {
 2725        if self.read_only(cx) {
 2726            return;
 2727        }
 2728
 2729        self.buffer.update(cx, |buffer, cx| {
 2730            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2731        });
 2732    }
 2733
 2734    pub fn edit_with_block_indent<I, S, T>(
 2735        &mut self,
 2736        edits: I,
 2737        original_indent_columns: Vec<u32>,
 2738        cx: &mut ViewContext<Self>,
 2739    ) where
 2740        I: IntoIterator<Item = (Range<S>, T)>,
 2741        S: ToOffset,
 2742        T: Into<Arc<str>>,
 2743    {
 2744        if self.read_only(cx) {
 2745            return;
 2746        }
 2747
 2748        self.buffer.update(cx, |buffer, cx| {
 2749            buffer.edit(
 2750                edits,
 2751                Some(AutoindentMode::Block {
 2752                    original_indent_columns,
 2753                }),
 2754                cx,
 2755            )
 2756        });
 2757    }
 2758
 2759    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2760        self.hide_context_menu(cx);
 2761
 2762        match phase {
 2763            SelectPhase::Begin {
 2764                position,
 2765                add,
 2766                click_count,
 2767            } => self.begin_selection(position, add, click_count, cx),
 2768            SelectPhase::BeginColumnar {
 2769                position,
 2770                goal_column,
 2771                reset,
 2772            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2773            SelectPhase::Extend {
 2774                position,
 2775                click_count,
 2776            } => self.extend_selection(position, click_count, cx),
 2777            SelectPhase::Update {
 2778                position,
 2779                goal_column,
 2780                scroll_delta,
 2781            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2782            SelectPhase::End => self.end_selection(cx),
 2783        }
 2784    }
 2785
 2786    fn extend_selection(
 2787        &mut self,
 2788        position: DisplayPoint,
 2789        click_count: usize,
 2790        cx: &mut ViewContext<Self>,
 2791    ) {
 2792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2793        let tail = self.selections.newest::<usize>(cx).tail();
 2794        self.begin_selection(position, false, click_count, cx);
 2795
 2796        let position = position.to_offset(&display_map, Bias::Left);
 2797        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2798
 2799        let mut pending_selection = self
 2800            .selections
 2801            .pending_anchor()
 2802            .expect("extend_selection not called with pending selection");
 2803        if position >= tail {
 2804            pending_selection.start = tail_anchor;
 2805        } else {
 2806            pending_selection.end = tail_anchor;
 2807            pending_selection.reversed = true;
 2808        }
 2809
 2810        let mut pending_mode = self.selections.pending_mode().unwrap();
 2811        match &mut pending_mode {
 2812            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2813            _ => {}
 2814        }
 2815
 2816        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2817            s.set_pending(pending_selection, pending_mode)
 2818        });
 2819    }
 2820
 2821    fn begin_selection(
 2822        &mut self,
 2823        position: DisplayPoint,
 2824        add: bool,
 2825        click_count: usize,
 2826        cx: &mut ViewContext<Self>,
 2827    ) {
 2828        if !self.focus_handle.is_focused(cx) {
 2829            self.last_focused_descendant = None;
 2830            cx.focus(&self.focus_handle);
 2831        }
 2832
 2833        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2834        let buffer = &display_map.buffer_snapshot;
 2835        let newest_selection = self.selections.newest_anchor().clone();
 2836        let position = display_map.clip_point(position, Bias::Left);
 2837
 2838        let start;
 2839        let end;
 2840        let mode;
 2841        let auto_scroll;
 2842        match click_count {
 2843            1 => {
 2844                start = buffer.anchor_before(position.to_point(&display_map));
 2845                end = start;
 2846                mode = SelectMode::Character;
 2847                auto_scroll = true;
 2848            }
 2849            2 => {
 2850                let range = movement::surrounding_word(&display_map, position);
 2851                start = buffer.anchor_before(range.start.to_point(&display_map));
 2852                end = buffer.anchor_before(range.end.to_point(&display_map));
 2853                mode = SelectMode::Word(start..end);
 2854                auto_scroll = true;
 2855            }
 2856            3 => {
 2857                let position = display_map
 2858                    .clip_point(position, Bias::Left)
 2859                    .to_point(&display_map);
 2860                let line_start = display_map.prev_line_boundary(position).0;
 2861                let next_line_start = buffer.clip_point(
 2862                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2863                    Bias::Left,
 2864                );
 2865                start = buffer.anchor_before(line_start);
 2866                end = buffer.anchor_before(next_line_start);
 2867                mode = SelectMode::Line(start..end);
 2868                auto_scroll = true;
 2869            }
 2870            _ => {
 2871                start = buffer.anchor_before(0);
 2872                end = buffer.anchor_before(buffer.len());
 2873                mode = SelectMode::All;
 2874                auto_scroll = false;
 2875            }
 2876        }
 2877
 2878        let point_to_delete: Option<usize> = {
 2879            let selected_points: Vec<Selection<Point>> =
 2880                self.selections.disjoint_in_range(start..end, cx);
 2881
 2882            if !add || click_count > 1 {
 2883                None
 2884            } else if !selected_points.is_empty() {
 2885                Some(selected_points[0].id)
 2886            } else {
 2887                let clicked_point_already_selected =
 2888                    self.selections.disjoint.iter().find(|selection| {
 2889                        selection.start.to_point(buffer) == start.to_point(buffer)
 2890                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2891                    });
 2892
 2893                clicked_point_already_selected.map(|selection| selection.id)
 2894            }
 2895        };
 2896
 2897        let selections_count = self.selections.count();
 2898
 2899        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2900            if let Some(point_to_delete) = point_to_delete {
 2901                s.delete(point_to_delete);
 2902
 2903                if selections_count == 1 {
 2904                    s.set_pending_anchor_range(start..end, mode);
 2905                }
 2906            } else {
 2907                if !add {
 2908                    s.clear_disjoint();
 2909                } else if click_count > 1 {
 2910                    s.delete(newest_selection.id)
 2911                }
 2912
 2913                s.set_pending_anchor_range(start..end, mode);
 2914            }
 2915        });
 2916    }
 2917
 2918    fn begin_columnar_selection(
 2919        &mut self,
 2920        position: DisplayPoint,
 2921        goal_column: u32,
 2922        reset: bool,
 2923        cx: &mut ViewContext<Self>,
 2924    ) {
 2925        if !self.focus_handle.is_focused(cx) {
 2926            self.last_focused_descendant = None;
 2927            cx.focus(&self.focus_handle);
 2928        }
 2929
 2930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2931
 2932        if reset {
 2933            let pointer_position = display_map
 2934                .buffer_snapshot
 2935                .anchor_before(position.to_point(&display_map));
 2936
 2937            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2938                s.clear_disjoint();
 2939                s.set_pending_anchor_range(
 2940                    pointer_position..pointer_position,
 2941                    SelectMode::Character,
 2942                );
 2943            });
 2944        }
 2945
 2946        let tail = self.selections.newest::<Point>(cx).tail();
 2947        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2948
 2949        if !reset {
 2950            self.select_columns(
 2951                tail.to_display_point(&display_map),
 2952                position,
 2953                goal_column,
 2954                &display_map,
 2955                cx,
 2956            );
 2957        }
 2958    }
 2959
 2960    fn update_selection(
 2961        &mut self,
 2962        position: DisplayPoint,
 2963        goal_column: u32,
 2964        scroll_delta: gpui::Point<f32>,
 2965        cx: &mut ViewContext<Self>,
 2966    ) {
 2967        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2968
 2969        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2970            let tail = tail.to_display_point(&display_map);
 2971            self.select_columns(tail, position, goal_column, &display_map, cx);
 2972        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2973            let buffer = self.buffer.read(cx).snapshot(cx);
 2974            let head;
 2975            let tail;
 2976            let mode = self.selections.pending_mode().unwrap();
 2977            match &mode {
 2978                SelectMode::Character => {
 2979                    head = position.to_point(&display_map);
 2980                    tail = pending.tail().to_point(&buffer);
 2981                }
 2982                SelectMode::Word(original_range) => {
 2983                    let original_display_range = original_range.start.to_display_point(&display_map)
 2984                        ..original_range.end.to_display_point(&display_map);
 2985                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2986                        ..original_display_range.end.to_point(&display_map);
 2987                    if movement::is_inside_word(&display_map, position)
 2988                        || original_display_range.contains(&position)
 2989                    {
 2990                        let word_range = movement::surrounding_word(&display_map, position);
 2991                        if word_range.start < original_display_range.start {
 2992                            head = word_range.start.to_point(&display_map);
 2993                        } else {
 2994                            head = word_range.end.to_point(&display_map);
 2995                        }
 2996                    } else {
 2997                        head = position.to_point(&display_map);
 2998                    }
 2999
 3000                    if head <= original_buffer_range.start {
 3001                        tail = original_buffer_range.end;
 3002                    } else {
 3003                        tail = original_buffer_range.start;
 3004                    }
 3005                }
 3006                SelectMode::Line(original_range) => {
 3007                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3008
 3009                    let position = display_map
 3010                        .clip_point(position, Bias::Left)
 3011                        .to_point(&display_map);
 3012                    let line_start = display_map.prev_line_boundary(position).0;
 3013                    let next_line_start = buffer.clip_point(
 3014                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3015                        Bias::Left,
 3016                    );
 3017
 3018                    if line_start < original_range.start {
 3019                        head = line_start
 3020                    } else {
 3021                        head = next_line_start
 3022                    }
 3023
 3024                    if head <= original_range.start {
 3025                        tail = original_range.end;
 3026                    } else {
 3027                        tail = original_range.start;
 3028                    }
 3029                }
 3030                SelectMode::All => {
 3031                    return;
 3032                }
 3033            };
 3034
 3035            if head < tail {
 3036                pending.start = buffer.anchor_before(head);
 3037                pending.end = buffer.anchor_before(tail);
 3038                pending.reversed = true;
 3039            } else {
 3040                pending.start = buffer.anchor_before(tail);
 3041                pending.end = buffer.anchor_before(head);
 3042                pending.reversed = false;
 3043            }
 3044
 3045            self.change_selections(None, cx, |s| {
 3046                s.set_pending(pending, mode);
 3047            });
 3048        } else {
 3049            log::error!("update_selection dispatched with no pending selection");
 3050            return;
 3051        }
 3052
 3053        self.apply_scroll_delta(scroll_delta, cx);
 3054        cx.notify();
 3055    }
 3056
 3057    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3058        self.columnar_selection_tail.take();
 3059        if self.selections.pending_anchor().is_some() {
 3060            let selections = self.selections.all::<usize>(cx);
 3061            self.change_selections(None, cx, |s| {
 3062                s.select(selections);
 3063                s.clear_pending();
 3064            });
 3065        }
 3066    }
 3067
 3068    fn select_columns(
 3069        &mut self,
 3070        tail: DisplayPoint,
 3071        head: DisplayPoint,
 3072        goal_column: u32,
 3073        display_map: &DisplaySnapshot,
 3074        cx: &mut ViewContext<Self>,
 3075    ) {
 3076        let start_row = cmp::min(tail.row(), head.row());
 3077        let end_row = cmp::max(tail.row(), head.row());
 3078        let start_column = cmp::min(tail.column(), goal_column);
 3079        let end_column = cmp::max(tail.column(), goal_column);
 3080        let reversed = start_column < tail.column();
 3081
 3082        let selection_ranges = (start_row.0..=end_row.0)
 3083            .map(DisplayRow)
 3084            .filter_map(|row| {
 3085                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3086                    let start = display_map
 3087                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3088                        .to_point(display_map);
 3089                    let end = display_map
 3090                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3091                        .to_point(display_map);
 3092                    if reversed {
 3093                        Some(end..start)
 3094                    } else {
 3095                        Some(start..end)
 3096                    }
 3097                } else {
 3098                    None
 3099                }
 3100            })
 3101            .collect::<Vec<_>>();
 3102
 3103        self.change_selections(None, cx, |s| {
 3104            s.select_ranges(selection_ranges);
 3105        });
 3106        cx.notify();
 3107    }
 3108
 3109    pub fn has_pending_nonempty_selection(&self) -> bool {
 3110        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3111            Some(Selection { start, end, .. }) => start != end,
 3112            None => false,
 3113        };
 3114
 3115        pending_nonempty_selection
 3116            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3117    }
 3118
 3119    pub fn has_pending_selection(&self) -> bool {
 3120        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3121    }
 3122
 3123    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3124        if self.clear_expanded_diff_hunks(cx) {
 3125            cx.notify();
 3126            return;
 3127        }
 3128        if self.dismiss_menus_and_popups(true, cx) {
 3129            return;
 3130        }
 3131
 3132        if self.mode == EditorMode::Full
 3133            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3134        {
 3135            return;
 3136        }
 3137
 3138        cx.propagate();
 3139    }
 3140
 3141    pub fn dismiss_menus_and_popups(
 3142        &mut self,
 3143        should_report_inline_completion_event: bool,
 3144        cx: &mut ViewContext<Self>,
 3145    ) -> bool {
 3146        if self.take_rename(false, cx).is_some() {
 3147            return true;
 3148        }
 3149
 3150        if hide_hover(self, cx) {
 3151            return true;
 3152        }
 3153
 3154        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3155            return true;
 3156        }
 3157
 3158        if self.hide_context_menu(cx).is_some() {
 3159            return true;
 3160        }
 3161
 3162        if self.mouse_context_menu.take().is_some() {
 3163            return true;
 3164        }
 3165
 3166        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3167            return true;
 3168        }
 3169
 3170        if self.snippet_stack.pop().is_some() {
 3171            return true;
 3172        }
 3173
 3174        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3175            self.dismiss_diagnostics(cx);
 3176            return true;
 3177        }
 3178
 3179        false
 3180    }
 3181
 3182    fn linked_editing_ranges_for(
 3183        &self,
 3184        selection: Range<text::Anchor>,
 3185        cx: &AppContext,
 3186    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3187        if self.linked_edit_ranges.is_empty() {
 3188            return None;
 3189        }
 3190        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3191            selection.end.buffer_id.and_then(|end_buffer_id| {
 3192                if selection.start.buffer_id != Some(end_buffer_id) {
 3193                    return None;
 3194                }
 3195                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3196                let snapshot = buffer.read(cx).snapshot();
 3197                self.linked_edit_ranges
 3198                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3199                    .map(|ranges| (ranges, snapshot, buffer))
 3200            })?;
 3201        use text::ToOffset as TO;
 3202        // find offset from the start of current range to current cursor position
 3203        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3204
 3205        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3206        let start_difference = start_offset - start_byte_offset;
 3207        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3208        let end_difference = end_offset - start_byte_offset;
 3209        // Current range has associated linked ranges.
 3210        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3211        for range in linked_ranges.iter() {
 3212            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3213            let end_offset = start_offset + end_difference;
 3214            let start_offset = start_offset + start_difference;
 3215            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3216                continue;
 3217            }
 3218            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3219                if s.start.buffer_id != selection.start.buffer_id
 3220                    || s.end.buffer_id != selection.end.buffer_id
 3221                {
 3222                    return false;
 3223                }
 3224                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3225                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3226            }) {
 3227                continue;
 3228            }
 3229            let start = buffer_snapshot.anchor_after(start_offset);
 3230            let end = buffer_snapshot.anchor_after(end_offset);
 3231            linked_edits
 3232                .entry(buffer.clone())
 3233                .or_default()
 3234                .push(start..end);
 3235        }
 3236        Some(linked_edits)
 3237    }
 3238
 3239    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3240        let text: Arc<str> = text.into();
 3241
 3242        if self.read_only(cx) {
 3243            return;
 3244        }
 3245
 3246        let selections = self.selections.all_adjusted(cx);
 3247        let mut bracket_inserted = false;
 3248        let mut edits = Vec::new();
 3249        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3250        let mut new_selections = Vec::with_capacity(selections.len());
 3251        let mut new_autoclose_regions = Vec::new();
 3252        let snapshot = self.buffer.read(cx).read(cx);
 3253
 3254        for (selection, autoclose_region) in
 3255            self.selections_with_autoclose_regions(selections, &snapshot)
 3256        {
 3257            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3258                // Determine if the inserted text matches the opening or closing
 3259                // bracket of any of this language's bracket pairs.
 3260                let mut bracket_pair = None;
 3261                let mut is_bracket_pair_start = false;
 3262                let mut is_bracket_pair_end = false;
 3263                if !text.is_empty() {
 3264                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3265                    //  and they are removing the character that triggered IME popup.
 3266                    for (pair, enabled) in scope.brackets() {
 3267                        if !pair.close && !pair.surround {
 3268                            continue;
 3269                        }
 3270
 3271                        if enabled && pair.start.ends_with(text.as_ref()) {
 3272                            let prefix_len = pair.start.len() - text.len();
 3273                            let preceding_text_matches_prefix = prefix_len == 0
 3274                                || (selection.start.column >= (prefix_len as u32)
 3275                                    && snapshot.contains_str_at(
 3276                                        Point::new(
 3277                                            selection.start.row,
 3278                                            selection.start.column - (prefix_len as u32),
 3279                                        ),
 3280                                        &pair.start[..prefix_len],
 3281                                    ));
 3282                            if preceding_text_matches_prefix {
 3283                                bracket_pair = Some(pair.clone());
 3284                                is_bracket_pair_start = true;
 3285                                break;
 3286                            }
 3287                        }
 3288                        if pair.end.as_str() == text.as_ref() {
 3289                            bracket_pair = Some(pair.clone());
 3290                            is_bracket_pair_end = true;
 3291                            break;
 3292                        }
 3293                    }
 3294                }
 3295
 3296                if let Some(bracket_pair) = bracket_pair {
 3297                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3298                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3299                    let auto_surround =
 3300                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3301                    if selection.is_empty() {
 3302                        if is_bracket_pair_start {
 3303                            // If the inserted text is a suffix of an opening bracket and the
 3304                            // selection is preceded by the rest of the opening bracket, then
 3305                            // insert the closing bracket.
 3306                            let following_text_allows_autoclose = snapshot
 3307                                .chars_at(selection.start)
 3308                                .next()
 3309                                .map_or(true, |c| scope.should_autoclose_before(c));
 3310
 3311                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3312                                && bracket_pair.start.len() == 1
 3313                            {
 3314                                let target = bracket_pair.start.chars().next().unwrap();
 3315                                let current_line_count = snapshot
 3316                                    .reversed_chars_at(selection.start)
 3317                                    .take_while(|&c| c != '\n')
 3318                                    .filter(|&c| c == target)
 3319                                    .count();
 3320                                current_line_count % 2 == 1
 3321                            } else {
 3322                                false
 3323                            };
 3324
 3325                            if autoclose
 3326                                && bracket_pair.close
 3327                                && following_text_allows_autoclose
 3328                                && !is_closing_quote
 3329                            {
 3330                                let anchor = snapshot.anchor_before(selection.end);
 3331                                new_selections.push((selection.map(|_| anchor), text.len()));
 3332                                new_autoclose_regions.push((
 3333                                    anchor,
 3334                                    text.len(),
 3335                                    selection.id,
 3336                                    bracket_pair.clone(),
 3337                                ));
 3338                                edits.push((
 3339                                    selection.range(),
 3340                                    format!("{}{}", text, bracket_pair.end).into(),
 3341                                ));
 3342                                bracket_inserted = true;
 3343                                continue;
 3344                            }
 3345                        }
 3346
 3347                        if let Some(region) = autoclose_region {
 3348                            // If the selection is followed by an auto-inserted closing bracket,
 3349                            // then don't insert that closing bracket again; just move the selection
 3350                            // past the closing bracket.
 3351                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3352                                && text.as_ref() == region.pair.end.as_str();
 3353                            if should_skip {
 3354                                let anchor = snapshot.anchor_after(selection.end);
 3355                                new_selections
 3356                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3357                                continue;
 3358                            }
 3359                        }
 3360
 3361                        let always_treat_brackets_as_autoclosed = snapshot
 3362                            .settings_at(selection.start, cx)
 3363                            .always_treat_brackets_as_autoclosed;
 3364                        if always_treat_brackets_as_autoclosed
 3365                            && is_bracket_pair_end
 3366                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3367                        {
 3368                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3369                            // and the inserted text is a closing bracket and the selection is followed
 3370                            // by the closing bracket then move the selection past the closing bracket.
 3371                            let anchor = snapshot.anchor_after(selection.end);
 3372                            new_selections.push((selection.map(|_| anchor), text.len()));
 3373                            continue;
 3374                        }
 3375                    }
 3376                    // If an opening bracket is 1 character long and is typed while
 3377                    // text is selected, then surround that text with the bracket pair.
 3378                    else if auto_surround
 3379                        && bracket_pair.surround
 3380                        && is_bracket_pair_start
 3381                        && bracket_pair.start.chars().count() == 1
 3382                    {
 3383                        edits.push((selection.start..selection.start, text.clone()));
 3384                        edits.push((
 3385                            selection.end..selection.end,
 3386                            bracket_pair.end.as_str().into(),
 3387                        ));
 3388                        bracket_inserted = true;
 3389                        new_selections.push((
 3390                            Selection {
 3391                                id: selection.id,
 3392                                start: snapshot.anchor_after(selection.start),
 3393                                end: snapshot.anchor_before(selection.end),
 3394                                reversed: selection.reversed,
 3395                                goal: selection.goal,
 3396                            },
 3397                            0,
 3398                        ));
 3399                        continue;
 3400                    }
 3401                }
 3402            }
 3403
 3404            if self.auto_replace_emoji_shortcode
 3405                && selection.is_empty()
 3406                && text.as_ref().ends_with(':')
 3407            {
 3408                if let Some(possible_emoji_short_code) =
 3409                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3410                {
 3411                    if !possible_emoji_short_code.is_empty() {
 3412                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3413                            let emoji_shortcode_start = Point::new(
 3414                                selection.start.row,
 3415                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3416                            );
 3417
 3418                            // Remove shortcode from buffer
 3419                            edits.push((
 3420                                emoji_shortcode_start..selection.start,
 3421                                "".to_string().into(),
 3422                            ));
 3423                            new_selections.push((
 3424                                Selection {
 3425                                    id: selection.id,
 3426                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3427                                    end: snapshot.anchor_before(selection.start),
 3428                                    reversed: selection.reversed,
 3429                                    goal: selection.goal,
 3430                                },
 3431                                0,
 3432                            ));
 3433
 3434                            // Insert emoji
 3435                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3436                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3437                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3438
 3439                            continue;
 3440                        }
 3441                    }
 3442                }
 3443            }
 3444
 3445            // If not handling any auto-close operation, then just replace the selected
 3446            // text with the given input and move the selection to the end of the
 3447            // newly inserted text.
 3448            let anchor = snapshot.anchor_after(selection.end);
 3449            if !self.linked_edit_ranges.is_empty() {
 3450                let start_anchor = snapshot.anchor_before(selection.start);
 3451
 3452                let is_word_char = text.chars().next().map_or(true, |char| {
 3453                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3454                    classifier.is_word(char)
 3455                });
 3456
 3457                if is_word_char {
 3458                    if let Some(ranges) = self
 3459                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3460                    {
 3461                        for (buffer, edits) in ranges {
 3462                            linked_edits
 3463                                .entry(buffer.clone())
 3464                                .or_default()
 3465                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3466                        }
 3467                    }
 3468                }
 3469            }
 3470
 3471            new_selections.push((selection.map(|_| anchor), 0));
 3472            edits.push((selection.start..selection.end, text.clone()));
 3473        }
 3474
 3475        drop(snapshot);
 3476
 3477        self.transact(cx, |this, cx| {
 3478            this.buffer.update(cx, |buffer, cx| {
 3479                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3480            });
 3481            for (buffer, edits) in linked_edits {
 3482                buffer.update(cx, |buffer, cx| {
 3483                    let snapshot = buffer.snapshot();
 3484                    let edits = edits
 3485                        .into_iter()
 3486                        .map(|(range, text)| {
 3487                            use text::ToPoint as TP;
 3488                            let end_point = TP::to_point(&range.end, &snapshot);
 3489                            let start_point = TP::to_point(&range.start, &snapshot);
 3490                            (start_point..end_point, text)
 3491                        })
 3492                        .sorted_by_key(|(range, _)| range.start)
 3493                        .collect::<Vec<_>>();
 3494                    buffer.edit(edits, None, cx);
 3495                })
 3496            }
 3497            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3498            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3499            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3500            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3501                .zip(new_selection_deltas)
 3502                .map(|(selection, delta)| Selection {
 3503                    id: selection.id,
 3504                    start: selection.start + delta,
 3505                    end: selection.end + delta,
 3506                    reversed: selection.reversed,
 3507                    goal: SelectionGoal::None,
 3508                })
 3509                .collect::<Vec<_>>();
 3510
 3511            let mut i = 0;
 3512            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3513                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3514                let start = map.buffer_snapshot.anchor_before(position);
 3515                let end = map.buffer_snapshot.anchor_after(position);
 3516                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3517                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3518                        Ordering::Less => i += 1,
 3519                        Ordering::Greater => break,
 3520                        Ordering::Equal => {
 3521                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3522                                Ordering::Less => i += 1,
 3523                                Ordering::Equal => break,
 3524                                Ordering::Greater => break,
 3525                            }
 3526                        }
 3527                    }
 3528                }
 3529                this.autoclose_regions.insert(
 3530                    i,
 3531                    AutocloseRegion {
 3532                        selection_id,
 3533                        range: start..end,
 3534                        pair,
 3535                    },
 3536                );
 3537            }
 3538
 3539            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3540            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3541                s.select(new_selections)
 3542            });
 3543
 3544            if !bracket_inserted {
 3545                if let Some(on_type_format_task) =
 3546                    this.trigger_on_type_formatting(text.to_string(), cx)
 3547                {
 3548                    on_type_format_task.detach_and_log_err(cx);
 3549                }
 3550            }
 3551
 3552            let editor_settings = EditorSettings::get_global(cx);
 3553            if bracket_inserted
 3554                && (editor_settings.auto_signature_help
 3555                    || editor_settings.show_signature_help_after_edits)
 3556            {
 3557                this.show_signature_help(&ShowSignatureHelp, cx);
 3558            }
 3559
 3560            let trigger_in_words = !had_active_inline_completion;
 3561            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3562            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3563            this.refresh_inline_completion(true, false, cx);
 3564        });
 3565    }
 3566
 3567    fn find_possible_emoji_shortcode_at_position(
 3568        snapshot: &MultiBufferSnapshot,
 3569        position: Point,
 3570    ) -> Option<String> {
 3571        let mut chars = Vec::new();
 3572        let mut found_colon = false;
 3573        for char in snapshot.reversed_chars_at(position).take(100) {
 3574            // Found a possible emoji shortcode in the middle of the buffer
 3575            if found_colon {
 3576                if char.is_whitespace() {
 3577                    chars.reverse();
 3578                    return Some(chars.iter().collect());
 3579                }
 3580                // If the previous character is not a whitespace, we are in the middle of a word
 3581                // and we only want to complete the shortcode if the word is made up of other emojis
 3582                let mut containing_word = String::new();
 3583                for ch in snapshot
 3584                    .reversed_chars_at(position)
 3585                    .skip(chars.len() + 1)
 3586                    .take(100)
 3587                {
 3588                    if ch.is_whitespace() {
 3589                        break;
 3590                    }
 3591                    containing_word.push(ch);
 3592                }
 3593                let containing_word = containing_word.chars().rev().collect::<String>();
 3594                if util::word_consists_of_emojis(containing_word.as_str()) {
 3595                    chars.reverse();
 3596                    return Some(chars.iter().collect());
 3597                }
 3598            }
 3599
 3600            if char.is_whitespace() || !char.is_ascii() {
 3601                return None;
 3602            }
 3603            if char == ':' {
 3604                found_colon = true;
 3605            } else {
 3606                chars.push(char);
 3607            }
 3608        }
 3609        // Found a possible emoji shortcode at the beginning of the buffer
 3610        chars.reverse();
 3611        Some(chars.iter().collect())
 3612    }
 3613
 3614    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3615        self.transact(cx, |this, cx| {
 3616            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3617                let selections = this.selections.all::<usize>(cx);
 3618                let multi_buffer = this.buffer.read(cx);
 3619                let buffer = multi_buffer.snapshot(cx);
 3620                selections
 3621                    .iter()
 3622                    .map(|selection| {
 3623                        let start_point = selection.start.to_point(&buffer);
 3624                        let mut indent =
 3625                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3626                        indent.len = cmp::min(indent.len, start_point.column);
 3627                        let start = selection.start;
 3628                        let end = selection.end;
 3629                        let selection_is_empty = start == end;
 3630                        let language_scope = buffer.language_scope_at(start);
 3631                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3632                            &language_scope
 3633                        {
 3634                            let leading_whitespace_len = buffer
 3635                                .reversed_chars_at(start)
 3636                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3637                                .map(|c| c.len_utf8())
 3638                                .sum::<usize>();
 3639
 3640                            let trailing_whitespace_len = buffer
 3641                                .chars_at(end)
 3642                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3643                                .map(|c| c.len_utf8())
 3644                                .sum::<usize>();
 3645
 3646                            let insert_extra_newline =
 3647                                language.brackets().any(|(pair, enabled)| {
 3648                                    let pair_start = pair.start.trim_end();
 3649                                    let pair_end = pair.end.trim_start();
 3650
 3651                                    enabled
 3652                                        && pair.newline
 3653                                        && buffer.contains_str_at(
 3654                                            end + trailing_whitespace_len,
 3655                                            pair_end,
 3656                                        )
 3657                                        && buffer.contains_str_at(
 3658                                            (start - leading_whitespace_len)
 3659                                                .saturating_sub(pair_start.len()),
 3660                                            pair_start,
 3661                                        )
 3662                                });
 3663
 3664                            // Comment extension on newline is allowed only for cursor selections
 3665                            let comment_delimiter = maybe!({
 3666                                if !selection_is_empty {
 3667                                    return None;
 3668                                }
 3669
 3670                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3671                                    return None;
 3672                                }
 3673
 3674                                let delimiters = language.line_comment_prefixes();
 3675                                let max_len_of_delimiter =
 3676                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3677                                let (snapshot, range) =
 3678                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3679
 3680                                let mut index_of_first_non_whitespace = 0;
 3681                                let comment_candidate = snapshot
 3682                                    .chars_for_range(range)
 3683                                    .skip_while(|c| {
 3684                                        let should_skip = c.is_whitespace();
 3685                                        if should_skip {
 3686                                            index_of_first_non_whitespace += 1;
 3687                                        }
 3688                                        should_skip
 3689                                    })
 3690                                    .take(max_len_of_delimiter)
 3691                                    .collect::<String>();
 3692                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3693                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3694                                })?;
 3695                                let cursor_is_placed_after_comment_marker =
 3696                                    index_of_first_non_whitespace + comment_prefix.len()
 3697                                        <= start_point.column as usize;
 3698                                if cursor_is_placed_after_comment_marker {
 3699                                    Some(comment_prefix.clone())
 3700                                } else {
 3701                                    None
 3702                                }
 3703                            });
 3704                            (comment_delimiter, insert_extra_newline)
 3705                        } else {
 3706                            (None, false)
 3707                        };
 3708
 3709                        let capacity_for_delimiter = comment_delimiter
 3710                            .as_deref()
 3711                            .map(str::len)
 3712                            .unwrap_or_default();
 3713                        let mut new_text =
 3714                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3715                        new_text.push('\n');
 3716                        new_text.extend(indent.chars());
 3717                        if let Some(delimiter) = &comment_delimiter {
 3718                            new_text.push_str(delimiter);
 3719                        }
 3720                        if insert_extra_newline {
 3721                            new_text = new_text.repeat(2);
 3722                        }
 3723
 3724                        let anchor = buffer.anchor_after(end);
 3725                        let new_selection = selection.map(|_| anchor);
 3726                        (
 3727                            (start..end, new_text),
 3728                            (insert_extra_newline, new_selection),
 3729                        )
 3730                    })
 3731                    .unzip()
 3732            };
 3733
 3734            this.edit_with_autoindent(edits, cx);
 3735            let buffer = this.buffer.read(cx).snapshot(cx);
 3736            let new_selections = selection_fixup_info
 3737                .into_iter()
 3738                .map(|(extra_newline_inserted, new_selection)| {
 3739                    let mut cursor = new_selection.end.to_point(&buffer);
 3740                    if extra_newline_inserted {
 3741                        cursor.row -= 1;
 3742                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3743                    }
 3744                    new_selection.map(|_| cursor)
 3745                })
 3746                .collect();
 3747
 3748            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3749            this.refresh_inline_completion(true, false, cx);
 3750        });
 3751    }
 3752
 3753    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3754        let buffer = self.buffer.read(cx);
 3755        let snapshot = buffer.snapshot(cx);
 3756
 3757        let mut edits = Vec::new();
 3758        let mut rows = Vec::new();
 3759
 3760        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3761            let cursor = selection.head();
 3762            let row = cursor.row;
 3763
 3764            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3765
 3766            let newline = "\n".to_string();
 3767            edits.push((start_of_line..start_of_line, newline));
 3768
 3769            rows.push(row + rows_inserted as u32);
 3770        }
 3771
 3772        self.transact(cx, |editor, cx| {
 3773            editor.edit(edits, cx);
 3774
 3775            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3776                let mut index = 0;
 3777                s.move_cursors_with(|map, _, _| {
 3778                    let row = rows[index];
 3779                    index += 1;
 3780
 3781                    let point = Point::new(row, 0);
 3782                    let boundary = map.next_line_boundary(point).1;
 3783                    let clipped = map.clip_point(boundary, Bias::Left);
 3784
 3785                    (clipped, SelectionGoal::None)
 3786                });
 3787            });
 3788
 3789            let mut indent_edits = Vec::new();
 3790            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3791            for row in rows {
 3792                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3793                for (row, indent) in indents {
 3794                    if indent.len == 0 {
 3795                        continue;
 3796                    }
 3797
 3798                    let text = match indent.kind {
 3799                        IndentKind::Space => " ".repeat(indent.len as usize),
 3800                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3801                    };
 3802                    let point = Point::new(row.0, 0);
 3803                    indent_edits.push((point..point, text));
 3804                }
 3805            }
 3806            editor.edit(indent_edits, cx);
 3807        });
 3808    }
 3809
 3810    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3811        let buffer = self.buffer.read(cx);
 3812        let snapshot = buffer.snapshot(cx);
 3813
 3814        let mut edits = Vec::new();
 3815        let mut rows = Vec::new();
 3816        let mut rows_inserted = 0;
 3817
 3818        for selection in self.selections.all_adjusted(cx) {
 3819            let cursor = selection.head();
 3820            let row = cursor.row;
 3821
 3822            let point = Point::new(row + 1, 0);
 3823            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3824
 3825            let newline = "\n".to_string();
 3826            edits.push((start_of_line..start_of_line, newline));
 3827
 3828            rows_inserted += 1;
 3829            rows.push(row + rows_inserted);
 3830        }
 3831
 3832        self.transact(cx, |editor, cx| {
 3833            editor.edit(edits, cx);
 3834
 3835            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3836                let mut index = 0;
 3837                s.move_cursors_with(|map, _, _| {
 3838                    let row = rows[index];
 3839                    index += 1;
 3840
 3841                    let point = Point::new(row, 0);
 3842                    let boundary = map.next_line_boundary(point).1;
 3843                    let clipped = map.clip_point(boundary, Bias::Left);
 3844
 3845                    (clipped, SelectionGoal::None)
 3846                });
 3847            });
 3848
 3849            let mut indent_edits = Vec::new();
 3850            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3851            for row in rows {
 3852                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3853                for (row, indent) in indents {
 3854                    if indent.len == 0 {
 3855                        continue;
 3856                    }
 3857
 3858                    let text = match indent.kind {
 3859                        IndentKind::Space => " ".repeat(indent.len as usize),
 3860                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3861                    };
 3862                    let point = Point::new(row.0, 0);
 3863                    indent_edits.push((point..point, text));
 3864                }
 3865            }
 3866            editor.edit(indent_edits, cx);
 3867        });
 3868    }
 3869
 3870    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3871        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3872            original_indent_columns: Vec::new(),
 3873        });
 3874        self.insert_with_autoindent_mode(text, autoindent, cx);
 3875    }
 3876
 3877    fn insert_with_autoindent_mode(
 3878        &mut self,
 3879        text: &str,
 3880        autoindent_mode: Option<AutoindentMode>,
 3881        cx: &mut ViewContext<Self>,
 3882    ) {
 3883        if self.read_only(cx) {
 3884            return;
 3885        }
 3886
 3887        let text: Arc<str> = text.into();
 3888        self.transact(cx, |this, cx| {
 3889            let old_selections = this.selections.all_adjusted(cx);
 3890            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3891                let anchors = {
 3892                    let snapshot = buffer.read(cx);
 3893                    old_selections
 3894                        .iter()
 3895                        .map(|s| {
 3896                            let anchor = snapshot.anchor_after(s.head());
 3897                            s.map(|_| anchor)
 3898                        })
 3899                        .collect::<Vec<_>>()
 3900                };
 3901                buffer.edit(
 3902                    old_selections
 3903                        .iter()
 3904                        .map(|s| (s.start..s.end, text.clone())),
 3905                    autoindent_mode,
 3906                    cx,
 3907                );
 3908                anchors
 3909            });
 3910
 3911            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3912                s.select_anchors(selection_anchors);
 3913            })
 3914        });
 3915    }
 3916
 3917    fn trigger_completion_on_input(
 3918        &mut self,
 3919        text: &str,
 3920        trigger_in_words: bool,
 3921        cx: &mut ViewContext<Self>,
 3922    ) {
 3923        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3924            self.show_completions(
 3925                &ShowCompletions {
 3926                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3927                },
 3928                cx,
 3929            );
 3930        } else {
 3931            self.hide_context_menu(cx);
 3932        }
 3933    }
 3934
 3935    fn is_completion_trigger(
 3936        &self,
 3937        text: &str,
 3938        trigger_in_words: bool,
 3939        cx: &mut ViewContext<Self>,
 3940    ) -> bool {
 3941        let position = self.selections.newest_anchor().head();
 3942        let multibuffer = self.buffer.read(cx);
 3943        let Some(buffer) = position
 3944            .buffer_id
 3945            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3946        else {
 3947            return false;
 3948        };
 3949
 3950        if let Some(completion_provider) = &self.completion_provider {
 3951            completion_provider.is_completion_trigger(
 3952                &buffer,
 3953                position.text_anchor,
 3954                text,
 3955                trigger_in_words,
 3956                cx,
 3957            )
 3958        } else {
 3959            false
 3960        }
 3961    }
 3962
 3963    /// If any empty selections is touching the start of its innermost containing autoclose
 3964    /// region, expand it to select the brackets.
 3965    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3966        let selections = self.selections.all::<usize>(cx);
 3967        let buffer = self.buffer.read(cx).read(cx);
 3968        let new_selections = self
 3969            .selections_with_autoclose_regions(selections, &buffer)
 3970            .map(|(mut selection, region)| {
 3971                if !selection.is_empty() {
 3972                    return selection;
 3973                }
 3974
 3975                if let Some(region) = region {
 3976                    let mut range = region.range.to_offset(&buffer);
 3977                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3978                        range.start -= region.pair.start.len();
 3979                        if buffer.contains_str_at(range.start, &region.pair.start)
 3980                            && buffer.contains_str_at(range.end, &region.pair.end)
 3981                        {
 3982                            range.end += region.pair.end.len();
 3983                            selection.start = range.start;
 3984                            selection.end = range.end;
 3985
 3986                            return selection;
 3987                        }
 3988                    }
 3989                }
 3990
 3991                let always_treat_brackets_as_autoclosed = buffer
 3992                    .settings_at(selection.start, cx)
 3993                    .always_treat_brackets_as_autoclosed;
 3994
 3995                if !always_treat_brackets_as_autoclosed {
 3996                    return selection;
 3997                }
 3998
 3999                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4000                    for (pair, enabled) in scope.brackets() {
 4001                        if !enabled || !pair.close {
 4002                            continue;
 4003                        }
 4004
 4005                        if buffer.contains_str_at(selection.start, &pair.end) {
 4006                            let pair_start_len = pair.start.len();
 4007                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4008                            {
 4009                                selection.start -= pair_start_len;
 4010                                selection.end += pair.end.len();
 4011
 4012                                return selection;
 4013                            }
 4014                        }
 4015                    }
 4016                }
 4017
 4018                selection
 4019            })
 4020            .collect();
 4021
 4022        drop(buffer);
 4023        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4024    }
 4025
 4026    /// Iterate the given selections, and for each one, find the smallest surrounding
 4027    /// autoclose region. This uses the ordering of the selections and the autoclose
 4028    /// regions to avoid repeated comparisons.
 4029    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4030        &'a self,
 4031        selections: impl IntoIterator<Item = Selection<D>>,
 4032        buffer: &'a MultiBufferSnapshot,
 4033    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4034        let mut i = 0;
 4035        let mut regions = self.autoclose_regions.as_slice();
 4036        selections.into_iter().map(move |selection| {
 4037            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4038
 4039            let mut enclosing = None;
 4040            while let Some(pair_state) = regions.get(i) {
 4041                if pair_state.range.end.to_offset(buffer) < range.start {
 4042                    regions = &regions[i + 1..];
 4043                    i = 0;
 4044                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4045                    break;
 4046                } else {
 4047                    if pair_state.selection_id == selection.id {
 4048                        enclosing = Some(pair_state);
 4049                    }
 4050                    i += 1;
 4051                }
 4052            }
 4053
 4054            (selection, enclosing)
 4055        })
 4056    }
 4057
 4058    /// Remove any autoclose regions that no longer contain their selection.
 4059    fn invalidate_autoclose_regions(
 4060        &mut self,
 4061        mut selections: &[Selection<Anchor>],
 4062        buffer: &MultiBufferSnapshot,
 4063    ) {
 4064        self.autoclose_regions.retain(|state| {
 4065            let mut i = 0;
 4066            while let Some(selection) = selections.get(i) {
 4067                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4068                    selections = &selections[1..];
 4069                    continue;
 4070                }
 4071                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4072                    break;
 4073                }
 4074                if selection.id == state.selection_id {
 4075                    return true;
 4076                } else {
 4077                    i += 1;
 4078                }
 4079            }
 4080            false
 4081        });
 4082    }
 4083
 4084    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4085        let offset = position.to_offset(buffer);
 4086        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4087        if offset > word_range.start && kind == Some(CharKind::Word) {
 4088            Some(
 4089                buffer
 4090                    .text_for_range(word_range.start..offset)
 4091                    .collect::<String>(),
 4092            )
 4093        } else {
 4094            None
 4095        }
 4096    }
 4097
 4098    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4099        self.refresh_inlay_hints(
 4100            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4101            cx,
 4102        );
 4103    }
 4104
 4105    pub fn inlay_hints_enabled(&self) -> bool {
 4106        self.inlay_hint_cache.enabled
 4107    }
 4108
 4109    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4110        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4111            return;
 4112        }
 4113
 4114        let reason_description = reason.description();
 4115        let ignore_debounce = matches!(
 4116            reason,
 4117            InlayHintRefreshReason::SettingsChange(_)
 4118                | InlayHintRefreshReason::Toggle(_)
 4119                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4120        );
 4121        let (invalidate_cache, required_languages) = match reason {
 4122            InlayHintRefreshReason::Toggle(enabled) => {
 4123                self.inlay_hint_cache.enabled = enabled;
 4124                if enabled {
 4125                    (InvalidationStrategy::RefreshRequested, None)
 4126                } else {
 4127                    self.inlay_hint_cache.clear();
 4128                    self.splice_inlays(
 4129                        self.visible_inlay_hints(cx)
 4130                            .iter()
 4131                            .map(|inlay| inlay.id)
 4132                            .collect(),
 4133                        Vec::new(),
 4134                        cx,
 4135                    );
 4136                    return;
 4137                }
 4138            }
 4139            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4140                match self.inlay_hint_cache.update_settings(
 4141                    &self.buffer,
 4142                    new_settings,
 4143                    self.visible_inlay_hints(cx),
 4144                    cx,
 4145                ) {
 4146                    ControlFlow::Break(Some(InlaySplice {
 4147                        to_remove,
 4148                        to_insert,
 4149                    })) => {
 4150                        self.splice_inlays(to_remove, to_insert, cx);
 4151                        return;
 4152                    }
 4153                    ControlFlow::Break(None) => return,
 4154                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4155                }
 4156            }
 4157            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4158                if let Some(InlaySplice {
 4159                    to_remove,
 4160                    to_insert,
 4161                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4162                {
 4163                    self.splice_inlays(to_remove, to_insert, cx);
 4164                }
 4165                return;
 4166            }
 4167            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4168            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4169                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4170            }
 4171            InlayHintRefreshReason::RefreshRequested => {
 4172                (InvalidationStrategy::RefreshRequested, None)
 4173            }
 4174        };
 4175
 4176        if let Some(InlaySplice {
 4177            to_remove,
 4178            to_insert,
 4179        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4180            reason_description,
 4181            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4182            invalidate_cache,
 4183            ignore_debounce,
 4184            cx,
 4185        ) {
 4186            self.splice_inlays(to_remove, to_insert, cx);
 4187        }
 4188    }
 4189
 4190    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4191        self.display_map
 4192            .read(cx)
 4193            .current_inlays()
 4194            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4195            .cloned()
 4196            .collect()
 4197    }
 4198
 4199    pub fn excerpts_for_inlay_hints_query(
 4200        &self,
 4201        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4202        cx: &mut ViewContext<Editor>,
 4203    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4204        let Some(project) = self.project.as_ref() else {
 4205            return HashMap::default();
 4206        };
 4207        let project = project.read(cx);
 4208        let multi_buffer = self.buffer().read(cx);
 4209        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4210        let multi_buffer_visible_start = self
 4211            .scroll_manager
 4212            .anchor()
 4213            .anchor
 4214            .to_point(&multi_buffer_snapshot);
 4215        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4216            multi_buffer_visible_start
 4217                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4218            Bias::Left,
 4219        );
 4220        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4221        multi_buffer
 4222            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4223            .into_iter()
 4224            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4225            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4226                let buffer = buffer_handle.read(cx);
 4227                let buffer_file = project::File::from_dyn(buffer.file())?;
 4228                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4229                let worktree_entry = buffer_worktree
 4230                    .read(cx)
 4231                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4232                if worktree_entry.is_ignored {
 4233                    return None;
 4234                }
 4235
 4236                let language = buffer.language()?;
 4237                if let Some(restrict_to_languages) = restrict_to_languages {
 4238                    if !restrict_to_languages.contains(language) {
 4239                        return None;
 4240                    }
 4241                }
 4242                Some((
 4243                    excerpt_id,
 4244                    (
 4245                        buffer_handle,
 4246                        buffer.version().clone(),
 4247                        excerpt_visible_range,
 4248                    ),
 4249                ))
 4250            })
 4251            .collect()
 4252    }
 4253
 4254    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4255        TextLayoutDetails {
 4256            text_system: cx.text_system().clone(),
 4257            editor_style: self.style.clone().unwrap(),
 4258            rem_size: cx.rem_size(),
 4259            scroll_anchor: self.scroll_manager.anchor(),
 4260            visible_rows: self.visible_line_count(),
 4261            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4262        }
 4263    }
 4264
 4265    fn splice_inlays(
 4266        &self,
 4267        to_remove: Vec<InlayId>,
 4268        to_insert: Vec<Inlay>,
 4269        cx: &mut ViewContext<Self>,
 4270    ) {
 4271        self.display_map.update(cx, |display_map, cx| {
 4272            display_map.splice_inlays(to_remove, to_insert, cx);
 4273        });
 4274        cx.notify();
 4275    }
 4276
 4277    fn trigger_on_type_formatting(
 4278        &self,
 4279        input: String,
 4280        cx: &mut ViewContext<Self>,
 4281    ) -> Option<Task<Result<()>>> {
 4282        if input.len() != 1 {
 4283            return None;
 4284        }
 4285
 4286        let project = self.project.as_ref()?;
 4287        let position = self.selections.newest_anchor().head();
 4288        let (buffer, buffer_position) = self
 4289            .buffer
 4290            .read(cx)
 4291            .text_anchor_for_position(position, cx)?;
 4292
 4293        let settings = language_settings::language_settings(
 4294            buffer
 4295                .read(cx)
 4296                .language_at(buffer_position)
 4297                .map(|l| l.name()),
 4298            buffer.read(cx).file(),
 4299            cx,
 4300        );
 4301        if !settings.use_on_type_format {
 4302            return None;
 4303        }
 4304
 4305        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4306        // hence we do LSP request & edit on host side only — add formats to host's history.
 4307        let push_to_lsp_host_history = true;
 4308        // If this is not the host, append its history with new edits.
 4309        let push_to_client_history = project.read(cx).is_via_collab();
 4310
 4311        let on_type_formatting = project.update(cx, |project, cx| {
 4312            project.on_type_format(
 4313                buffer.clone(),
 4314                buffer_position,
 4315                input,
 4316                push_to_lsp_host_history,
 4317                cx,
 4318            )
 4319        });
 4320        Some(cx.spawn(|editor, mut cx| async move {
 4321            if let Some(transaction) = on_type_formatting.await? {
 4322                if push_to_client_history {
 4323                    buffer
 4324                        .update(&mut cx, |buffer, _| {
 4325                            buffer.push_transaction(transaction, Instant::now());
 4326                        })
 4327                        .ok();
 4328                }
 4329                editor.update(&mut cx, |editor, cx| {
 4330                    editor.refresh_document_highlights(cx);
 4331                })?;
 4332            }
 4333            Ok(())
 4334        }))
 4335    }
 4336
 4337    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4338        if self.pending_rename.is_some() {
 4339            return;
 4340        }
 4341
 4342        let Some(provider) = self.completion_provider.as_ref() else {
 4343            return;
 4344        };
 4345
 4346        let position = self.selections.newest_anchor().head();
 4347        let (buffer, buffer_position) =
 4348            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4349                output
 4350            } else {
 4351                return;
 4352            };
 4353
 4354        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4355        let is_followup_invoke = {
 4356            let context_menu_state = self.context_menu.read();
 4357            matches!(
 4358                context_menu_state.deref(),
 4359                Some(ContextMenu::Completions(_))
 4360            )
 4361        };
 4362        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4363            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4364            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4365                CompletionTriggerKind::TRIGGER_CHARACTER
 4366            }
 4367
 4368            _ => CompletionTriggerKind::INVOKED,
 4369        };
 4370        let completion_context = CompletionContext {
 4371            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4372                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4373                    Some(String::from(trigger))
 4374                } else {
 4375                    None
 4376                }
 4377            }),
 4378            trigger_kind,
 4379        };
 4380        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4381        let sort_completions = provider.sort_completions();
 4382
 4383        let id = post_inc(&mut self.next_completion_id);
 4384        let task = cx.spawn(|this, mut cx| {
 4385            async move {
 4386                this.update(&mut cx, |this, _| {
 4387                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4388                })?;
 4389                let completions = completions.await.log_err();
 4390                let menu = if let Some(completions) = completions {
 4391                    let mut menu = CompletionsMenu {
 4392                        id,
 4393                        sort_completions,
 4394                        initial_position: position,
 4395                        match_candidates: completions
 4396                            .iter()
 4397                            .enumerate()
 4398                            .map(|(id, completion)| {
 4399                                StringMatchCandidate::new(
 4400                                    id,
 4401                                    completion.label.text[completion.label.filter_range.clone()]
 4402                                        .into(),
 4403                                )
 4404                            })
 4405                            .collect(),
 4406                        buffer: buffer.clone(),
 4407                        completions: Arc::new(RwLock::new(completions.into())),
 4408                        matches: Vec::new().into(),
 4409                        selected_item: 0,
 4410                        scroll_handle: UniformListScrollHandle::new(),
 4411                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4412                            DebouncedDelay::new(),
 4413                        )),
 4414                    };
 4415                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4416                        .await;
 4417
 4418                    if menu.matches.is_empty() {
 4419                        None
 4420                    } else {
 4421                        this.update(&mut cx, |editor, cx| {
 4422                            let completions = menu.completions.clone();
 4423                            let matches = menu.matches.clone();
 4424
 4425                            let delay_ms = EditorSettings::get_global(cx)
 4426                                .completion_documentation_secondary_query_debounce;
 4427                            let delay = Duration::from_millis(delay_ms);
 4428                            editor
 4429                                .completion_documentation_pre_resolve_debounce
 4430                                .fire_new(delay, cx, |editor, cx| {
 4431                                    CompletionsMenu::pre_resolve_completion_documentation(
 4432                                        buffer,
 4433                                        completions,
 4434                                        matches,
 4435                                        editor,
 4436                                        cx,
 4437                                    )
 4438                                });
 4439                        })
 4440                        .ok();
 4441                        Some(menu)
 4442                    }
 4443                } else {
 4444                    None
 4445                };
 4446
 4447                this.update(&mut cx, |this, cx| {
 4448                    let mut context_menu = this.context_menu.write();
 4449                    match context_menu.as_ref() {
 4450                        None => {}
 4451
 4452                        Some(ContextMenu::Completions(prev_menu)) => {
 4453                            if prev_menu.id > id {
 4454                                return;
 4455                            }
 4456                        }
 4457
 4458                        _ => return,
 4459                    }
 4460
 4461                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4462                        let menu = menu.unwrap();
 4463                        *context_menu = Some(ContextMenu::Completions(menu));
 4464                        drop(context_menu);
 4465                        this.discard_inline_completion(false, cx);
 4466                        cx.notify();
 4467                    } else if this.completion_tasks.len() <= 1 {
 4468                        // If there are no more completion tasks and the last menu was
 4469                        // empty, we should hide it. If it was already hidden, we should
 4470                        // also show the copilot completion when available.
 4471                        drop(context_menu);
 4472                        if this.hide_context_menu(cx).is_none() {
 4473                            this.update_visible_inline_completion(cx);
 4474                        }
 4475                    }
 4476                })?;
 4477
 4478                Ok::<_, anyhow::Error>(())
 4479            }
 4480            .log_err()
 4481        });
 4482
 4483        self.completion_tasks.push((id, task));
 4484    }
 4485
 4486    pub fn confirm_completion(
 4487        &mut self,
 4488        action: &ConfirmCompletion,
 4489        cx: &mut ViewContext<Self>,
 4490    ) -> Option<Task<Result<()>>> {
 4491        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4492    }
 4493
 4494    pub fn compose_completion(
 4495        &mut self,
 4496        action: &ComposeCompletion,
 4497        cx: &mut ViewContext<Self>,
 4498    ) -> Option<Task<Result<()>>> {
 4499        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4500    }
 4501
 4502    fn do_completion(
 4503        &mut self,
 4504        item_ix: Option<usize>,
 4505        intent: CompletionIntent,
 4506        cx: &mut ViewContext<Editor>,
 4507    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4508        use language::ToOffset as _;
 4509
 4510        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4511            menu
 4512        } else {
 4513            return None;
 4514        };
 4515
 4516        let mat = completions_menu
 4517            .matches
 4518            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4519        let buffer_handle = completions_menu.buffer;
 4520        let completions = completions_menu.completions.read();
 4521        let completion = completions.get(mat.candidate_id)?;
 4522        cx.stop_propagation();
 4523
 4524        let snippet;
 4525        let text;
 4526
 4527        if completion.is_snippet() {
 4528            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4529            text = snippet.as_ref().unwrap().text.clone();
 4530        } else {
 4531            snippet = None;
 4532            text = completion.new_text.clone();
 4533        };
 4534        let selections = self.selections.all::<usize>(cx);
 4535        let buffer = buffer_handle.read(cx);
 4536        let old_range = completion.old_range.to_offset(buffer);
 4537        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4538
 4539        let newest_selection = self.selections.newest_anchor();
 4540        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4541            return None;
 4542        }
 4543
 4544        let lookbehind = newest_selection
 4545            .start
 4546            .text_anchor
 4547            .to_offset(buffer)
 4548            .saturating_sub(old_range.start);
 4549        let lookahead = old_range
 4550            .end
 4551            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4552        let mut common_prefix_len = old_text
 4553            .bytes()
 4554            .zip(text.bytes())
 4555            .take_while(|(a, b)| a == b)
 4556            .count();
 4557
 4558        let snapshot = self.buffer.read(cx).snapshot(cx);
 4559        let mut range_to_replace: Option<Range<isize>> = None;
 4560        let mut ranges = Vec::new();
 4561        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4562        for selection in &selections {
 4563            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4564                let start = selection.start.saturating_sub(lookbehind);
 4565                let end = selection.end + lookahead;
 4566                if selection.id == newest_selection.id {
 4567                    range_to_replace = Some(
 4568                        ((start + common_prefix_len) as isize - selection.start as isize)
 4569                            ..(end as isize - selection.start as isize),
 4570                    );
 4571                }
 4572                ranges.push(start + common_prefix_len..end);
 4573            } else {
 4574                common_prefix_len = 0;
 4575                ranges.clear();
 4576                ranges.extend(selections.iter().map(|s| {
 4577                    if s.id == newest_selection.id {
 4578                        range_to_replace = Some(
 4579                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4580                                - selection.start as isize
 4581                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4582                                    - selection.start as isize,
 4583                        );
 4584                        old_range.clone()
 4585                    } else {
 4586                        s.start..s.end
 4587                    }
 4588                }));
 4589                break;
 4590            }
 4591            if !self.linked_edit_ranges.is_empty() {
 4592                let start_anchor = snapshot.anchor_before(selection.head());
 4593                let end_anchor = snapshot.anchor_after(selection.tail());
 4594                if let Some(ranges) = self
 4595                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4596                {
 4597                    for (buffer, edits) in ranges {
 4598                        linked_edits.entry(buffer.clone()).or_default().extend(
 4599                            edits
 4600                                .into_iter()
 4601                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4602                        );
 4603                    }
 4604                }
 4605            }
 4606        }
 4607        let text = &text[common_prefix_len..];
 4608
 4609        cx.emit(EditorEvent::InputHandled {
 4610            utf16_range_to_replace: range_to_replace,
 4611            text: text.into(),
 4612        });
 4613
 4614        self.transact(cx, |this, cx| {
 4615            if let Some(mut snippet) = snippet {
 4616                snippet.text = text.to_string();
 4617                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4618                    tabstop.start -= common_prefix_len as isize;
 4619                    tabstop.end -= common_prefix_len as isize;
 4620                }
 4621
 4622                this.insert_snippet(&ranges, snippet, cx).log_err();
 4623            } else {
 4624                this.buffer.update(cx, |buffer, cx| {
 4625                    buffer.edit(
 4626                        ranges.iter().map(|range| (range.clone(), text)),
 4627                        this.autoindent_mode.clone(),
 4628                        cx,
 4629                    );
 4630                });
 4631            }
 4632            for (buffer, edits) in linked_edits {
 4633                buffer.update(cx, |buffer, cx| {
 4634                    let snapshot = buffer.snapshot();
 4635                    let edits = edits
 4636                        .into_iter()
 4637                        .map(|(range, text)| {
 4638                            use text::ToPoint as TP;
 4639                            let end_point = TP::to_point(&range.end, &snapshot);
 4640                            let start_point = TP::to_point(&range.start, &snapshot);
 4641                            (start_point..end_point, text)
 4642                        })
 4643                        .sorted_by_key(|(range, _)| range.start)
 4644                        .collect::<Vec<_>>();
 4645                    buffer.edit(edits, None, cx);
 4646                })
 4647            }
 4648
 4649            this.refresh_inline_completion(true, false, cx);
 4650        });
 4651
 4652        let show_new_completions_on_confirm = completion
 4653            .confirm
 4654            .as_ref()
 4655            .map_or(false, |confirm| confirm(intent, cx));
 4656        if show_new_completions_on_confirm {
 4657            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4658        }
 4659
 4660        let provider = self.completion_provider.as_ref()?;
 4661        let apply_edits = provider.apply_additional_edits_for_completion(
 4662            buffer_handle,
 4663            completion.clone(),
 4664            true,
 4665            cx,
 4666        );
 4667
 4668        let editor_settings = EditorSettings::get_global(cx);
 4669        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4670            // After the code completion is finished, users often want to know what signatures are needed.
 4671            // so we should automatically call signature_help
 4672            self.show_signature_help(&ShowSignatureHelp, cx);
 4673        }
 4674
 4675        Some(cx.foreground_executor().spawn(async move {
 4676            apply_edits.await?;
 4677            Ok(())
 4678        }))
 4679    }
 4680
 4681    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4682        let mut context_menu = self.context_menu.write();
 4683        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4684            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4685                // Toggle if we're selecting the same one
 4686                *context_menu = None;
 4687                cx.notify();
 4688                return;
 4689            } else {
 4690                // Otherwise, clear it and start a new one
 4691                *context_menu = None;
 4692                cx.notify();
 4693            }
 4694        }
 4695        drop(context_menu);
 4696        let snapshot = self.snapshot(cx);
 4697        let deployed_from_indicator = action.deployed_from_indicator;
 4698        let mut task = self.code_actions_task.take();
 4699        let action = action.clone();
 4700        cx.spawn(|editor, mut cx| async move {
 4701            while let Some(prev_task) = task {
 4702                prev_task.await.log_err();
 4703                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4704            }
 4705
 4706            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4707                if editor.focus_handle.is_focused(cx) {
 4708                    let multibuffer_point = action
 4709                        .deployed_from_indicator
 4710                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4711                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4712                    let (buffer, buffer_row) = snapshot
 4713                        .buffer_snapshot
 4714                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4715                        .and_then(|(buffer_snapshot, range)| {
 4716                            editor
 4717                                .buffer
 4718                                .read(cx)
 4719                                .buffer(buffer_snapshot.remote_id())
 4720                                .map(|buffer| (buffer, range.start.row))
 4721                        })?;
 4722                    let (_, code_actions) = editor
 4723                        .available_code_actions
 4724                        .clone()
 4725                        .and_then(|(location, code_actions)| {
 4726                            let snapshot = location.buffer.read(cx).snapshot();
 4727                            let point_range = location.range.to_point(&snapshot);
 4728                            let point_range = point_range.start.row..=point_range.end.row;
 4729                            if point_range.contains(&buffer_row) {
 4730                                Some((location, code_actions))
 4731                            } else {
 4732                                None
 4733                            }
 4734                        })
 4735                        .unzip();
 4736                    let buffer_id = buffer.read(cx).remote_id();
 4737                    let tasks = editor
 4738                        .tasks
 4739                        .get(&(buffer_id, buffer_row))
 4740                        .map(|t| Arc::new(t.to_owned()));
 4741                    if tasks.is_none() && code_actions.is_none() {
 4742                        return None;
 4743                    }
 4744
 4745                    editor.completion_tasks.clear();
 4746                    editor.discard_inline_completion(false, cx);
 4747                    let task_context =
 4748                        tasks
 4749                            .as_ref()
 4750                            .zip(editor.project.clone())
 4751                            .map(|(tasks, project)| {
 4752                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4753                            });
 4754
 4755                    Some(cx.spawn(|editor, mut cx| async move {
 4756                        let task_context = match task_context {
 4757                            Some(task_context) => task_context.await,
 4758                            None => None,
 4759                        };
 4760                        let resolved_tasks =
 4761                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4762                                Arc::new(ResolvedTasks {
 4763                                    templates: tasks.resolve(&task_context).collect(),
 4764                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4765                                        multibuffer_point.row,
 4766                                        tasks.column,
 4767                                    )),
 4768                                })
 4769                            });
 4770                        let spawn_straight_away = resolved_tasks
 4771                            .as_ref()
 4772                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4773                            && code_actions
 4774                                .as_ref()
 4775                                .map_or(true, |actions| actions.is_empty());
 4776                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4777                            *editor.context_menu.write() =
 4778                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4779                                    buffer,
 4780                                    actions: CodeActionContents {
 4781                                        tasks: resolved_tasks,
 4782                                        actions: code_actions,
 4783                                    },
 4784                                    selected_item: Default::default(),
 4785                                    scroll_handle: UniformListScrollHandle::default(),
 4786                                    deployed_from_indicator,
 4787                                }));
 4788                            if spawn_straight_away {
 4789                                if let Some(task) = editor.confirm_code_action(
 4790                                    &ConfirmCodeAction { item_ix: Some(0) },
 4791                                    cx,
 4792                                ) {
 4793                                    cx.notify();
 4794                                    return task;
 4795                                }
 4796                            }
 4797                            cx.notify();
 4798                            Task::ready(Ok(()))
 4799                        }) {
 4800                            task.await
 4801                        } else {
 4802                            Ok(())
 4803                        }
 4804                    }))
 4805                } else {
 4806                    Some(Task::ready(Ok(())))
 4807                }
 4808            })?;
 4809            if let Some(task) = spawned_test_task {
 4810                task.await?;
 4811            }
 4812
 4813            Ok::<_, anyhow::Error>(())
 4814        })
 4815        .detach_and_log_err(cx);
 4816    }
 4817
 4818    pub fn confirm_code_action(
 4819        &mut self,
 4820        action: &ConfirmCodeAction,
 4821        cx: &mut ViewContext<Self>,
 4822    ) -> Option<Task<Result<()>>> {
 4823        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4824            menu
 4825        } else {
 4826            return None;
 4827        };
 4828        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4829        let action = actions_menu.actions.get(action_ix)?;
 4830        let title = action.label();
 4831        let buffer = actions_menu.buffer;
 4832        let workspace = self.workspace()?;
 4833
 4834        match action {
 4835            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4836                workspace.update(cx, |workspace, cx| {
 4837                    workspace::tasks::schedule_resolved_task(
 4838                        workspace,
 4839                        task_source_kind,
 4840                        resolved_task,
 4841                        false,
 4842                        cx,
 4843                    );
 4844
 4845                    Some(Task::ready(Ok(())))
 4846                })
 4847            }
 4848            CodeActionsItem::CodeAction {
 4849                excerpt_id,
 4850                action,
 4851                provider,
 4852            } => {
 4853                let apply_code_action =
 4854                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4855                let workspace = workspace.downgrade();
 4856                Some(cx.spawn(|editor, cx| async move {
 4857                    let project_transaction = apply_code_action.await?;
 4858                    Self::open_project_transaction(
 4859                        &editor,
 4860                        workspace,
 4861                        project_transaction,
 4862                        title,
 4863                        cx,
 4864                    )
 4865                    .await
 4866                }))
 4867            }
 4868        }
 4869    }
 4870
 4871    pub async fn open_project_transaction(
 4872        this: &WeakView<Editor>,
 4873        workspace: WeakView<Workspace>,
 4874        transaction: ProjectTransaction,
 4875        title: String,
 4876        mut cx: AsyncWindowContext,
 4877    ) -> Result<()> {
 4878        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4879        cx.update(|cx| {
 4880            entries.sort_unstable_by_key(|(buffer, _)| {
 4881                buffer.read(cx).file().map(|f| f.path().clone())
 4882            });
 4883        })?;
 4884
 4885        // If the project transaction's edits are all contained within this editor, then
 4886        // avoid opening a new editor to display them.
 4887
 4888        if let Some((buffer, transaction)) = entries.first() {
 4889            if entries.len() == 1 {
 4890                let excerpt = this.update(&mut cx, |editor, cx| {
 4891                    editor
 4892                        .buffer()
 4893                        .read(cx)
 4894                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4895                })?;
 4896                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4897                    if excerpted_buffer == *buffer {
 4898                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4899                            let excerpt_range = excerpt_range.to_offset(buffer);
 4900                            buffer
 4901                                .edited_ranges_for_transaction::<usize>(transaction)
 4902                                .all(|range| {
 4903                                    excerpt_range.start <= range.start
 4904                                        && excerpt_range.end >= range.end
 4905                                })
 4906                        })?;
 4907
 4908                        if all_edits_within_excerpt {
 4909                            return Ok(());
 4910                        }
 4911                    }
 4912                }
 4913            }
 4914        } else {
 4915            return Ok(());
 4916        }
 4917
 4918        let mut ranges_to_highlight = Vec::new();
 4919        let excerpt_buffer = cx.new_model(|cx| {
 4920            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4921            for (buffer_handle, transaction) in &entries {
 4922                let buffer = buffer_handle.read(cx);
 4923                ranges_to_highlight.extend(
 4924                    multibuffer.push_excerpts_with_context_lines(
 4925                        buffer_handle.clone(),
 4926                        buffer
 4927                            .edited_ranges_for_transaction::<usize>(transaction)
 4928                            .collect(),
 4929                        DEFAULT_MULTIBUFFER_CONTEXT,
 4930                        cx,
 4931                    ),
 4932                );
 4933            }
 4934            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4935            multibuffer
 4936        })?;
 4937
 4938        workspace.update(&mut cx, |workspace, cx| {
 4939            let project = workspace.project().clone();
 4940            let editor =
 4941                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4942            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4943            editor.update(cx, |editor, cx| {
 4944                editor.highlight_background::<Self>(
 4945                    &ranges_to_highlight,
 4946                    |theme| theme.editor_highlighted_line_background,
 4947                    cx,
 4948                );
 4949            });
 4950        })?;
 4951
 4952        Ok(())
 4953    }
 4954
 4955    pub fn clear_code_action_providers(&mut self) {
 4956        self.code_action_providers.clear();
 4957        self.available_code_actions.take();
 4958    }
 4959
 4960    pub fn push_code_action_provider(
 4961        &mut self,
 4962        provider: Arc<dyn CodeActionProvider>,
 4963        cx: &mut ViewContext<Self>,
 4964    ) {
 4965        self.code_action_providers.push(provider);
 4966        self.refresh_code_actions(cx);
 4967    }
 4968
 4969    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4970        let buffer = self.buffer.read(cx);
 4971        let newest_selection = self.selections.newest_anchor().clone();
 4972        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4973        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4974        if start_buffer != end_buffer {
 4975            return None;
 4976        }
 4977
 4978        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4979            cx.background_executor()
 4980                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4981                .await;
 4982
 4983            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4984                let providers = this.code_action_providers.clone();
 4985                let tasks = this
 4986                    .code_action_providers
 4987                    .iter()
 4988                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4989                    .collect::<Vec<_>>();
 4990                (providers, tasks)
 4991            })?;
 4992
 4993            let mut actions = Vec::new();
 4994            for (provider, provider_actions) in
 4995                providers.into_iter().zip(future::join_all(tasks).await)
 4996            {
 4997                if let Some(provider_actions) = provider_actions.log_err() {
 4998                    actions.extend(provider_actions.into_iter().map(|action| {
 4999                        AvailableCodeAction {
 5000                            excerpt_id: newest_selection.start.excerpt_id,
 5001                            action,
 5002                            provider: provider.clone(),
 5003                        }
 5004                    }));
 5005                }
 5006            }
 5007
 5008            this.update(&mut cx, |this, cx| {
 5009                this.available_code_actions = if actions.is_empty() {
 5010                    None
 5011                } else {
 5012                    Some((
 5013                        Location {
 5014                            buffer: start_buffer,
 5015                            range: start..end,
 5016                        },
 5017                        actions.into(),
 5018                    ))
 5019                };
 5020                cx.notify();
 5021            })
 5022        }));
 5023        None
 5024    }
 5025
 5026    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5027        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5028            self.show_git_blame_inline = false;
 5029
 5030            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5031                cx.background_executor().timer(delay).await;
 5032
 5033                this.update(&mut cx, |this, cx| {
 5034                    this.show_git_blame_inline = true;
 5035                    cx.notify();
 5036                })
 5037                .log_err();
 5038            }));
 5039        }
 5040    }
 5041
 5042    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5043        if self.pending_rename.is_some() {
 5044            return None;
 5045        }
 5046
 5047        let provider = self.semantics_provider.clone()?;
 5048        let buffer = self.buffer.read(cx);
 5049        let newest_selection = self.selections.newest_anchor().clone();
 5050        let cursor_position = newest_selection.head();
 5051        let (cursor_buffer, cursor_buffer_position) =
 5052            buffer.text_anchor_for_position(cursor_position, cx)?;
 5053        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5054        if cursor_buffer != tail_buffer {
 5055            return None;
 5056        }
 5057
 5058        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5059            cx.background_executor()
 5060                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5061                .await;
 5062
 5063            let highlights = if let Some(highlights) = cx
 5064                .update(|cx| {
 5065                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5066                })
 5067                .ok()
 5068                .flatten()
 5069            {
 5070                highlights.await.log_err()
 5071            } else {
 5072                None
 5073            };
 5074
 5075            if let Some(highlights) = highlights {
 5076                this.update(&mut cx, |this, cx| {
 5077                    if this.pending_rename.is_some() {
 5078                        return;
 5079                    }
 5080
 5081                    let buffer_id = cursor_position.buffer_id;
 5082                    let buffer = this.buffer.read(cx);
 5083                    if !buffer
 5084                        .text_anchor_for_position(cursor_position, cx)
 5085                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5086                    {
 5087                        return;
 5088                    }
 5089
 5090                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5091                    let mut write_ranges = Vec::new();
 5092                    let mut read_ranges = Vec::new();
 5093                    for highlight in highlights {
 5094                        for (excerpt_id, excerpt_range) in
 5095                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5096                        {
 5097                            let start = highlight
 5098                                .range
 5099                                .start
 5100                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5101                            let end = highlight
 5102                                .range
 5103                                .end
 5104                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5105                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5106                                continue;
 5107                            }
 5108
 5109                            let range = Anchor {
 5110                                buffer_id,
 5111                                excerpt_id,
 5112                                text_anchor: start,
 5113                            }..Anchor {
 5114                                buffer_id,
 5115                                excerpt_id,
 5116                                text_anchor: end,
 5117                            };
 5118                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5119                                write_ranges.push(range);
 5120                            } else {
 5121                                read_ranges.push(range);
 5122                            }
 5123                        }
 5124                    }
 5125
 5126                    this.highlight_background::<DocumentHighlightRead>(
 5127                        &read_ranges,
 5128                        |theme| theme.editor_document_highlight_read_background,
 5129                        cx,
 5130                    );
 5131                    this.highlight_background::<DocumentHighlightWrite>(
 5132                        &write_ranges,
 5133                        |theme| theme.editor_document_highlight_write_background,
 5134                        cx,
 5135                    );
 5136                    cx.notify();
 5137                })
 5138                .log_err();
 5139            }
 5140        }));
 5141        None
 5142    }
 5143
 5144    pub fn refresh_inline_completion(
 5145        &mut self,
 5146        debounce: bool,
 5147        user_requested: bool,
 5148        cx: &mut ViewContext<Self>,
 5149    ) -> Option<()> {
 5150        let provider = self.inline_completion_provider()?;
 5151        let cursor = self.selections.newest_anchor().head();
 5152        let (buffer, cursor_buffer_position) =
 5153            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5154
 5155        if !user_requested
 5156            && (!self.enable_inline_completions
 5157                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5158        {
 5159            self.discard_inline_completion(false, cx);
 5160            return None;
 5161        }
 5162
 5163        self.update_visible_inline_completion(cx);
 5164        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5165        Some(())
 5166    }
 5167
 5168    fn cycle_inline_completion(
 5169        &mut self,
 5170        direction: Direction,
 5171        cx: &mut ViewContext<Self>,
 5172    ) -> Option<()> {
 5173        let provider = self.inline_completion_provider()?;
 5174        let cursor = self.selections.newest_anchor().head();
 5175        let (buffer, cursor_buffer_position) =
 5176            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5177        if !self.enable_inline_completions
 5178            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5179        {
 5180            return None;
 5181        }
 5182
 5183        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5184        self.update_visible_inline_completion(cx);
 5185
 5186        Some(())
 5187    }
 5188
 5189    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5190        if !self.has_active_inline_completion(cx) {
 5191            self.refresh_inline_completion(false, true, cx);
 5192            return;
 5193        }
 5194
 5195        self.update_visible_inline_completion(cx);
 5196    }
 5197
 5198    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5199        self.show_cursor_names(cx);
 5200    }
 5201
 5202    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5203        self.show_cursor_names = true;
 5204        cx.notify();
 5205        cx.spawn(|this, mut cx| async move {
 5206            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5207            this.update(&mut cx, |this, cx| {
 5208                this.show_cursor_names = false;
 5209                cx.notify()
 5210            })
 5211            .ok()
 5212        })
 5213        .detach();
 5214    }
 5215
 5216    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5217        if self.has_active_inline_completion(cx) {
 5218            self.cycle_inline_completion(Direction::Next, cx);
 5219        } else {
 5220            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5221            if is_copilot_disabled {
 5222                cx.propagate();
 5223            }
 5224        }
 5225    }
 5226
 5227    pub fn previous_inline_completion(
 5228        &mut self,
 5229        _: &PreviousInlineCompletion,
 5230        cx: &mut ViewContext<Self>,
 5231    ) {
 5232        if self.has_active_inline_completion(cx) {
 5233            self.cycle_inline_completion(Direction::Prev, cx);
 5234        } else {
 5235            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5236            if is_copilot_disabled {
 5237                cx.propagate();
 5238            }
 5239        }
 5240    }
 5241
 5242    pub fn accept_inline_completion(
 5243        &mut self,
 5244        _: &AcceptInlineCompletion,
 5245        cx: &mut ViewContext<Self>,
 5246    ) {
 5247        let Some(completion) = self.take_active_inline_completion(cx) else {
 5248            return;
 5249        };
 5250        if let Some(provider) = self.inline_completion_provider() {
 5251            provider.accept(cx);
 5252        }
 5253
 5254        cx.emit(EditorEvent::InputHandled {
 5255            utf16_range_to_replace: None,
 5256            text: completion.text.to_string().into(),
 5257        });
 5258
 5259        if let Some(range) = completion.delete_range {
 5260            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5261        }
 5262        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5263        self.refresh_inline_completion(true, true, cx);
 5264        cx.notify();
 5265    }
 5266
 5267    pub fn accept_partial_inline_completion(
 5268        &mut self,
 5269        _: &AcceptPartialInlineCompletion,
 5270        cx: &mut ViewContext<Self>,
 5271    ) {
 5272        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5273            if let Some(completion) = self.take_active_inline_completion(cx) {
 5274                let mut partial_completion = completion
 5275                    .text
 5276                    .chars()
 5277                    .by_ref()
 5278                    .take_while(|c| c.is_alphabetic())
 5279                    .collect::<String>();
 5280                if partial_completion.is_empty() {
 5281                    partial_completion = completion
 5282                        .text
 5283                        .chars()
 5284                        .by_ref()
 5285                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5286                        .collect::<String>();
 5287                }
 5288
 5289                cx.emit(EditorEvent::InputHandled {
 5290                    utf16_range_to_replace: None,
 5291                    text: partial_completion.clone().into(),
 5292                });
 5293
 5294                if let Some(range) = completion.delete_range {
 5295                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5296                }
 5297                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5298
 5299                self.refresh_inline_completion(true, true, cx);
 5300                cx.notify();
 5301            }
 5302        }
 5303    }
 5304
 5305    fn discard_inline_completion(
 5306        &mut self,
 5307        should_report_inline_completion_event: bool,
 5308        cx: &mut ViewContext<Self>,
 5309    ) -> bool {
 5310        if let Some(provider) = self.inline_completion_provider() {
 5311            provider.discard(should_report_inline_completion_event, cx);
 5312        }
 5313
 5314        self.take_active_inline_completion(cx).is_some()
 5315    }
 5316
 5317    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5318        if let Some(completion) = self.active_inline_completion.as_ref() {
 5319            let buffer = self.buffer.read(cx).read(cx);
 5320            completion.position.is_valid(&buffer)
 5321        } else {
 5322            false
 5323        }
 5324    }
 5325
 5326    fn take_active_inline_completion(
 5327        &mut self,
 5328        cx: &mut ViewContext<Self>,
 5329    ) -> Option<CompletionState> {
 5330        let completion = self.active_inline_completion.take()?;
 5331        let render_inlay_ids = completion.render_inlay_ids.clone();
 5332        self.display_map.update(cx, |map, cx| {
 5333            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5334        });
 5335        let buffer = self.buffer.read(cx).read(cx);
 5336
 5337        if completion.position.is_valid(&buffer) {
 5338            Some(completion)
 5339        } else {
 5340            None
 5341        }
 5342    }
 5343
 5344    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5345        let selection = self.selections.newest_anchor();
 5346        let cursor = selection.head();
 5347
 5348        let excerpt_id = cursor.excerpt_id;
 5349
 5350        if self.context_menu.read().is_none()
 5351            && self.completion_tasks.is_empty()
 5352            && selection.start == selection.end
 5353        {
 5354            if let Some(provider) = self.inline_completion_provider() {
 5355                if let Some((buffer, cursor_buffer_position)) =
 5356                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5357                {
 5358                    if let Some(proposal) =
 5359                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5360                    {
 5361                        let mut to_remove = Vec::new();
 5362                        if let Some(completion) = self.active_inline_completion.take() {
 5363                            to_remove.extend(completion.render_inlay_ids.iter());
 5364                        }
 5365
 5366                        let to_add = proposal
 5367                            .inlays
 5368                            .iter()
 5369                            .filter_map(|inlay| {
 5370                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5371                                let id = post_inc(&mut self.next_inlay_id);
 5372                                match inlay {
 5373                                    InlayProposal::Hint(position, hint) => {
 5374                                        let position =
 5375                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5376                                        Some(Inlay::hint(id, position, hint))
 5377                                    }
 5378                                    InlayProposal::Suggestion(position, text) => {
 5379                                        let position =
 5380                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5381                                        Some(Inlay::suggestion(id, position, text.clone()))
 5382                                    }
 5383                                }
 5384                            })
 5385                            .collect_vec();
 5386
 5387                        self.active_inline_completion = Some(CompletionState {
 5388                            position: cursor,
 5389                            text: proposal.text,
 5390                            delete_range: proposal.delete_range.and_then(|range| {
 5391                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5392                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5393                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5394                                Some(start?..end?)
 5395                            }),
 5396                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5397                        });
 5398
 5399                        self.display_map
 5400                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5401
 5402                        cx.notify();
 5403                        return;
 5404                    }
 5405                }
 5406            }
 5407        }
 5408
 5409        self.discard_inline_completion(false, cx);
 5410    }
 5411
 5412    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5413        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5414    }
 5415
 5416    fn render_code_actions_indicator(
 5417        &self,
 5418        _style: &EditorStyle,
 5419        row: DisplayRow,
 5420        is_active: bool,
 5421        cx: &mut ViewContext<Self>,
 5422    ) -> Option<IconButton> {
 5423        if self.available_code_actions.is_some() {
 5424            Some(
 5425                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5426                    .shape(ui::IconButtonShape::Square)
 5427                    .icon_size(IconSize::XSmall)
 5428                    .icon_color(Color::Muted)
 5429                    .selected(is_active)
 5430                    .tooltip({
 5431                        let focus_handle = self.focus_handle.clone();
 5432                        move |cx| {
 5433                            Tooltip::for_action_in(
 5434                                "Toggle Code Actions",
 5435                                &ToggleCodeActions {
 5436                                    deployed_from_indicator: None,
 5437                                },
 5438                                &focus_handle,
 5439                                cx,
 5440                            )
 5441                        }
 5442                    })
 5443                    .on_click(cx.listener(move |editor, _e, cx| {
 5444                        editor.focus(cx);
 5445                        editor.toggle_code_actions(
 5446                            &ToggleCodeActions {
 5447                                deployed_from_indicator: Some(row),
 5448                            },
 5449                            cx,
 5450                        );
 5451                    })),
 5452            )
 5453        } else {
 5454            None
 5455        }
 5456    }
 5457
 5458    fn clear_tasks(&mut self) {
 5459        self.tasks.clear()
 5460    }
 5461
 5462    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5463        if self.tasks.insert(key, value).is_some() {
 5464            // This case should hopefully be rare, but just in case...
 5465            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5466        }
 5467    }
 5468
 5469    fn build_tasks_context(
 5470        project: &Model<Project>,
 5471        buffer: &Model<Buffer>,
 5472        buffer_row: u32,
 5473        tasks: &Arc<RunnableTasks>,
 5474        cx: &mut ViewContext<Self>,
 5475    ) -> Task<Option<task::TaskContext>> {
 5476        let position = Point::new(buffer_row, tasks.column);
 5477        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5478        let location = Location {
 5479            buffer: buffer.clone(),
 5480            range: range_start..range_start,
 5481        };
 5482        // Fill in the environmental variables from the tree-sitter captures
 5483        let mut captured_task_variables = TaskVariables::default();
 5484        for (capture_name, value) in tasks.extra_variables.clone() {
 5485            captured_task_variables.insert(
 5486                task::VariableName::Custom(capture_name.into()),
 5487                value.clone(),
 5488            );
 5489        }
 5490        project.update(cx, |project, cx| {
 5491            project.task_store().update(cx, |task_store, cx| {
 5492                task_store.task_context_for_location(captured_task_variables, location, cx)
 5493            })
 5494        })
 5495    }
 5496
 5497    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5498        let Some((workspace, _)) = self.workspace.clone() else {
 5499            return;
 5500        };
 5501        let Some(project) = self.project.clone() else {
 5502            return;
 5503        };
 5504
 5505        // Try to find a closest, enclosing node using tree-sitter that has a
 5506        // task
 5507        let Some((buffer, buffer_row, tasks)) = self
 5508            .find_enclosing_node_task(cx)
 5509            // Or find the task that's closest in row-distance.
 5510            .or_else(|| self.find_closest_task(cx))
 5511        else {
 5512            return;
 5513        };
 5514
 5515        let reveal_strategy = action.reveal;
 5516        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5517        cx.spawn(|_, mut cx| async move {
 5518            let context = task_context.await?;
 5519            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5520
 5521            let resolved = resolved_task.resolved.as_mut()?;
 5522            resolved.reveal = reveal_strategy;
 5523
 5524            workspace
 5525                .update(&mut cx, |workspace, cx| {
 5526                    workspace::tasks::schedule_resolved_task(
 5527                        workspace,
 5528                        task_source_kind,
 5529                        resolved_task,
 5530                        false,
 5531                        cx,
 5532                    );
 5533                })
 5534                .ok()
 5535        })
 5536        .detach();
 5537    }
 5538
 5539    fn find_closest_task(
 5540        &mut self,
 5541        cx: &mut ViewContext<Self>,
 5542    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5543        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5544
 5545        let ((buffer_id, row), tasks) = self
 5546            .tasks
 5547            .iter()
 5548            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5549
 5550        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5551        let tasks = Arc::new(tasks.to_owned());
 5552        Some((buffer, *row, tasks))
 5553    }
 5554
 5555    fn find_enclosing_node_task(
 5556        &mut self,
 5557        cx: &mut ViewContext<Self>,
 5558    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5559        let snapshot = self.buffer.read(cx).snapshot(cx);
 5560        let offset = self.selections.newest::<usize>(cx).head();
 5561        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5562        let buffer_id = excerpt.buffer().remote_id();
 5563
 5564        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5565        let mut cursor = layer.node().walk();
 5566
 5567        while cursor.goto_first_child_for_byte(offset).is_some() {
 5568            if cursor.node().end_byte() == offset {
 5569                cursor.goto_next_sibling();
 5570            }
 5571        }
 5572
 5573        // Ascend to the smallest ancestor that contains the range and has a task.
 5574        loop {
 5575            let node = cursor.node();
 5576            let node_range = node.byte_range();
 5577            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5578
 5579            // Check if this node contains our offset
 5580            if node_range.start <= offset && node_range.end >= offset {
 5581                // If it contains offset, check for task
 5582                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5583                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5584                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5585                }
 5586            }
 5587
 5588            if !cursor.goto_parent() {
 5589                break;
 5590            }
 5591        }
 5592        None
 5593    }
 5594
 5595    fn render_run_indicator(
 5596        &self,
 5597        _style: &EditorStyle,
 5598        is_active: bool,
 5599        row: DisplayRow,
 5600        cx: &mut ViewContext<Self>,
 5601    ) -> IconButton {
 5602        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5603            .shape(ui::IconButtonShape::Square)
 5604            .icon_size(IconSize::XSmall)
 5605            .icon_color(Color::Muted)
 5606            .selected(is_active)
 5607            .on_click(cx.listener(move |editor, _e, cx| {
 5608                editor.focus(cx);
 5609                editor.toggle_code_actions(
 5610                    &ToggleCodeActions {
 5611                        deployed_from_indicator: Some(row),
 5612                    },
 5613                    cx,
 5614                );
 5615            }))
 5616    }
 5617
 5618    pub fn context_menu_visible(&self) -> bool {
 5619        self.context_menu
 5620            .read()
 5621            .as_ref()
 5622            .map_or(false, |menu| menu.visible())
 5623    }
 5624
 5625    fn render_context_menu(
 5626        &self,
 5627        cursor_position: DisplayPoint,
 5628        style: &EditorStyle,
 5629        max_height: Pixels,
 5630        cx: &mut ViewContext<Editor>,
 5631    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5632        self.context_menu.read().as_ref().map(|menu| {
 5633            menu.render(
 5634                cursor_position,
 5635                style,
 5636                max_height,
 5637                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5638                cx,
 5639            )
 5640        })
 5641    }
 5642
 5643    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5644        cx.notify();
 5645        self.completion_tasks.clear();
 5646        let context_menu = self.context_menu.write().take();
 5647        if context_menu.is_some() {
 5648            self.update_visible_inline_completion(cx);
 5649        }
 5650        context_menu
 5651    }
 5652
 5653    pub fn insert_snippet(
 5654        &mut self,
 5655        insertion_ranges: &[Range<usize>],
 5656        snippet: Snippet,
 5657        cx: &mut ViewContext<Self>,
 5658    ) -> Result<()> {
 5659        struct Tabstop<T> {
 5660            is_end_tabstop: bool,
 5661            ranges: Vec<Range<T>>,
 5662        }
 5663
 5664        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5665            let snippet_text: Arc<str> = snippet.text.clone().into();
 5666            buffer.edit(
 5667                insertion_ranges
 5668                    .iter()
 5669                    .cloned()
 5670                    .map(|range| (range, snippet_text.clone())),
 5671                Some(AutoindentMode::EachLine),
 5672                cx,
 5673            );
 5674
 5675            let snapshot = &*buffer.read(cx);
 5676            let snippet = &snippet;
 5677            snippet
 5678                .tabstops
 5679                .iter()
 5680                .map(|tabstop| {
 5681                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5682                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5683                    });
 5684                    let mut tabstop_ranges = tabstop
 5685                        .iter()
 5686                        .flat_map(|tabstop_range| {
 5687                            let mut delta = 0_isize;
 5688                            insertion_ranges.iter().map(move |insertion_range| {
 5689                                let insertion_start = insertion_range.start as isize + delta;
 5690                                delta +=
 5691                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5692
 5693                                let start = ((insertion_start + tabstop_range.start) as usize)
 5694                                    .min(snapshot.len());
 5695                                let end = ((insertion_start + tabstop_range.end) as usize)
 5696                                    .min(snapshot.len());
 5697                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5698                            })
 5699                        })
 5700                        .collect::<Vec<_>>();
 5701                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5702
 5703                    Tabstop {
 5704                        is_end_tabstop,
 5705                        ranges: tabstop_ranges,
 5706                    }
 5707                })
 5708                .collect::<Vec<_>>()
 5709        });
 5710        if let Some(tabstop) = tabstops.first() {
 5711            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5712                s.select_ranges(tabstop.ranges.iter().cloned());
 5713            });
 5714
 5715            // If we're already at the last tabstop and it's at the end of the snippet,
 5716            // we're done, we don't need to keep the state around.
 5717            if !tabstop.is_end_tabstop {
 5718                let ranges = tabstops
 5719                    .into_iter()
 5720                    .map(|tabstop| tabstop.ranges)
 5721                    .collect::<Vec<_>>();
 5722                self.snippet_stack.push(SnippetState {
 5723                    active_index: 0,
 5724                    ranges,
 5725                });
 5726            }
 5727
 5728            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5729            if self.autoclose_regions.is_empty() {
 5730                let snapshot = self.buffer.read(cx).snapshot(cx);
 5731                for selection in &mut self.selections.all::<Point>(cx) {
 5732                    let selection_head = selection.head();
 5733                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5734                        continue;
 5735                    };
 5736
 5737                    let mut bracket_pair = None;
 5738                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5739                    let prev_chars = snapshot
 5740                        .reversed_chars_at(selection_head)
 5741                        .collect::<String>();
 5742                    for (pair, enabled) in scope.brackets() {
 5743                        if enabled
 5744                            && pair.close
 5745                            && prev_chars.starts_with(pair.start.as_str())
 5746                            && next_chars.starts_with(pair.end.as_str())
 5747                        {
 5748                            bracket_pair = Some(pair.clone());
 5749                            break;
 5750                        }
 5751                    }
 5752                    if let Some(pair) = bracket_pair {
 5753                        let start = snapshot.anchor_after(selection_head);
 5754                        let end = snapshot.anchor_after(selection_head);
 5755                        self.autoclose_regions.push(AutocloseRegion {
 5756                            selection_id: selection.id,
 5757                            range: start..end,
 5758                            pair,
 5759                        });
 5760                    }
 5761                }
 5762            }
 5763        }
 5764        Ok(())
 5765    }
 5766
 5767    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5768        self.move_to_snippet_tabstop(Bias::Right, cx)
 5769    }
 5770
 5771    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5772        self.move_to_snippet_tabstop(Bias::Left, cx)
 5773    }
 5774
 5775    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5776        if let Some(mut snippet) = self.snippet_stack.pop() {
 5777            match bias {
 5778                Bias::Left => {
 5779                    if snippet.active_index > 0 {
 5780                        snippet.active_index -= 1;
 5781                    } else {
 5782                        self.snippet_stack.push(snippet);
 5783                        return false;
 5784                    }
 5785                }
 5786                Bias::Right => {
 5787                    if snippet.active_index + 1 < snippet.ranges.len() {
 5788                        snippet.active_index += 1;
 5789                    } else {
 5790                        self.snippet_stack.push(snippet);
 5791                        return false;
 5792                    }
 5793                }
 5794            }
 5795            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5796                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5797                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5798                });
 5799                // If snippet state is not at the last tabstop, push it back on the stack
 5800                if snippet.active_index + 1 < snippet.ranges.len() {
 5801                    self.snippet_stack.push(snippet);
 5802                }
 5803                return true;
 5804            }
 5805        }
 5806
 5807        false
 5808    }
 5809
 5810    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5811        self.transact(cx, |this, cx| {
 5812            this.select_all(&SelectAll, cx);
 5813            this.insert("", cx);
 5814        });
 5815    }
 5816
 5817    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5818        self.transact(cx, |this, cx| {
 5819            this.select_autoclose_pair(cx);
 5820            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5821            if !this.linked_edit_ranges.is_empty() {
 5822                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5823                let snapshot = this.buffer.read(cx).snapshot(cx);
 5824
 5825                for selection in selections.iter() {
 5826                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5827                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5828                    if selection_start.buffer_id != selection_end.buffer_id {
 5829                        continue;
 5830                    }
 5831                    if let Some(ranges) =
 5832                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5833                    {
 5834                        for (buffer, entries) in ranges {
 5835                            linked_ranges.entry(buffer).or_default().extend(entries);
 5836                        }
 5837                    }
 5838                }
 5839            }
 5840
 5841            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5842            if !this.selections.line_mode {
 5843                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5844                for selection in &mut selections {
 5845                    if selection.is_empty() {
 5846                        let old_head = selection.head();
 5847                        let mut new_head =
 5848                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5849                                .to_point(&display_map);
 5850                        if let Some((buffer, line_buffer_range)) = display_map
 5851                            .buffer_snapshot
 5852                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5853                        {
 5854                            let indent_size =
 5855                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5856                            let indent_len = match indent_size.kind {
 5857                                IndentKind::Space => {
 5858                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5859                                }
 5860                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5861                            };
 5862                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5863                                let indent_len = indent_len.get();
 5864                                new_head = cmp::min(
 5865                                    new_head,
 5866                                    MultiBufferPoint::new(
 5867                                        old_head.row,
 5868                                        ((old_head.column - 1) / indent_len) * indent_len,
 5869                                    ),
 5870                                );
 5871                            }
 5872                        }
 5873
 5874                        selection.set_head(new_head, SelectionGoal::None);
 5875                    }
 5876                }
 5877            }
 5878
 5879            this.signature_help_state.set_backspace_pressed(true);
 5880            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5881            this.insert("", cx);
 5882            let empty_str: Arc<str> = Arc::from("");
 5883            for (buffer, edits) in linked_ranges {
 5884                let snapshot = buffer.read(cx).snapshot();
 5885                use text::ToPoint as TP;
 5886
 5887                let edits = edits
 5888                    .into_iter()
 5889                    .map(|range| {
 5890                        let end_point = TP::to_point(&range.end, &snapshot);
 5891                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5892
 5893                        if end_point == start_point {
 5894                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5895                                .saturating_sub(1);
 5896                            start_point = TP::to_point(&offset, &snapshot);
 5897                        };
 5898
 5899                        (start_point..end_point, empty_str.clone())
 5900                    })
 5901                    .sorted_by_key(|(range, _)| range.start)
 5902                    .collect::<Vec<_>>();
 5903                buffer.update(cx, |this, cx| {
 5904                    this.edit(edits, None, cx);
 5905                })
 5906            }
 5907            this.refresh_inline_completion(true, false, cx);
 5908            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5909        });
 5910    }
 5911
 5912    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5913        self.transact(cx, |this, cx| {
 5914            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5915                let line_mode = s.line_mode;
 5916                s.move_with(|map, selection| {
 5917                    if selection.is_empty() && !line_mode {
 5918                        let cursor = movement::right(map, selection.head());
 5919                        selection.end = cursor;
 5920                        selection.reversed = true;
 5921                        selection.goal = SelectionGoal::None;
 5922                    }
 5923                })
 5924            });
 5925            this.insert("", cx);
 5926            this.refresh_inline_completion(true, false, cx);
 5927        });
 5928    }
 5929
 5930    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5931        if self.move_to_prev_snippet_tabstop(cx) {
 5932            return;
 5933        }
 5934
 5935        self.outdent(&Outdent, cx);
 5936    }
 5937
 5938    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5939        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5940            return;
 5941        }
 5942
 5943        let mut selections = self.selections.all_adjusted(cx);
 5944        let buffer = self.buffer.read(cx);
 5945        let snapshot = buffer.snapshot(cx);
 5946        let rows_iter = selections.iter().map(|s| s.head().row);
 5947        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5948
 5949        let mut edits = Vec::new();
 5950        let mut prev_edited_row = 0;
 5951        let mut row_delta = 0;
 5952        for selection in &mut selections {
 5953            if selection.start.row != prev_edited_row {
 5954                row_delta = 0;
 5955            }
 5956            prev_edited_row = selection.end.row;
 5957
 5958            // If the selection is non-empty, then increase the indentation of the selected lines.
 5959            if !selection.is_empty() {
 5960                row_delta =
 5961                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5962                continue;
 5963            }
 5964
 5965            // If the selection is empty and the cursor is in the leading whitespace before the
 5966            // suggested indentation, then auto-indent the line.
 5967            let cursor = selection.head();
 5968            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5969            if let Some(suggested_indent) =
 5970                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5971            {
 5972                if cursor.column < suggested_indent.len
 5973                    && cursor.column <= current_indent.len
 5974                    && current_indent.len <= suggested_indent.len
 5975                {
 5976                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5977                    selection.end = selection.start;
 5978                    if row_delta == 0 {
 5979                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5980                            cursor.row,
 5981                            current_indent,
 5982                            suggested_indent,
 5983                        ));
 5984                        row_delta = suggested_indent.len - current_indent.len;
 5985                    }
 5986                    continue;
 5987                }
 5988            }
 5989
 5990            // Otherwise, insert a hard or soft tab.
 5991            let settings = buffer.settings_at(cursor, cx);
 5992            let tab_size = if settings.hard_tabs {
 5993                IndentSize::tab()
 5994            } else {
 5995                let tab_size = settings.tab_size.get();
 5996                let char_column = snapshot
 5997                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5998                    .flat_map(str::chars)
 5999                    .count()
 6000                    + row_delta as usize;
 6001                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6002                IndentSize::spaces(chars_to_next_tab_stop)
 6003            };
 6004            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6005            selection.end = selection.start;
 6006            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6007            row_delta += tab_size.len;
 6008        }
 6009
 6010        self.transact(cx, |this, cx| {
 6011            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6012            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6013            this.refresh_inline_completion(true, false, cx);
 6014        });
 6015    }
 6016
 6017    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6018        if self.read_only(cx) {
 6019            return;
 6020        }
 6021        let mut selections = self.selections.all::<Point>(cx);
 6022        let mut prev_edited_row = 0;
 6023        let mut row_delta = 0;
 6024        let mut edits = Vec::new();
 6025        let buffer = self.buffer.read(cx);
 6026        let snapshot = buffer.snapshot(cx);
 6027        for selection in &mut selections {
 6028            if selection.start.row != prev_edited_row {
 6029                row_delta = 0;
 6030            }
 6031            prev_edited_row = selection.end.row;
 6032
 6033            row_delta =
 6034                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6035        }
 6036
 6037        self.transact(cx, |this, cx| {
 6038            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6039            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6040        });
 6041    }
 6042
 6043    fn indent_selection(
 6044        buffer: &MultiBuffer,
 6045        snapshot: &MultiBufferSnapshot,
 6046        selection: &mut Selection<Point>,
 6047        edits: &mut Vec<(Range<Point>, String)>,
 6048        delta_for_start_row: u32,
 6049        cx: &AppContext,
 6050    ) -> u32 {
 6051        let settings = buffer.settings_at(selection.start, cx);
 6052        let tab_size = settings.tab_size.get();
 6053        let indent_kind = if settings.hard_tabs {
 6054            IndentKind::Tab
 6055        } else {
 6056            IndentKind::Space
 6057        };
 6058        let mut start_row = selection.start.row;
 6059        let mut end_row = selection.end.row + 1;
 6060
 6061        // If a selection ends at the beginning of a line, don't indent
 6062        // that last line.
 6063        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6064            end_row -= 1;
 6065        }
 6066
 6067        // Avoid re-indenting a row that has already been indented by a
 6068        // previous selection, but still update this selection's column
 6069        // to reflect that indentation.
 6070        if delta_for_start_row > 0 {
 6071            start_row += 1;
 6072            selection.start.column += delta_for_start_row;
 6073            if selection.end.row == selection.start.row {
 6074                selection.end.column += delta_for_start_row;
 6075            }
 6076        }
 6077
 6078        let mut delta_for_end_row = 0;
 6079        let has_multiple_rows = start_row + 1 != end_row;
 6080        for row in start_row..end_row {
 6081            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6082            let indent_delta = match (current_indent.kind, indent_kind) {
 6083                (IndentKind::Space, IndentKind::Space) => {
 6084                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6085                    IndentSize::spaces(columns_to_next_tab_stop)
 6086                }
 6087                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6088                (_, IndentKind::Tab) => IndentSize::tab(),
 6089            };
 6090
 6091            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6092                0
 6093            } else {
 6094                selection.start.column
 6095            };
 6096            let row_start = Point::new(row, start);
 6097            edits.push((
 6098                row_start..row_start,
 6099                indent_delta.chars().collect::<String>(),
 6100            ));
 6101
 6102            // Update this selection's endpoints to reflect the indentation.
 6103            if row == selection.start.row {
 6104                selection.start.column += indent_delta.len;
 6105            }
 6106            if row == selection.end.row {
 6107                selection.end.column += indent_delta.len;
 6108                delta_for_end_row = indent_delta.len;
 6109            }
 6110        }
 6111
 6112        if selection.start.row == selection.end.row {
 6113            delta_for_start_row + delta_for_end_row
 6114        } else {
 6115            delta_for_end_row
 6116        }
 6117    }
 6118
 6119    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6120        if self.read_only(cx) {
 6121            return;
 6122        }
 6123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6124        let selections = self.selections.all::<Point>(cx);
 6125        let mut deletion_ranges = Vec::new();
 6126        let mut last_outdent = None;
 6127        {
 6128            let buffer = self.buffer.read(cx);
 6129            let snapshot = buffer.snapshot(cx);
 6130            for selection in &selections {
 6131                let settings = buffer.settings_at(selection.start, cx);
 6132                let tab_size = settings.tab_size.get();
 6133                let mut rows = selection.spanned_rows(false, &display_map);
 6134
 6135                // Avoid re-outdenting a row that has already been outdented by a
 6136                // previous selection.
 6137                if let Some(last_row) = last_outdent {
 6138                    if last_row == rows.start {
 6139                        rows.start = rows.start.next_row();
 6140                    }
 6141                }
 6142                let has_multiple_rows = rows.len() > 1;
 6143                for row in rows.iter_rows() {
 6144                    let indent_size = snapshot.indent_size_for_line(row);
 6145                    if indent_size.len > 0 {
 6146                        let deletion_len = match indent_size.kind {
 6147                            IndentKind::Space => {
 6148                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6149                                if columns_to_prev_tab_stop == 0 {
 6150                                    tab_size
 6151                                } else {
 6152                                    columns_to_prev_tab_stop
 6153                                }
 6154                            }
 6155                            IndentKind::Tab => 1,
 6156                        };
 6157                        let start = if has_multiple_rows
 6158                            || deletion_len > selection.start.column
 6159                            || indent_size.len < selection.start.column
 6160                        {
 6161                            0
 6162                        } else {
 6163                            selection.start.column - deletion_len
 6164                        };
 6165                        deletion_ranges.push(
 6166                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6167                        );
 6168                        last_outdent = Some(row);
 6169                    }
 6170                }
 6171            }
 6172        }
 6173
 6174        self.transact(cx, |this, cx| {
 6175            this.buffer.update(cx, |buffer, cx| {
 6176                let empty_str: Arc<str> = Arc::default();
 6177                buffer.edit(
 6178                    deletion_ranges
 6179                        .into_iter()
 6180                        .map(|range| (range, empty_str.clone())),
 6181                    None,
 6182                    cx,
 6183                );
 6184            });
 6185            let selections = this.selections.all::<usize>(cx);
 6186            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6187        });
 6188    }
 6189
 6190    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6192        let selections = self.selections.all::<Point>(cx);
 6193
 6194        let mut new_cursors = Vec::new();
 6195        let mut edit_ranges = Vec::new();
 6196        let mut selections = selections.iter().peekable();
 6197        while let Some(selection) = selections.next() {
 6198            let mut rows = selection.spanned_rows(false, &display_map);
 6199            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6200
 6201            // Accumulate contiguous regions of rows that we want to delete.
 6202            while let Some(next_selection) = selections.peek() {
 6203                let next_rows = next_selection.spanned_rows(false, &display_map);
 6204                if next_rows.start <= rows.end {
 6205                    rows.end = next_rows.end;
 6206                    selections.next().unwrap();
 6207                } else {
 6208                    break;
 6209                }
 6210            }
 6211
 6212            let buffer = &display_map.buffer_snapshot;
 6213            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6214            let edit_end;
 6215            let cursor_buffer_row;
 6216            if buffer.max_point().row >= rows.end.0 {
 6217                // If there's a line after the range, delete the \n from the end of the row range
 6218                // and position the cursor on the next line.
 6219                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6220                cursor_buffer_row = rows.end;
 6221            } else {
 6222                // If there isn't a line after the range, delete the \n from the line before the
 6223                // start of the row range and position the cursor there.
 6224                edit_start = edit_start.saturating_sub(1);
 6225                edit_end = buffer.len();
 6226                cursor_buffer_row = rows.start.previous_row();
 6227            }
 6228
 6229            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6230            *cursor.column_mut() =
 6231                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6232
 6233            new_cursors.push((
 6234                selection.id,
 6235                buffer.anchor_after(cursor.to_point(&display_map)),
 6236            ));
 6237            edit_ranges.push(edit_start..edit_end);
 6238        }
 6239
 6240        self.transact(cx, |this, cx| {
 6241            let buffer = this.buffer.update(cx, |buffer, cx| {
 6242                let empty_str: Arc<str> = Arc::default();
 6243                buffer.edit(
 6244                    edit_ranges
 6245                        .into_iter()
 6246                        .map(|range| (range, empty_str.clone())),
 6247                    None,
 6248                    cx,
 6249                );
 6250                buffer.snapshot(cx)
 6251            });
 6252            let new_selections = new_cursors
 6253                .into_iter()
 6254                .map(|(id, cursor)| {
 6255                    let cursor = cursor.to_point(&buffer);
 6256                    Selection {
 6257                        id,
 6258                        start: cursor,
 6259                        end: cursor,
 6260                        reversed: false,
 6261                        goal: SelectionGoal::None,
 6262                    }
 6263                })
 6264                .collect();
 6265
 6266            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6267                s.select(new_selections);
 6268            });
 6269        });
 6270    }
 6271
 6272    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6273        if self.read_only(cx) {
 6274            return;
 6275        }
 6276        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6277        for selection in self.selections.all::<Point>(cx) {
 6278            let start = MultiBufferRow(selection.start.row);
 6279            let end = if selection.start.row == selection.end.row {
 6280                MultiBufferRow(selection.start.row + 1)
 6281            } else {
 6282                MultiBufferRow(selection.end.row)
 6283            };
 6284
 6285            if let Some(last_row_range) = row_ranges.last_mut() {
 6286                if start <= last_row_range.end {
 6287                    last_row_range.end = end;
 6288                    continue;
 6289                }
 6290            }
 6291            row_ranges.push(start..end);
 6292        }
 6293
 6294        let snapshot = self.buffer.read(cx).snapshot(cx);
 6295        let mut cursor_positions = Vec::new();
 6296        for row_range in &row_ranges {
 6297            let anchor = snapshot.anchor_before(Point::new(
 6298                row_range.end.previous_row().0,
 6299                snapshot.line_len(row_range.end.previous_row()),
 6300            ));
 6301            cursor_positions.push(anchor..anchor);
 6302        }
 6303
 6304        self.transact(cx, |this, cx| {
 6305            for row_range in row_ranges.into_iter().rev() {
 6306                for row in row_range.iter_rows().rev() {
 6307                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6308                    let next_line_row = row.next_row();
 6309                    let indent = snapshot.indent_size_for_line(next_line_row);
 6310                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6311
 6312                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6313                        " "
 6314                    } else {
 6315                        ""
 6316                    };
 6317
 6318                    this.buffer.update(cx, |buffer, cx| {
 6319                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6320                    });
 6321                }
 6322            }
 6323
 6324            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6325                s.select_anchor_ranges(cursor_positions)
 6326            });
 6327        });
 6328    }
 6329
 6330    pub fn sort_lines_case_sensitive(
 6331        &mut self,
 6332        _: &SortLinesCaseSensitive,
 6333        cx: &mut ViewContext<Self>,
 6334    ) {
 6335        self.manipulate_lines(cx, |lines| lines.sort())
 6336    }
 6337
 6338    pub fn sort_lines_case_insensitive(
 6339        &mut self,
 6340        _: &SortLinesCaseInsensitive,
 6341        cx: &mut ViewContext<Self>,
 6342    ) {
 6343        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6344    }
 6345
 6346    pub fn unique_lines_case_insensitive(
 6347        &mut self,
 6348        _: &UniqueLinesCaseInsensitive,
 6349        cx: &mut ViewContext<Self>,
 6350    ) {
 6351        self.manipulate_lines(cx, |lines| {
 6352            let mut seen = HashSet::default();
 6353            lines.retain(|line| seen.insert(line.to_lowercase()));
 6354        })
 6355    }
 6356
 6357    pub fn unique_lines_case_sensitive(
 6358        &mut self,
 6359        _: &UniqueLinesCaseSensitive,
 6360        cx: &mut ViewContext<Self>,
 6361    ) {
 6362        self.manipulate_lines(cx, |lines| {
 6363            let mut seen = HashSet::default();
 6364            lines.retain(|line| seen.insert(*line));
 6365        })
 6366    }
 6367
 6368    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6369        let mut revert_changes = HashMap::default();
 6370        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6371        for hunk in hunks_for_rows(
 6372            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6373            &multi_buffer_snapshot,
 6374        ) {
 6375            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6376        }
 6377        if !revert_changes.is_empty() {
 6378            self.transact(cx, |editor, cx| {
 6379                editor.revert(revert_changes, cx);
 6380            });
 6381        }
 6382    }
 6383
 6384    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6385        let Some(project) = self.project.clone() else {
 6386            return;
 6387        };
 6388        self.reload(project, cx).detach_and_notify_err(cx);
 6389    }
 6390
 6391    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6392        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6393        if !revert_changes.is_empty() {
 6394            self.transact(cx, |editor, cx| {
 6395                editor.revert(revert_changes, cx);
 6396            });
 6397        }
 6398    }
 6399
 6400    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6401        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6402            let project_path = buffer.read(cx).project_path(cx)?;
 6403            let project = self.project.as_ref()?.read(cx);
 6404            let entry = project.entry_for_path(&project_path, cx)?;
 6405            let parent = match &entry.canonical_path {
 6406                Some(canonical_path) => canonical_path.to_path_buf(),
 6407                None => project.absolute_path(&project_path, cx)?,
 6408            }
 6409            .parent()?
 6410            .to_path_buf();
 6411            Some(parent)
 6412        }) {
 6413            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6414        }
 6415    }
 6416
 6417    fn gather_revert_changes(
 6418        &mut self,
 6419        selections: &[Selection<Anchor>],
 6420        cx: &mut ViewContext<'_, Editor>,
 6421    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6422        let mut revert_changes = HashMap::default();
 6423        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6424        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6425            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6426        }
 6427        revert_changes
 6428    }
 6429
 6430    pub fn prepare_revert_change(
 6431        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6432        multi_buffer: &Model<MultiBuffer>,
 6433        hunk: &MultiBufferDiffHunk,
 6434        cx: &AppContext,
 6435    ) -> Option<()> {
 6436        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6437        let buffer = buffer.read(cx);
 6438        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6439        let buffer_snapshot = buffer.snapshot();
 6440        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6441        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6442            probe
 6443                .0
 6444                .start
 6445                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6446                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6447        }) {
 6448            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6449            Some(())
 6450        } else {
 6451            None
 6452        }
 6453    }
 6454
 6455    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6456        self.manipulate_lines(cx, |lines| lines.reverse())
 6457    }
 6458
 6459    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6460        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6461    }
 6462
 6463    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6464    where
 6465        Fn: FnMut(&mut Vec<&str>),
 6466    {
 6467        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6468        let buffer = self.buffer.read(cx).snapshot(cx);
 6469
 6470        let mut edits = Vec::new();
 6471
 6472        let selections = self.selections.all::<Point>(cx);
 6473        let mut selections = selections.iter().peekable();
 6474        let mut contiguous_row_selections = Vec::new();
 6475        let mut new_selections = Vec::new();
 6476        let mut added_lines = 0;
 6477        let mut removed_lines = 0;
 6478
 6479        while let Some(selection) = selections.next() {
 6480            let (start_row, end_row) = consume_contiguous_rows(
 6481                &mut contiguous_row_selections,
 6482                selection,
 6483                &display_map,
 6484                &mut selections,
 6485            );
 6486
 6487            let start_point = Point::new(start_row.0, 0);
 6488            let end_point = Point::new(
 6489                end_row.previous_row().0,
 6490                buffer.line_len(end_row.previous_row()),
 6491            );
 6492            let text = buffer
 6493                .text_for_range(start_point..end_point)
 6494                .collect::<String>();
 6495
 6496            let mut lines = text.split('\n').collect_vec();
 6497
 6498            let lines_before = lines.len();
 6499            callback(&mut lines);
 6500            let lines_after = lines.len();
 6501
 6502            edits.push((start_point..end_point, lines.join("\n")));
 6503
 6504            // Selections must change based on added and removed line count
 6505            let start_row =
 6506                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6507            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6508            new_selections.push(Selection {
 6509                id: selection.id,
 6510                start: start_row,
 6511                end: end_row,
 6512                goal: SelectionGoal::None,
 6513                reversed: selection.reversed,
 6514            });
 6515
 6516            if lines_after > lines_before {
 6517                added_lines += lines_after - lines_before;
 6518            } else if lines_before > lines_after {
 6519                removed_lines += lines_before - lines_after;
 6520            }
 6521        }
 6522
 6523        self.transact(cx, |this, cx| {
 6524            let buffer = this.buffer.update(cx, |buffer, cx| {
 6525                buffer.edit(edits, None, cx);
 6526                buffer.snapshot(cx)
 6527            });
 6528
 6529            // Recalculate offsets on newly edited buffer
 6530            let new_selections = new_selections
 6531                .iter()
 6532                .map(|s| {
 6533                    let start_point = Point::new(s.start.0, 0);
 6534                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6535                    Selection {
 6536                        id: s.id,
 6537                        start: buffer.point_to_offset(start_point),
 6538                        end: buffer.point_to_offset(end_point),
 6539                        goal: s.goal,
 6540                        reversed: s.reversed,
 6541                    }
 6542                })
 6543                .collect();
 6544
 6545            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6546                s.select(new_selections);
 6547            });
 6548
 6549            this.request_autoscroll(Autoscroll::fit(), cx);
 6550        });
 6551    }
 6552
 6553    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6554        self.manipulate_text(cx, |text| text.to_uppercase())
 6555    }
 6556
 6557    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6558        self.manipulate_text(cx, |text| text.to_lowercase())
 6559    }
 6560
 6561    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6562        self.manipulate_text(cx, |text| {
 6563            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6564            // https://github.com/rutrum/convert-case/issues/16
 6565            text.split('\n')
 6566                .map(|line| line.to_case(Case::Title))
 6567                .join("\n")
 6568        })
 6569    }
 6570
 6571    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6572        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6573    }
 6574
 6575    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6576        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6577    }
 6578
 6579    pub fn convert_to_upper_camel_case(
 6580        &mut self,
 6581        _: &ConvertToUpperCamelCase,
 6582        cx: &mut ViewContext<Self>,
 6583    ) {
 6584        self.manipulate_text(cx, |text| {
 6585            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6586            // https://github.com/rutrum/convert-case/issues/16
 6587            text.split('\n')
 6588                .map(|line| line.to_case(Case::UpperCamel))
 6589                .join("\n")
 6590        })
 6591    }
 6592
 6593    pub fn convert_to_lower_camel_case(
 6594        &mut self,
 6595        _: &ConvertToLowerCamelCase,
 6596        cx: &mut ViewContext<Self>,
 6597    ) {
 6598        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6599    }
 6600
 6601    pub fn convert_to_opposite_case(
 6602        &mut self,
 6603        _: &ConvertToOppositeCase,
 6604        cx: &mut ViewContext<Self>,
 6605    ) {
 6606        self.manipulate_text(cx, |text| {
 6607            text.chars()
 6608                .fold(String::with_capacity(text.len()), |mut t, c| {
 6609                    if c.is_uppercase() {
 6610                        t.extend(c.to_lowercase());
 6611                    } else {
 6612                        t.extend(c.to_uppercase());
 6613                    }
 6614                    t
 6615                })
 6616        })
 6617    }
 6618
 6619    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6620    where
 6621        Fn: FnMut(&str) -> String,
 6622    {
 6623        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6624        let buffer = self.buffer.read(cx).snapshot(cx);
 6625
 6626        let mut new_selections = Vec::new();
 6627        let mut edits = Vec::new();
 6628        let mut selection_adjustment = 0i32;
 6629
 6630        for selection in self.selections.all::<usize>(cx) {
 6631            let selection_is_empty = selection.is_empty();
 6632
 6633            let (start, end) = if selection_is_empty {
 6634                let word_range = movement::surrounding_word(
 6635                    &display_map,
 6636                    selection.start.to_display_point(&display_map),
 6637                );
 6638                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6639                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6640                (start, end)
 6641            } else {
 6642                (selection.start, selection.end)
 6643            };
 6644
 6645            let text = buffer.text_for_range(start..end).collect::<String>();
 6646            let old_length = text.len() as i32;
 6647            let text = callback(&text);
 6648
 6649            new_selections.push(Selection {
 6650                start: (start as i32 - selection_adjustment) as usize,
 6651                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6652                goal: SelectionGoal::None,
 6653                ..selection
 6654            });
 6655
 6656            selection_adjustment += old_length - text.len() as i32;
 6657
 6658            edits.push((start..end, text));
 6659        }
 6660
 6661        self.transact(cx, |this, cx| {
 6662            this.buffer.update(cx, |buffer, cx| {
 6663                buffer.edit(edits, None, cx);
 6664            });
 6665
 6666            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6667                s.select(new_selections);
 6668            });
 6669
 6670            this.request_autoscroll(Autoscroll::fit(), cx);
 6671        });
 6672    }
 6673
 6674    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6675        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6676        let buffer = &display_map.buffer_snapshot;
 6677        let selections = self.selections.all::<Point>(cx);
 6678
 6679        let mut edits = Vec::new();
 6680        let mut selections_iter = selections.iter().peekable();
 6681        while let Some(selection) = selections_iter.next() {
 6682            // Avoid duplicating the same lines twice.
 6683            let mut rows = selection.spanned_rows(false, &display_map);
 6684
 6685            while let Some(next_selection) = selections_iter.peek() {
 6686                let next_rows = next_selection.spanned_rows(false, &display_map);
 6687                if next_rows.start < rows.end {
 6688                    rows.end = next_rows.end;
 6689                    selections_iter.next().unwrap();
 6690                } else {
 6691                    break;
 6692                }
 6693            }
 6694
 6695            // Copy the text from the selected row region and splice it either at the start
 6696            // or end of the region.
 6697            let start = Point::new(rows.start.0, 0);
 6698            let end = Point::new(
 6699                rows.end.previous_row().0,
 6700                buffer.line_len(rows.end.previous_row()),
 6701            );
 6702            let text = buffer
 6703                .text_for_range(start..end)
 6704                .chain(Some("\n"))
 6705                .collect::<String>();
 6706            let insert_location = if upwards {
 6707                Point::new(rows.end.0, 0)
 6708            } else {
 6709                start
 6710            };
 6711            edits.push((insert_location..insert_location, text));
 6712        }
 6713
 6714        self.transact(cx, |this, cx| {
 6715            this.buffer.update(cx, |buffer, cx| {
 6716                buffer.edit(edits, None, cx);
 6717            });
 6718
 6719            this.request_autoscroll(Autoscroll::fit(), cx);
 6720        });
 6721    }
 6722
 6723    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6724        self.duplicate_line(true, cx);
 6725    }
 6726
 6727    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6728        self.duplicate_line(false, cx);
 6729    }
 6730
 6731    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6732        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6733        let buffer = self.buffer.read(cx).snapshot(cx);
 6734
 6735        let mut edits = Vec::new();
 6736        let mut unfold_ranges = Vec::new();
 6737        let mut refold_ranges = Vec::new();
 6738
 6739        let selections = self.selections.all::<Point>(cx);
 6740        let mut selections = selections.iter().peekable();
 6741        let mut contiguous_row_selections = Vec::new();
 6742        let mut new_selections = Vec::new();
 6743
 6744        while let Some(selection) = selections.next() {
 6745            // Find all the selections that span a contiguous row range
 6746            let (start_row, end_row) = consume_contiguous_rows(
 6747                &mut contiguous_row_selections,
 6748                selection,
 6749                &display_map,
 6750                &mut selections,
 6751            );
 6752
 6753            // Move the text spanned by the row range to be before the line preceding the row range
 6754            if start_row.0 > 0 {
 6755                let range_to_move = Point::new(
 6756                    start_row.previous_row().0,
 6757                    buffer.line_len(start_row.previous_row()),
 6758                )
 6759                    ..Point::new(
 6760                        end_row.previous_row().0,
 6761                        buffer.line_len(end_row.previous_row()),
 6762                    );
 6763                let insertion_point = display_map
 6764                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6765                    .0;
 6766
 6767                // Don't move lines across excerpts
 6768                if buffer
 6769                    .excerpt_boundaries_in_range((
 6770                        Bound::Excluded(insertion_point),
 6771                        Bound::Included(range_to_move.end),
 6772                    ))
 6773                    .next()
 6774                    .is_none()
 6775                {
 6776                    let text = buffer
 6777                        .text_for_range(range_to_move.clone())
 6778                        .flat_map(|s| s.chars())
 6779                        .skip(1)
 6780                        .chain(['\n'])
 6781                        .collect::<String>();
 6782
 6783                    edits.push((
 6784                        buffer.anchor_after(range_to_move.start)
 6785                            ..buffer.anchor_before(range_to_move.end),
 6786                        String::new(),
 6787                    ));
 6788                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6789                    edits.push((insertion_anchor..insertion_anchor, text));
 6790
 6791                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6792
 6793                    // Move selections up
 6794                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6795                        |mut selection| {
 6796                            selection.start.row -= row_delta;
 6797                            selection.end.row -= row_delta;
 6798                            selection
 6799                        },
 6800                    ));
 6801
 6802                    // Move folds up
 6803                    unfold_ranges.push(range_to_move.clone());
 6804                    for fold in display_map.folds_in_range(
 6805                        buffer.anchor_before(range_to_move.start)
 6806                            ..buffer.anchor_after(range_to_move.end),
 6807                    ) {
 6808                        let mut start = fold.range.start.to_point(&buffer);
 6809                        let mut end = fold.range.end.to_point(&buffer);
 6810                        start.row -= row_delta;
 6811                        end.row -= row_delta;
 6812                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6813                    }
 6814                }
 6815            }
 6816
 6817            // If we didn't move line(s), preserve the existing selections
 6818            new_selections.append(&mut contiguous_row_selections);
 6819        }
 6820
 6821        self.transact(cx, |this, cx| {
 6822            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6823            this.buffer.update(cx, |buffer, cx| {
 6824                for (range, text) in edits {
 6825                    buffer.edit([(range, text)], None, cx);
 6826                }
 6827            });
 6828            this.fold_ranges(refold_ranges, true, cx);
 6829            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6830                s.select(new_selections);
 6831            })
 6832        });
 6833    }
 6834
 6835    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6836        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6837        let buffer = self.buffer.read(cx).snapshot(cx);
 6838
 6839        let mut edits = Vec::new();
 6840        let mut unfold_ranges = Vec::new();
 6841        let mut refold_ranges = Vec::new();
 6842
 6843        let selections = self.selections.all::<Point>(cx);
 6844        let mut selections = selections.iter().peekable();
 6845        let mut contiguous_row_selections = Vec::new();
 6846        let mut new_selections = Vec::new();
 6847
 6848        while let Some(selection) = selections.next() {
 6849            // Find all the selections that span a contiguous row range
 6850            let (start_row, end_row) = consume_contiguous_rows(
 6851                &mut contiguous_row_selections,
 6852                selection,
 6853                &display_map,
 6854                &mut selections,
 6855            );
 6856
 6857            // Move the text spanned by the row range to be after the last line of the row range
 6858            if end_row.0 <= buffer.max_point().row {
 6859                let range_to_move =
 6860                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6861                let insertion_point = display_map
 6862                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6863                    .0;
 6864
 6865                // Don't move lines across excerpt boundaries
 6866                if buffer
 6867                    .excerpt_boundaries_in_range((
 6868                        Bound::Excluded(range_to_move.start),
 6869                        Bound::Included(insertion_point),
 6870                    ))
 6871                    .next()
 6872                    .is_none()
 6873                {
 6874                    let mut text = String::from("\n");
 6875                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6876                    text.pop(); // Drop trailing newline
 6877                    edits.push((
 6878                        buffer.anchor_after(range_to_move.start)
 6879                            ..buffer.anchor_before(range_to_move.end),
 6880                        String::new(),
 6881                    ));
 6882                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6883                    edits.push((insertion_anchor..insertion_anchor, text));
 6884
 6885                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6886
 6887                    // Move selections down
 6888                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6889                        |mut selection| {
 6890                            selection.start.row += row_delta;
 6891                            selection.end.row += row_delta;
 6892                            selection
 6893                        },
 6894                    ));
 6895
 6896                    // Move folds down
 6897                    unfold_ranges.push(range_to_move.clone());
 6898                    for fold in display_map.folds_in_range(
 6899                        buffer.anchor_before(range_to_move.start)
 6900                            ..buffer.anchor_after(range_to_move.end),
 6901                    ) {
 6902                        let mut start = fold.range.start.to_point(&buffer);
 6903                        let mut end = fold.range.end.to_point(&buffer);
 6904                        start.row += row_delta;
 6905                        end.row += row_delta;
 6906                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6907                    }
 6908                }
 6909            }
 6910
 6911            // If we didn't move line(s), preserve the existing selections
 6912            new_selections.append(&mut contiguous_row_selections);
 6913        }
 6914
 6915        self.transact(cx, |this, cx| {
 6916            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6917            this.buffer.update(cx, |buffer, cx| {
 6918                for (range, text) in edits {
 6919                    buffer.edit([(range, text)], None, cx);
 6920                }
 6921            });
 6922            this.fold_ranges(refold_ranges, true, cx);
 6923            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6924        });
 6925    }
 6926
 6927    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6928        let text_layout_details = &self.text_layout_details(cx);
 6929        self.transact(cx, |this, cx| {
 6930            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6931                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6932                let line_mode = s.line_mode;
 6933                s.move_with(|display_map, selection| {
 6934                    if !selection.is_empty() || line_mode {
 6935                        return;
 6936                    }
 6937
 6938                    let mut head = selection.head();
 6939                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6940                    if head.column() == display_map.line_len(head.row()) {
 6941                        transpose_offset = display_map
 6942                            .buffer_snapshot
 6943                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6944                    }
 6945
 6946                    if transpose_offset == 0 {
 6947                        return;
 6948                    }
 6949
 6950                    *head.column_mut() += 1;
 6951                    head = display_map.clip_point(head, Bias::Right);
 6952                    let goal = SelectionGoal::HorizontalPosition(
 6953                        display_map
 6954                            .x_for_display_point(head, text_layout_details)
 6955                            .into(),
 6956                    );
 6957                    selection.collapse_to(head, goal);
 6958
 6959                    let transpose_start = display_map
 6960                        .buffer_snapshot
 6961                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6962                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6963                        let transpose_end = display_map
 6964                            .buffer_snapshot
 6965                            .clip_offset(transpose_offset + 1, Bias::Right);
 6966                        if let Some(ch) =
 6967                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6968                        {
 6969                            edits.push((transpose_start..transpose_offset, String::new()));
 6970                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6971                        }
 6972                    }
 6973                });
 6974                edits
 6975            });
 6976            this.buffer
 6977                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6978            let selections = this.selections.all::<usize>(cx);
 6979            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6980                s.select(selections);
 6981            });
 6982        });
 6983    }
 6984
 6985    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6986        self.rewrap_impl(true, cx)
 6987    }
 6988
 6989    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6990        let buffer = self.buffer.read(cx).snapshot(cx);
 6991        let selections = self.selections.all::<Point>(cx);
 6992        let mut selections = selections.iter().peekable();
 6993
 6994        let mut edits = Vec::new();
 6995        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6996
 6997        while let Some(selection) = selections.next() {
 6998            let mut start_row = selection.start.row;
 6999            let mut end_row = selection.end.row;
 7000
 7001            // Skip selections that overlap with a range that has already been rewrapped.
 7002            let selection_range = start_row..end_row;
 7003            if rewrapped_row_ranges
 7004                .iter()
 7005                .any(|range| range.overlaps(&selection_range))
 7006            {
 7007                continue;
 7008            }
 7009
 7010            let mut should_rewrap = !only_text;
 7011
 7012            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7013                match language_scope.language_name().0.as_ref() {
 7014                    "Markdown" | "Plain Text" => {
 7015                        should_rewrap = true;
 7016                    }
 7017                    _ => {}
 7018                }
 7019            }
 7020
 7021            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7022
 7023            // Since not all lines in the selection may be at the same indent
 7024            // level, choose the indent size that is the most common between all
 7025            // of the lines.
 7026            //
 7027            // If there is a tie, we use the deepest indent.
 7028            let (indent_size, indent_end) = {
 7029                let mut indent_size_occurrences = HashMap::default();
 7030                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7031
 7032                for row in start_row..=end_row {
 7033                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7034                    rows_by_indent_size.entry(indent).or_default().push(row);
 7035                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7036                }
 7037
 7038                let indent_size = indent_size_occurrences
 7039                    .into_iter()
 7040                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7041                    .map(|(indent, _)| indent)
 7042                    .unwrap_or_default();
 7043                let row = rows_by_indent_size[&indent_size][0];
 7044                let indent_end = Point::new(row, indent_size.len);
 7045
 7046                (indent_size, indent_end)
 7047            };
 7048
 7049            let mut line_prefix = indent_size.chars().collect::<String>();
 7050
 7051            if let Some(comment_prefix) =
 7052                buffer
 7053                    .language_scope_at(selection.head())
 7054                    .and_then(|language| {
 7055                        language
 7056                            .line_comment_prefixes()
 7057                            .iter()
 7058                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7059                            .cloned()
 7060                    })
 7061            {
 7062                line_prefix.push_str(&comment_prefix);
 7063                should_rewrap = true;
 7064            }
 7065
 7066            if !should_rewrap {
 7067                continue;
 7068            }
 7069
 7070            if selection.is_empty() {
 7071                'expand_upwards: while start_row > 0 {
 7072                    let prev_row = start_row - 1;
 7073                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7074                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7075                    {
 7076                        start_row = prev_row;
 7077                    } else {
 7078                        break 'expand_upwards;
 7079                    }
 7080                }
 7081
 7082                'expand_downwards: while end_row < buffer.max_point().row {
 7083                    let next_row = end_row + 1;
 7084                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7085                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7086                    {
 7087                        end_row = next_row;
 7088                    } else {
 7089                        break 'expand_downwards;
 7090                    }
 7091                }
 7092            }
 7093
 7094            let start = Point::new(start_row, 0);
 7095            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7096            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7097            let Some(lines_without_prefixes) = selection_text
 7098                .lines()
 7099                .map(|line| {
 7100                    line.strip_prefix(&line_prefix)
 7101                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7102                        .ok_or_else(|| {
 7103                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7104                        })
 7105                })
 7106                .collect::<Result<Vec<_>, _>>()
 7107                .log_err()
 7108            else {
 7109                continue;
 7110            };
 7111
 7112            let wrap_column = buffer
 7113                .settings_at(Point::new(start_row, 0), cx)
 7114                .preferred_line_length as usize;
 7115            let wrapped_text = wrap_with_prefix(
 7116                line_prefix,
 7117                lines_without_prefixes.join(" "),
 7118                wrap_column,
 7119                tab_size,
 7120            );
 7121
 7122            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7123            let mut offset = start.to_offset(&buffer);
 7124            let mut moved_since_edit = true;
 7125
 7126            for change in diff.iter_all_changes() {
 7127                let value = change.value();
 7128                match change.tag() {
 7129                    ChangeTag::Equal => {
 7130                        offset += value.len();
 7131                        moved_since_edit = true;
 7132                    }
 7133                    ChangeTag::Delete => {
 7134                        let start = buffer.anchor_after(offset);
 7135                        let end = buffer.anchor_before(offset + value.len());
 7136
 7137                        if moved_since_edit {
 7138                            edits.push((start..end, String::new()));
 7139                        } else {
 7140                            edits.last_mut().unwrap().0.end = end;
 7141                        }
 7142
 7143                        offset += value.len();
 7144                        moved_since_edit = false;
 7145                    }
 7146                    ChangeTag::Insert => {
 7147                        if moved_since_edit {
 7148                            let anchor = buffer.anchor_after(offset);
 7149                            edits.push((anchor..anchor, value.to_string()));
 7150                        } else {
 7151                            edits.last_mut().unwrap().1.push_str(value);
 7152                        }
 7153
 7154                        moved_since_edit = false;
 7155                    }
 7156                }
 7157            }
 7158
 7159            rewrapped_row_ranges.push(start_row..=end_row);
 7160        }
 7161
 7162        self.buffer
 7163            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7164    }
 7165
 7166    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7167        let mut text = String::new();
 7168        let buffer = self.buffer.read(cx).snapshot(cx);
 7169        let mut selections = self.selections.all::<Point>(cx);
 7170        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7171        {
 7172            let max_point = buffer.max_point();
 7173            let mut is_first = true;
 7174            for selection in &mut selections {
 7175                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7176                if is_entire_line {
 7177                    selection.start = Point::new(selection.start.row, 0);
 7178                    if !selection.is_empty() && selection.end.column == 0 {
 7179                        selection.end = cmp::min(max_point, selection.end);
 7180                    } else {
 7181                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7182                    }
 7183                    selection.goal = SelectionGoal::None;
 7184                }
 7185                if is_first {
 7186                    is_first = false;
 7187                } else {
 7188                    text += "\n";
 7189                }
 7190                let mut len = 0;
 7191                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7192                    text.push_str(chunk);
 7193                    len += chunk.len();
 7194                }
 7195                clipboard_selections.push(ClipboardSelection {
 7196                    len,
 7197                    is_entire_line,
 7198                    first_line_indent: buffer
 7199                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7200                        .len,
 7201                });
 7202            }
 7203        }
 7204
 7205        self.transact(cx, |this, cx| {
 7206            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7207                s.select(selections);
 7208            });
 7209            this.insert("", cx);
 7210            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7211                text,
 7212                clipboard_selections,
 7213            ));
 7214        });
 7215    }
 7216
 7217    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7218        let selections = self.selections.all::<Point>(cx);
 7219        let buffer = self.buffer.read(cx).read(cx);
 7220        let mut text = String::new();
 7221
 7222        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7223        {
 7224            let max_point = buffer.max_point();
 7225            let mut is_first = true;
 7226            for selection in selections.iter() {
 7227                let mut start = selection.start;
 7228                let mut end = selection.end;
 7229                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7230                if is_entire_line {
 7231                    start = Point::new(start.row, 0);
 7232                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7233                }
 7234                if is_first {
 7235                    is_first = false;
 7236                } else {
 7237                    text += "\n";
 7238                }
 7239                let mut len = 0;
 7240                for chunk in buffer.text_for_range(start..end) {
 7241                    text.push_str(chunk);
 7242                    len += chunk.len();
 7243                }
 7244                clipboard_selections.push(ClipboardSelection {
 7245                    len,
 7246                    is_entire_line,
 7247                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7248                });
 7249            }
 7250        }
 7251
 7252        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7253            text,
 7254            clipboard_selections,
 7255        ));
 7256    }
 7257
 7258    pub fn do_paste(
 7259        &mut self,
 7260        text: &String,
 7261        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7262        handle_entire_lines: bool,
 7263        cx: &mut ViewContext<Self>,
 7264    ) {
 7265        if self.read_only(cx) {
 7266            return;
 7267        }
 7268
 7269        let clipboard_text = Cow::Borrowed(text);
 7270
 7271        self.transact(cx, |this, cx| {
 7272            if let Some(mut clipboard_selections) = clipboard_selections {
 7273                let old_selections = this.selections.all::<usize>(cx);
 7274                let all_selections_were_entire_line =
 7275                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7276                let first_selection_indent_column =
 7277                    clipboard_selections.first().map(|s| s.first_line_indent);
 7278                if clipboard_selections.len() != old_selections.len() {
 7279                    clipboard_selections.drain(..);
 7280                }
 7281                let cursor_offset = this.selections.last::<usize>(cx).head();
 7282                let mut auto_indent_on_paste = true;
 7283
 7284                this.buffer.update(cx, |buffer, cx| {
 7285                    let snapshot = buffer.read(cx);
 7286                    auto_indent_on_paste =
 7287                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7288
 7289                    let mut start_offset = 0;
 7290                    let mut edits = Vec::new();
 7291                    let mut original_indent_columns = Vec::new();
 7292                    for (ix, selection) in old_selections.iter().enumerate() {
 7293                        let to_insert;
 7294                        let entire_line;
 7295                        let original_indent_column;
 7296                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7297                            let end_offset = start_offset + clipboard_selection.len;
 7298                            to_insert = &clipboard_text[start_offset..end_offset];
 7299                            entire_line = clipboard_selection.is_entire_line;
 7300                            start_offset = end_offset + 1;
 7301                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7302                        } else {
 7303                            to_insert = clipboard_text.as_str();
 7304                            entire_line = all_selections_were_entire_line;
 7305                            original_indent_column = first_selection_indent_column
 7306                        }
 7307
 7308                        // If the corresponding selection was empty when this slice of the
 7309                        // clipboard text was written, then the entire line containing the
 7310                        // selection was copied. If this selection is also currently empty,
 7311                        // then paste the line before the current line of the buffer.
 7312                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7313                            let column = selection.start.to_point(&snapshot).column as usize;
 7314                            let line_start = selection.start - column;
 7315                            line_start..line_start
 7316                        } else {
 7317                            selection.range()
 7318                        };
 7319
 7320                        edits.push((range, to_insert));
 7321                        original_indent_columns.extend(original_indent_column);
 7322                    }
 7323                    drop(snapshot);
 7324
 7325                    buffer.edit(
 7326                        edits,
 7327                        if auto_indent_on_paste {
 7328                            Some(AutoindentMode::Block {
 7329                                original_indent_columns,
 7330                            })
 7331                        } else {
 7332                            None
 7333                        },
 7334                        cx,
 7335                    );
 7336                });
 7337
 7338                let selections = this.selections.all::<usize>(cx);
 7339                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7340            } else {
 7341                this.insert(&clipboard_text, cx);
 7342            }
 7343        });
 7344    }
 7345
 7346    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7347        if let Some(item) = cx.read_from_clipboard() {
 7348            let entries = item.entries();
 7349
 7350            match entries.first() {
 7351                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7352                // of all the pasted entries.
 7353                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7354                    .do_paste(
 7355                        clipboard_string.text(),
 7356                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7357                        true,
 7358                        cx,
 7359                    ),
 7360                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7361            }
 7362        }
 7363    }
 7364
 7365    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7366        if self.read_only(cx) {
 7367            return;
 7368        }
 7369
 7370        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7371            if let Some((selections, _)) =
 7372                self.selection_history.transaction(transaction_id).cloned()
 7373            {
 7374                self.change_selections(None, cx, |s| {
 7375                    s.select_anchors(selections.to_vec());
 7376                });
 7377            }
 7378            self.request_autoscroll(Autoscroll::fit(), cx);
 7379            self.unmark_text(cx);
 7380            self.refresh_inline_completion(true, false, cx);
 7381            cx.emit(EditorEvent::Edited { transaction_id });
 7382            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7383        }
 7384    }
 7385
 7386    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7387        if self.read_only(cx) {
 7388            return;
 7389        }
 7390
 7391        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7392            if let Some((_, Some(selections))) =
 7393                self.selection_history.transaction(transaction_id).cloned()
 7394            {
 7395                self.change_selections(None, cx, |s| {
 7396                    s.select_anchors(selections.to_vec());
 7397                });
 7398            }
 7399            self.request_autoscroll(Autoscroll::fit(), cx);
 7400            self.unmark_text(cx);
 7401            self.refresh_inline_completion(true, false, cx);
 7402            cx.emit(EditorEvent::Edited { transaction_id });
 7403        }
 7404    }
 7405
 7406    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7407        self.buffer
 7408            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7409    }
 7410
 7411    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7412        self.buffer
 7413            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7414    }
 7415
 7416    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7417        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7418            let line_mode = s.line_mode;
 7419            s.move_with(|map, selection| {
 7420                let cursor = if selection.is_empty() && !line_mode {
 7421                    movement::left(map, selection.start)
 7422                } else {
 7423                    selection.start
 7424                };
 7425                selection.collapse_to(cursor, SelectionGoal::None);
 7426            });
 7427        })
 7428    }
 7429
 7430    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7431        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7432            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7433        })
 7434    }
 7435
 7436    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7437        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7438            let line_mode = s.line_mode;
 7439            s.move_with(|map, selection| {
 7440                let cursor = if selection.is_empty() && !line_mode {
 7441                    movement::right(map, selection.end)
 7442                } else {
 7443                    selection.end
 7444                };
 7445                selection.collapse_to(cursor, SelectionGoal::None)
 7446            });
 7447        })
 7448    }
 7449
 7450    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7452            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7453        })
 7454    }
 7455
 7456    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7457        if self.take_rename(true, cx).is_some() {
 7458            return;
 7459        }
 7460
 7461        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7462            cx.propagate();
 7463            return;
 7464        }
 7465
 7466        let text_layout_details = &self.text_layout_details(cx);
 7467        let selection_count = self.selections.count();
 7468        let first_selection = self.selections.first_anchor();
 7469
 7470        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7471            let line_mode = s.line_mode;
 7472            s.move_with(|map, selection| {
 7473                if !selection.is_empty() && !line_mode {
 7474                    selection.goal = SelectionGoal::None;
 7475                }
 7476                let (cursor, goal) = movement::up(
 7477                    map,
 7478                    selection.start,
 7479                    selection.goal,
 7480                    false,
 7481                    text_layout_details,
 7482                );
 7483                selection.collapse_to(cursor, goal);
 7484            });
 7485        });
 7486
 7487        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7488        {
 7489            cx.propagate();
 7490        }
 7491    }
 7492
 7493    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7494        if self.take_rename(true, cx).is_some() {
 7495            return;
 7496        }
 7497
 7498        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7499            cx.propagate();
 7500            return;
 7501        }
 7502
 7503        let text_layout_details = &self.text_layout_details(cx);
 7504
 7505        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7506            let line_mode = s.line_mode;
 7507            s.move_with(|map, selection| {
 7508                if !selection.is_empty() && !line_mode {
 7509                    selection.goal = SelectionGoal::None;
 7510                }
 7511                let (cursor, goal) = movement::up_by_rows(
 7512                    map,
 7513                    selection.start,
 7514                    action.lines,
 7515                    selection.goal,
 7516                    false,
 7517                    text_layout_details,
 7518                );
 7519                selection.collapse_to(cursor, goal);
 7520            });
 7521        })
 7522    }
 7523
 7524    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7525        if self.take_rename(true, cx).is_some() {
 7526            return;
 7527        }
 7528
 7529        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7530            cx.propagate();
 7531            return;
 7532        }
 7533
 7534        let text_layout_details = &self.text_layout_details(cx);
 7535
 7536        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7537            let line_mode = s.line_mode;
 7538            s.move_with(|map, selection| {
 7539                if !selection.is_empty() && !line_mode {
 7540                    selection.goal = SelectionGoal::None;
 7541                }
 7542                let (cursor, goal) = movement::down_by_rows(
 7543                    map,
 7544                    selection.start,
 7545                    action.lines,
 7546                    selection.goal,
 7547                    false,
 7548                    text_layout_details,
 7549                );
 7550                selection.collapse_to(cursor, goal);
 7551            });
 7552        })
 7553    }
 7554
 7555    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7556        let text_layout_details = &self.text_layout_details(cx);
 7557        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7558            s.move_heads_with(|map, head, goal| {
 7559                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7560            })
 7561        })
 7562    }
 7563
 7564    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7565        let text_layout_details = &self.text_layout_details(cx);
 7566        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7567            s.move_heads_with(|map, head, goal| {
 7568                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7569            })
 7570        })
 7571    }
 7572
 7573    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7574        let Some(row_count) = self.visible_row_count() else {
 7575            return;
 7576        };
 7577
 7578        let text_layout_details = &self.text_layout_details(cx);
 7579
 7580        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7581            s.move_heads_with(|map, head, goal| {
 7582                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7583            })
 7584        })
 7585    }
 7586
 7587    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7588        if self.take_rename(true, cx).is_some() {
 7589            return;
 7590        }
 7591
 7592        if self
 7593            .context_menu
 7594            .write()
 7595            .as_mut()
 7596            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7597            .unwrap_or(false)
 7598        {
 7599            return;
 7600        }
 7601
 7602        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7603            cx.propagate();
 7604            return;
 7605        }
 7606
 7607        let Some(row_count) = self.visible_row_count() else {
 7608            return;
 7609        };
 7610
 7611        let autoscroll = if action.center_cursor {
 7612            Autoscroll::center()
 7613        } else {
 7614            Autoscroll::fit()
 7615        };
 7616
 7617        let text_layout_details = &self.text_layout_details(cx);
 7618
 7619        self.change_selections(Some(autoscroll), cx, |s| {
 7620            let line_mode = s.line_mode;
 7621            s.move_with(|map, selection| {
 7622                if !selection.is_empty() && !line_mode {
 7623                    selection.goal = SelectionGoal::None;
 7624                }
 7625                let (cursor, goal) = movement::up_by_rows(
 7626                    map,
 7627                    selection.end,
 7628                    row_count,
 7629                    selection.goal,
 7630                    false,
 7631                    text_layout_details,
 7632                );
 7633                selection.collapse_to(cursor, goal);
 7634            });
 7635        });
 7636    }
 7637
 7638    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7639        let text_layout_details = &self.text_layout_details(cx);
 7640        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7641            s.move_heads_with(|map, head, goal| {
 7642                movement::up(map, head, goal, false, text_layout_details)
 7643            })
 7644        })
 7645    }
 7646
 7647    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7648        self.take_rename(true, cx);
 7649
 7650        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7651            cx.propagate();
 7652            return;
 7653        }
 7654
 7655        let text_layout_details = &self.text_layout_details(cx);
 7656        let selection_count = self.selections.count();
 7657        let first_selection = self.selections.first_anchor();
 7658
 7659        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7660            let line_mode = s.line_mode;
 7661            s.move_with(|map, selection| {
 7662                if !selection.is_empty() && !line_mode {
 7663                    selection.goal = SelectionGoal::None;
 7664                }
 7665                let (cursor, goal) = movement::down(
 7666                    map,
 7667                    selection.end,
 7668                    selection.goal,
 7669                    false,
 7670                    text_layout_details,
 7671                );
 7672                selection.collapse_to(cursor, goal);
 7673            });
 7674        });
 7675
 7676        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7677        {
 7678            cx.propagate();
 7679        }
 7680    }
 7681
 7682    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7683        let Some(row_count) = self.visible_row_count() else {
 7684            return;
 7685        };
 7686
 7687        let text_layout_details = &self.text_layout_details(cx);
 7688
 7689        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7690            s.move_heads_with(|map, head, goal| {
 7691                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7692            })
 7693        })
 7694    }
 7695
 7696    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7697        if self.take_rename(true, cx).is_some() {
 7698            return;
 7699        }
 7700
 7701        if self
 7702            .context_menu
 7703            .write()
 7704            .as_mut()
 7705            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7706            .unwrap_or(false)
 7707        {
 7708            return;
 7709        }
 7710
 7711        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7712            cx.propagate();
 7713            return;
 7714        }
 7715
 7716        let Some(row_count) = self.visible_row_count() else {
 7717            return;
 7718        };
 7719
 7720        let autoscroll = if action.center_cursor {
 7721            Autoscroll::center()
 7722        } else {
 7723            Autoscroll::fit()
 7724        };
 7725
 7726        let text_layout_details = &self.text_layout_details(cx);
 7727        self.change_selections(Some(autoscroll), cx, |s| {
 7728            let line_mode = s.line_mode;
 7729            s.move_with(|map, selection| {
 7730                if !selection.is_empty() && !line_mode {
 7731                    selection.goal = SelectionGoal::None;
 7732                }
 7733                let (cursor, goal) = movement::down_by_rows(
 7734                    map,
 7735                    selection.end,
 7736                    row_count,
 7737                    selection.goal,
 7738                    false,
 7739                    text_layout_details,
 7740                );
 7741                selection.collapse_to(cursor, goal);
 7742            });
 7743        });
 7744    }
 7745
 7746    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7747        let text_layout_details = &self.text_layout_details(cx);
 7748        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7749            s.move_heads_with(|map, head, goal| {
 7750                movement::down(map, head, goal, false, text_layout_details)
 7751            })
 7752        });
 7753    }
 7754
 7755    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7756        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7757            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7758        }
 7759    }
 7760
 7761    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7762        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7763            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7764        }
 7765    }
 7766
 7767    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7768        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7769            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7770        }
 7771    }
 7772
 7773    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7774        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7775            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7776        }
 7777    }
 7778
 7779    pub fn move_to_previous_word_start(
 7780        &mut self,
 7781        _: &MoveToPreviousWordStart,
 7782        cx: &mut ViewContext<Self>,
 7783    ) {
 7784        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7785            s.move_cursors_with(|map, head, _| {
 7786                (
 7787                    movement::previous_word_start(map, head),
 7788                    SelectionGoal::None,
 7789                )
 7790            });
 7791        })
 7792    }
 7793
 7794    pub fn move_to_previous_subword_start(
 7795        &mut self,
 7796        _: &MoveToPreviousSubwordStart,
 7797        cx: &mut ViewContext<Self>,
 7798    ) {
 7799        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7800            s.move_cursors_with(|map, head, _| {
 7801                (
 7802                    movement::previous_subword_start(map, head),
 7803                    SelectionGoal::None,
 7804                )
 7805            });
 7806        })
 7807    }
 7808
 7809    pub fn select_to_previous_word_start(
 7810        &mut self,
 7811        _: &SelectToPreviousWordStart,
 7812        cx: &mut ViewContext<Self>,
 7813    ) {
 7814        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7815            s.move_heads_with(|map, head, _| {
 7816                (
 7817                    movement::previous_word_start(map, head),
 7818                    SelectionGoal::None,
 7819                )
 7820            });
 7821        })
 7822    }
 7823
 7824    pub fn select_to_previous_subword_start(
 7825        &mut self,
 7826        _: &SelectToPreviousSubwordStart,
 7827        cx: &mut ViewContext<Self>,
 7828    ) {
 7829        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7830            s.move_heads_with(|map, head, _| {
 7831                (
 7832                    movement::previous_subword_start(map, head),
 7833                    SelectionGoal::None,
 7834                )
 7835            });
 7836        })
 7837    }
 7838
 7839    pub fn delete_to_previous_word_start(
 7840        &mut self,
 7841        action: &DeleteToPreviousWordStart,
 7842        cx: &mut ViewContext<Self>,
 7843    ) {
 7844        self.transact(cx, |this, cx| {
 7845            this.select_autoclose_pair(cx);
 7846            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7847                let line_mode = s.line_mode;
 7848                s.move_with(|map, selection| {
 7849                    if selection.is_empty() && !line_mode {
 7850                        let cursor = if action.ignore_newlines {
 7851                            movement::previous_word_start(map, selection.head())
 7852                        } else {
 7853                            movement::previous_word_start_or_newline(map, selection.head())
 7854                        };
 7855                        selection.set_head(cursor, SelectionGoal::None);
 7856                    }
 7857                });
 7858            });
 7859            this.insert("", cx);
 7860        });
 7861    }
 7862
 7863    pub fn delete_to_previous_subword_start(
 7864        &mut self,
 7865        _: &DeleteToPreviousSubwordStart,
 7866        cx: &mut ViewContext<Self>,
 7867    ) {
 7868        self.transact(cx, |this, cx| {
 7869            this.select_autoclose_pair(cx);
 7870            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7871                let line_mode = s.line_mode;
 7872                s.move_with(|map, selection| {
 7873                    if selection.is_empty() && !line_mode {
 7874                        let cursor = movement::previous_subword_start(map, selection.head());
 7875                        selection.set_head(cursor, SelectionGoal::None);
 7876                    }
 7877                });
 7878            });
 7879            this.insert("", cx);
 7880        });
 7881    }
 7882
 7883    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7884        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7885            s.move_cursors_with(|map, head, _| {
 7886                (movement::next_word_end(map, head), SelectionGoal::None)
 7887            });
 7888        })
 7889    }
 7890
 7891    pub fn move_to_next_subword_end(
 7892        &mut self,
 7893        _: &MoveToNextSubwordEnd,
 7894        cx: &mut ViewContext<Self>,
 7895    ) {
 7896        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897            s.move_cursors_with(|map, head, _| {
 7898                (movement::next_subword_end(map, head), SelectionGoal::None)
 7899            });
 7900        })
 7901    }
 7902
 7903    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7904        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7905            s.move_heads_with(|map, head, _| {
 7906                (movement::next_word_end(map, head), SelectionGoal::None)
 7907            });
 7908        })
 7909    }
 7910
 7911    pub fn select_to_next_subword_end(
 7912        &mut self,
 7913        _: &SelectToNextSubwordEnd,
 7914        cx: &mut ViewContext<Self>,
 7915    ) {
 7916        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7917            s.move_heads_with(|map, head, _| {
 7918                (movement::next_subword_end(map, head), SelectionGoal::None)
 7919            });
 7920        })
 7921    }
 7922
 7923    pub fn delete_to_next_word_end(
 7924        &mut self,
 7925        action: &DeleteToNextWordEnd,
 7926        cx: &mut ViewContext<Self>,
 7927    ) {
 7928        self.transact(cx, |this, cx| {
 7929            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7930                let line_mode = s.line_mode;
 7931                s.move_with(|map, selection| {
 7932                    if selection.is_empty() && !line_mode {
 7933                        let cursor = if action.ignore_newlines {
 7934                            movement::next_word_end(map, selection.head())
 7935                        } else {
 7936                            movement::next_word_end_or_newline(map, selection.head())
 7937                        };
 7938                        selection.set_head(cursor, SelectionGoal::None);
 7939                    }
 7940                });
 7941            });
 7942            this.insert("", cx);
 7943        });
 7944    }
 7945
 7946    pub fn delete_to_next_subword_end(
 7947        &mut self,
 7948        _: &DeleteToNextSubwordEnd,
 7949        cx: &mut ViewContext<Self>,
 7950    ) {
 7951        self.transact(cx, |this, cx| {
 7952            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7953                s.move_with(|map, selection| {
 7954                    if selection.is_empty() {
 7955                        let cursor = movement::next_subword_end(map, selection.head());
 7956                        selection.set_head(cursor, SelectionGoal::None);
 7957                    }
 7958                });
 7959            });
 7960            this.insert("", cx);
 7961        });
 7962    }
 7963
 7964    pub fn move_to_beginning_of_line(
 7965        &mut self,
 7966        action: &MoveToBeginningOfLine,
 7967        cx: &mut ViewContext<Self>,
 7968    ) {
 7969        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7970            s.move_cursors_with(|map, head, _| {
 7971                (
 7972                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7973                    SelectionGoal::None,
 7974                )
 7975            });
 7976        })
 7977    }
 7978
 7979    pub fn select_to_beginning_of_line(
 7980        &mut self,
 7981        action: &SelectToBeginningOfLine,
 7982        cx: &mut ViewContext<Self>,
 7983    ) {
 7984        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7985            s.move_heads_with(|map, head, _| {
 7986                (
 7987                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7988                    SelectionGoal::None,
 7989                )
 7990            });
 7991        });
 7992    }
 7993
 7994    pub fn delete_to_beginning_of_line(
 7995        &mut self,
 7996        _: &DeleteToBeginningOfLine,
 7997        cx: &mut ViewContext<Self>,
 7998    ) {
 7999        self.transact(cx, |this, cx| {
 8000            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8001                s.move_with(|_, selection| {
 8002                    selection.reversed = true;
 8003                });
 8004            });
 8005
 8006            this.select_to_beginning_of_line(
 8007                &SelectToBeginningOfLine {
 8008                    stop_at_soft_wraps: false,
 8009                },
 8010                cx,
 8011            );
 8012            this.backspace(&Backspace, cx);
 8013        });
 8014    }
 8015
 8016    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8018            s.move_cursors_with(|map, head, _| {
 8019                (
 8020                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8021                    SelectionGoal::None,
 8022                )
 8023            });
 8024        })
 8025    }
 8026
 8027    pub fn select_to_end_of_line(
 8028        &mut self,
 8029        action: &SelectToEndOfLine,
 8030        cx: &mut ViewContext<Self>,
 8031    ) {
 8032        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8033            s.move_heads_with(|map, head, _| {
 8034                (
 8035                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8036                    SelectionGoal::None,
 8037                )
 8038            });
 8039        })
 8040    }
 8041
 8042    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8043        self.transact(cx, |this, cx| {
 8044            this.select_to_end_of_line(
 8045                &SelectToEndOfLine {
 8046                    stop_at_soft_wraps: false,
 8047                },
 8048                cx,
 8049            );
 8050            this.delete(&Delete, cx);
 8051        });
 8052    }
 8053
 8054    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8055        self.transact(cx, |this, cx| {
 8056            this.select_to_end_of_line(
 8057                &SelectToEndOfLine {
 8058                    stop_at_soft_wraps: false,
 8059                },
 8060                cx,
 8061            );
 8062            this.cut(&Cut, cx);
 8063        });
 8064    }
 8065
 8066    pub fn move_to_start_of_paragraph(
 8067        &mut self,
 8068        _: &MoveToStartOfParagraph,
 8069        cx: &mut ViewContext<Self>,
 8070    ) {
 8071        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8072            cx.propagate();
 8073            return;
 8074        }
 8075
 8076        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8077            s.move_with(|map, selection| {
 8078                selection.collapse_to(
 8079                    movement::start_of_paragraph(map, selection.head(), 1),
 8080                    SelectionGoal::None,
 8081                )
 8082            });
 8083        })
 8084    }
 8085
 8086    pub fn move_to_end_of_paragraph(
 8087        &mut self,
 8088        _: &MoveToEndOfParagraph,
 8089        cx: &mut ViewContext<Self>,
 8090    ) {
 8091        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8092            cx.propagate();
 8093            return;
 8094        }
 8095
 8096        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8097            s.move_with(|map, selection| {
 8098                selection.collapse_to(
 8099                    movement::end_of_paragraph(map, selection.head(), 1),
 8100                    SelectionGoal::None,
 8101                )
 8102            });
 8103        })
 8104    }
 8105
 8106    pub fn select_to_start_of_paragraph(
 8107        &mut self,
 8108        _: &SelectToStartOfParagraph,
 8109        cx: &mut ViewContext<Self>,
 8110    ) {
 8111        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8112            cx.propagate();
 8113            return;
 8114        }
 8115
 8116        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8117            s.move_heads_with(|map, head, _| {
 8118                (
 8119                    movement::start_of_paragraph(map, head, 1),
 8120                    SelectionGoal::None,
 8121                )
 8122            });
 8123        })
 8124    }
 8125
 8126    pub fn select_to_end_of_paragraph(
 8127        &mut self,
 8128        _: &SelectToEndOfParagraph,
 8129        cx: &mut ViewContext<Self>,
 8130    ) {
 8131        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8132            cx.propagate();
 8133            return;
 8134        }
 8135
 8136        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8137            s.move_heads_with(|map, head, _| {
 8138                (
 8139                    movement::end_of_paragraph(map, head, 1),
 8140                    SelectionGoal::None,
 8141                )
 8142            });
 8143        })
 8144    }
 8145
 8146    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8147        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8148            cx.propagate();
 8149            return;
 8150        }
 8151
 8152        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8153            s.select_ranges(vec![0..0]);
 8154        });
 8155    }
 8156
 8157    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8158        let mut selection = self.selections.last::<Point>(cx);
 8159        selection.set_head(Point::zero(), SelectionGoal::None);
 8160
 8161        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8162            s.select(vec![selection]);
 8163        });
 8164    }
 8165
 8166    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8167        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8168            cx.propagate();
 8169            return;
 8170        }
 8171
 8172        let cursor = self.buffer.read(cx).read(cx).len();
 8173        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8174            s.select_ranges(vec![cursor..cursor])
 8175        });
 8176    }
 8177
 8178    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8179        self.nav_history = nav_history;
 8180    }
 8181
 8182    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8183        self.nav_history.as_ref()
 8184    }
 8185
 8186    fn push_to_nav_history(
 8187        &mut self,
 8188        cursor_anchor: Anchor,
 8189        new_position: Option<Point>,
 8190        cx: &mut ViewContext<Self>,
 8191    ) {
 8192        if let Some(nav_history) = self.nav_history.as_mut() {
 8193            let buffer = self.buffer.read(cx).read(cx);
 8194            let cursor_position = cursor_anchor.to_point(&buffer);
 8195            let scroll_state = self.scroll_manager.anchor();
 8196            let scroll_top_row = scroll_state.top_row(&buffer);
 8197            drop(buffer);
 8198
 8199            if let Some(new_position) = new_position {
 8200                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8201                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8202                    return;
 8203                }
 8204            }
 8205
 8206            nav_history.push(
 8207                Some(NavigationData {
 8208                    cursor_anchor,
 8209                    cursor_position,
 8210                    scroll_anchor: scroll_state,
 8211                    scroll_top_row,
 8212                }),
 8213                cx,
 8214            );
 8215        }
 8216    }
 8217
 8218    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8219        let buffer = self.buffer.read(cx).snapshot(cx);
 8220        let mut selection = self.selections.first::<usize>(cx);
 8221        selection.set_head(buffer.len(), SelectionGoal::None);
 8222        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8223            s.select(vec![selection]);
 8224        });
 8225    }
 8226
 8227    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8228        let end = self.buffer.read(cx).read(cx).len();
 8229        self.change_selections(None, cx, |s| {
 8230            s.select_ranges(vec![0..end]);
 8231        });
 8232    }
 8233
 8234    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8235        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8236        let mut selections = self.selections.all::<Point>(cx);
 8237        let max_point = display_map.buffer_snapshot.max_point();
 8238        for selection in &mut selections {
 8239            let rows = selection.spanned_rows(true, &display_map);
 8240            selection.start = Point::new(rows.start.0, 0);
 8241            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8242            selection.reversed = false;
 8243        }
 8244        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8245            s.select(selections);
 8246        });
 8247    }
 8248
 8249    pub fn split_selection_into_lines(
 8250        &mut self,
 8251        _: &SplitSelectionIntoLines,
 8252        cx: &mut ViewContext<Self>,
 8253    ) {
 8254        let mut to_unfold = Vec::new();
 8255        let mut new_selection_ranges = Vec::new();
 8256        {
 8257            let selections = self.selections.all::<Point>(cx);
 8258            let buffer = self.buffer.read(cx).read(cx);
 8259            for selection in selections {
 8260                for row in selection.start.row..selection.end.row {
 8261                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8262                    new_selection_ranges.push(cursor..cursor);
 8263                }
 8264                new_selection_ranges.push(selection.end..selection.end);
 8265                to_unfold.push(selection.start..selection.end);
 8266            }
 8267        }
 8268        self.unfold_ranges(&to_unfold, true, true, cx);
 8269        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8270            s.select_ranges(new_selection_ranges);
 8271        });
 8272    }
 8273
 8274    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8275        self.add_selection(true, cx);
 8276    }
 8277
 8278    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8279        self.add_selection(false, cx);
 8280    }
 8281
 8282    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8284        let mut selections = self.selections.all::<Point>(cx);
 8285        let text_layout_details = self.text_layout_details(cx);
 8286        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8287            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8288            let range = oldest_selection.display_range(&display_map).sorted();
 8289
 8290            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8291            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8292            let positions = start_x.min(end_x)..start_x.max(end_x);
 8293
 8294            selections.clear();
 8295            let mut stack = Vec::new();
 8296            for row in range.start.row().0..=range.end.row().0 {
 8297                if let Some(selection) = self.selections.build_columnar_selection(
 8298                    &display_map,
 8299                    DisplayRow(row),
 8300                    &positions,
 8301                    oldest_selection.reversed,
 8302                    &text_layout_details,
 8303                ) {
 8304                    stack.push(selection.id);
 8305                    selections.push(selection);
 8306                }
 8307            }
 8308
 8309            if above {
 8310                stack.reverse();
 8311            }
 8312
 8313            AddSelectionsState { above, stack }
 8314        });
 8315
 8316        let last_added_selection = *state.stack.last().unwrap();
 8317        let mut new_selections = Vec::new();
 8318        if above == state.above {
 8319            let end_row = if above {
 8320                DisplayRow(0)
 8321            } else {
 8322                display_map.max_point().row()
 8323            };
 8324
 8325            'outer: for selection in selections {
 8326                if selection.id == last_added_selection {
 8327                    let range = selection.display_range(&display_map).sorted();
 8328                    debug_assert_eq!(range.start.row(), range.end.row());
 8329                    let mut row = range.start.row();
 8330                    let positions =
 8331                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8332                            px(start)..px(end)
 8333                        } else {
 8334                            let start_x =
 8335                                display_map.x_for_display_point(range.start, &text_layout_details);
 8336                            let end_x =
 8337                                display_map.x_for_display_point(range.end, &text_layout_details);
 8338                            start_x.min(end_x)..start_x.max(end_x)
 8339                        };
 8340
 8341                    while row != end_row {
 8342                        if above {
 8343                            row.0 -= 1;
 8344                        } else {
 8345                            row.0 += 1;
 8346                        }
 8347
 8348                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8349                            &display_map,
 8350                            row,
 8351                            &positions,
 8352                            selection.reversed,
 8353                            &text_layout_details,
 8354                        ) {
 8355                            state.stack.push(new_selection.id);
 8356                            if above {
 8357                                new_selections.push(new_selection);
 8358                                new_selections.push(selection);
 8359                            } else {
 8360                                new_selections.push(selection);
 8361                                new_selections.push(new_selection);
 8362                            }
 8363
 8364                            continue 'outer;
 8365                        }
 8366                    }
 8367                }
 8368
 8369                new_selections.push(selection);
 8370            }
 8371        } else {
 8372            new_selections = selections;
 8373            new_selections.retain(|s| s.id != last_added_selection);
 8374            state.stack.pop();
 8375        }
 8376
 8377        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8378            s.select(new_selections);
 8379        });
 8380        if state.stack.len() > 1 {
 8381            self.add_selections_state = Some(state);
 8382        }
 8383    }
 8384
 8385    pub fn select_next_match_internal(
 8386        &mut self,
 8387        display_map: &DisplaySnapshot,
 8388        replace_newest: bool,
 8389        autoscroll: Option<Autoscroll>,
 8390        cx: &mut ViewContext<Self>,
 8391    ) -> Result<()> {
 8392        fn select_next_match_ranges(
 8393            this: &mut Editor,
 8394            range: Range<usize>,
 8395            replace_newest: bool,
 8396            auto_scroll: Option<Autoscroll>,
 8397            cx: &mut ViewContext<Editor>,
 8398        ) {
 8399            this.unfold_ranges(&[range.clone()], false, true, cx);
 8400            this.change_selections(auto_scroll, cx, |s| {
 8401                if replace_newest {
 8402                    s.delete(s.newest_anchor().id);
 8403                }
 8404                s.insert_range(range.clone());
 8405            });
 8406        }
 8407
 8408        let buffer = &display_map.buffer_snapshot;
 8409        let mut selections = self.selections.all::<usize>(cx);
 8410        if let Some(mut select_next_state) = self.select_next_state.take() {
 8411            let query = &select_next_state.query;
 8412            if !select_next_state.done {
 8413                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8414                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8415                let mut next_selected_range = None;
 8416
 8417                let bytes_after_last_selection =
 8418                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8419                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8420                let query_matches = query
 8421                    .stream_find_iter(bytes_after_last_selection)
 8422                    .map(|result| (last_selection.end, result))
 8423                    .chain(
 8424                        query
 8425                            .stream_find_iter(bytes_before_first_selection)
 8426                            .map(|result| (0, result)),
 8427                    );
 8428
 8429                for (start_offset, query_match) in query_matches {
 8430                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8431                    let offset_range =
 8432                        start_offset + query_match.start()..start_offset + query_match.end();
 8433                    let display_range = offset_range.start.to_display_point(display_map)
 8434                        ..offset_range.end.to_display_point(display_map);
 8435
 8436                    if !select_next_state.wordwise
 8437                        || (!movement::is_inside_word(display_map, display_range.start)
 8438                            && !movement::is_inside_word(display_map, display_range.end))
 8439                    {
 8440                        // TODO: This is n^2, because we might check all the selections
 8441                        if !selections
 8442                            .iter()
 8443                            .any(|selection| selection.range().overlaps(&offset_range))
 8444                        {
 8445                            next_selected_range = Some(offset_range);
 8446                            break;
 8447                        }
 8448                    }
 8449                }
 8450
 8451                if let Some(next_selected_range) = next_selected_range {
 8452                    select_next_match_ranges(
 8453                        self,
 8454                        next_selected_range,
 8455                        replace_newest,
 8456                        autoscroll,
 8457                        cx,
 8458                    );
 8459                } else {
 8460                    select_next_state.done = true;
 8461                }
 8462            }
 8463
 8464            self.select_next_state = Some(select_next_state);
 8465        } else {
 8466            let mut only_carets = true;
 8467            let mut same_text_selected = true;
 8468            let mut selected_text = None;
 8469
 8470            let mut selections_iter = selections.iter().peekable();
 8471            while let Some(selection) = selections_iter.next() {
 8472                if selection.start != selection.end {
 8473                    only_carets = false;
 8474                }
 8475
 8476                if same_text_selected {
 8477                    if selected_text.is_none() {
 8478                        selected_text =
 8479                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8480                    }
 8481
 8482                    if let Some(next_selection) = selections_iter.peek() {
 8483                        if next_selection.range().len() == selection.range().len() {
 8484                            let next_selected_text = buffer
 8485                                .text_for_range(next_selection.range())
 8486                                .collect::<String>();
 8487                            if Some(next_selected_text) != selected_text {
 8488                                same_text_selected = false;
 8489                                selected_text = None;
 8490                            }
 8491                        } else {
 8492                            same_text_selected = false;
 8493                            selected_text = None;
 8494                        }
 8495                    }
 8496                }
 8497            }
 8498
 8499            if only_carets {
 8500                for selection in &mut selections {
 8501                    let word_range = movement::surrounding_word(
 8502                        display_map,
 8503                        selection.start.to_display_point(display_map),
 8504                    );
 8505                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8506                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8507                    selection.goal = SelectionGoal::None;
 8508                    selection.reversed = false;
 8509                    select_next_match_ranges(
 8510                        self,
 8511                        selection.start..selection.end,
 8512                        replace_newest,
 8513                        autoscroll,
 8514                        cx,
 8515                    );
 8516                }
 8517
 8518                if selections.len() == 1 {
 8519                    let selection = selections
 8520                        .last()
 8521                        .expect("ensured that there's only one selection");
 8522                    let query = buffer
 8523                        .text_for_range(selection.start..selection.end)
 8524                        .collect::<String>();
 8525                    let is_empty = query.is_empty();
 8526                    let select_state = SelectNextState {
 8527                        query: AhoCorasick::new(&[query])?,
 8528                        wordwise: true,
 8529                        done: is_empty,
 8530                    };
 8531                    self.select_next_state = Some(select_state);
 8532                } else {
 8533                    self.select_next_state = None;
 8534                }
 8535            } else if let Some(selected_text) = selected_text {
 8536                self.select_next_state = Some(SelectNextState {
 8537                    query: AhoCorasick::new(&[selected_text])?,
 8538                    wordwise: false,
 8539                    done: false,
 8540                });
 8541                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8542            }
 8543        }
 8544        Ok(())
 8545    }
 8546
 8547    pub fn select_all_matches(
 8548        &mut self,
 8549        _action: &SelectAllMatches,
 8550        cx: &mut ViewContext<Self>,
 8551    ) -> Result<()> {
 8552        self.push_to_selection_history();
 8553        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8554
 8555        self.select_next_match_internal(&display_map, false, None, cx)?;
 8556        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8557            return Ok(());
 8558        };
 8559        if select_next_state.done {
 8560            return Ok(());
 8561        }
 8562
 8563        let mut new_selections = self.selections.all::<usize>(cx);
 8564
 8565        let buffer = &display_map.buffer_snapshot;
 8566        let query_matches = select_next_state
 8567            .query
 8568            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8569
 8570        for query_match in query_matches {
 8571            let query_match = query_match.unwrap(); // can only fail due to I/O
 8572            let offset_range = query_match.start()..query_match.end();
 8573            let display_range = offset_range.start.to_display_point(&display_map)
 8574                ..offset_range.end.to_display_point(&display_map);
 8575
 8576            if !select_next_state.wordwise
 8577                || (!movement::is_inside_word(&display_map, display_range.start)
 8578                    && !movement::is_inside_word(&display_map, display_range.end))
 8579            {
 8580                self.selections.change_with(cx, |selections| {
 8581                    new_selections.push(Selection {
 8582                        id: selections.new_selection_id(),
 8583                        start: offset_range.start,
 8584                        end: offset_range.end,
 8585                        reversed: false,
 8586                        goal: SelectionGoal::None,
 8587                    });
 8588                });
 8589            }
 8590        }
 8591
 8592        new_selections.sort_by_key(|selection| selection.start);
 8593        let mut ix = 0;
 8594        while ix + 1 < new_selections.len() {
 8595            let current_selection = &new_selections[ix];
 8596            let next_selection = &new_selections[ix + 1];
 8597            if current_selection.range().overlaps(&next_selection.range()) {
 8598                if current_selection.id < next_selection.id {
 8599                    new_selections.remove(ix + 1);
 8600                } else {
 8601                    new_selections.remove(ix);
 8602                }
 8603            } else {
 8604                ix += 1;
 8605            }
 8606        }
 8607
 8608        select_next_state.done = true;
 8609        self.unfold_ranges(
 8610            &new_selections
 8611                .iter()
 8612                .map(|selection| selection.range())
 8613                .collect::<Vec<_>>(),
 8614            false,
 8615            false,
 8616            cx,
 8617        );
 8618        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8619            selections.select(new_selections)
 8620        });
 8621
 8622        Ok(())
 8623    }
 8624
 8625    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8626        self.push_to_selection_history();
 8627        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8628        self.select_next_match_internal(
 8629            &display_map,
 8630            action.replace_newest,
 8631            Some(Autoscroll::newest()),
 8632            cx,
 8633        )?;
 8634        Ok(())
 8635    }
 8636
 8637    pub fn select_previous(
 8638        &mut self,
 8639        action: &SelectPrevious,
 8640        cx: &mut ViewContext<Self>,
 8641    ) -> Result<()> {
 8642        self.push_to_selection_history();
 8643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8644        let buffer = &display_map.buffer_snapshot;
 8645        let mut selections = self.selections.all::<usize>(cx);
 8646        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8647            let query = &select_prev_state.query;
 8648            if !select_prev_state.done {
 8649                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8650                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8651                let mut next_selected_range = None;
 8652                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8653                let bytes_before_last_selection =
 8654                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8655                let bytes_after_first_selection =
 8656                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8657                let query_matches = query
 8658                    .stream_find_iter(bytes_before_last_selection)
 8659                    .map(|result| (last_selection.start, result))
 8660                    .chain(
 8661                        query
 8662                            .stream_find_iter(bytes_after_first_selection)
 8663                            .map(|result| (buffer.len(), result)),
 8664                    );
 8665                for (end_offset, query_match) in query_matches {
 8666                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8667                    let offset_range =
 8668                        end_offset - query_match.end()..end_offset - query_match.start();
 8669                    let display_range = offset_range.start.to_display_point(&display_map)
 8670                        ..offset_range.end.to_display_point(&display_map);
 8671
 8672                    if !select_prev_state.wordwise
 8673                        || (!movement::is_inside_word(&display_map, display_range.start)
 8674                            && !movement::is_inside_word(&display_map, display_range.end))
 8675                    {
 8676                        next_selected_range = Some(offset_range);
 8677                        break;
 8678                    }
 8679                }
 8680
 8681                if let Some(next_selected_range) = next_selected_range {
 8682                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8683                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8684                        if action.replace_newest {
 8685                            s.delete(s.newest_anchor().id);
 8686                        }
 8687                        s.insert_range(next_selected_range);
 8688                    });
 8689                } else {
 8690                    select_prev_state.done = true;
 8691                }
 8692            }
 8693
 8694            self.select_prev_state = Some(select_prev_state);
 8695        } else {
 8696            let mut only_carets = true;
 8697            let mut same_text_selected = true;
 8698            let mut selected_text = None;
 8699
 8700            let mut selections_iter = selections.iter().peekable();
 8701            while let Some(selection) = selections_iter.next() {
 8702                if selection.start != selection.end {
 8703                    only_carets = false;
 8704                }
 8705
 8706                if same_text_selected {
 8707                    if selected_text.is_none() {
 8708                        selected_text =
 8709                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8710                    }
 8711
 8712                    if let Some(next_selection) = selections_iter.peek() {
 8713                        if next_selection.range().len() == selection.range().len() {
 8714                            let next_selected_text = buffer
 8715                                .text_for_range(next_selection.range())
 8716                                .collect::<String>();
 8717                            if Some(next_selected_text) != selected_text {
 8718                                same_text_selected = false;
 8719                                selected_text = None;
 8720                            }
 8721                        } else {
 8722                            same_text_selected = false;
 8723                            selected_text = None;
 8724                        }
 8725                    }
 8726                }
 8727            }
 8728
 8729            if only_carets {
 8730                for selection in &mut selections {
 8731                    let word_range = movement::surrounding_word(
 8732                        &display_map,
 8733                        selection.start.to_display_point(&display_map),
 8734                    );
 8735                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8736                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8737                    selection.goal = SelectionGoal::None;
 8738                    selection.reversed = false;
 8739                }
 8740                if selections.len() == 1 {
 8741                    let selection = selections
 8742                        .last()
 8743                        .expect("ensured that there's only one selection");
 8744                    let query = buffer
 8745                        .text_for_range(selection.start..selection.end)
 8746                        .collect::<String>();
 8747                    let is_empty = query.is_empty();
 8748                    let select_state = SelectNextState {
 8749                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8750                        wordwise: true,
 8751                        done: is_empty,
 8752                    };
 8753                    self.select_prev_state = Some(select_state);
 8754                } else {
 8755                    self.select_prev_state = None;
 8756                }
 8757
 8758                self.unfold_ranges(
 8759                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8760                    false,
 8761                    true,
 8762                    cx,
 8763                );
 8764                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8765                    s.select(selections);
 8766                });
 8767            } else if let Some(selected_text) = selected_text {
 8768                self.select_prev_state = Some(SelectNextState {
 8769                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8770                    wordwise: false,
 8771                    done: false,
 8772                });
 8773                self.select_previous(action, cx)?;
 8774            }
 8775        }
 8776        Ok(())
 8777    }
 8778
 8779    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8780        let text_layout_details = &self.text_layout_details(cx);
 8781        self.transact(cx, |this, cx| {
 8782            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8783            let mut edits = Vec::new();
 8784            let mut selection_edit_ranges = Vec::new();
 8785            let mut last_toggled_row = None;
 8786            let snapshot = this.buffer.read(cx).read(cx);
 8787            let empty_str: Arc<str> = Arc::default();
 8788            let mut suffixes_inserted = Vec::new();
 8789            let ignore_indent = action.ignore_indent;
 8790
 8791            fn comment_prefix_range(
 8792                snapshot: &MultiBufferSnapshot,
 8793                row: MultiBufferRow,
 8794                comment_prefix: &str,
 8795                comment_prefix_whitespace: &str,
 8796                ignore_indent: bool,
 8797            ) -> Range<Point> {
 8798                let indent_size = if ignore_indent {
 8799                    0
 8800                } else {
 8801                    snapshot.indent_size_for_line(row).len
 8802                };
 8803
 8804                let start = Point::new(row.0, indent_size);
 8805
 8806                let mut line_bytes = snapshot
 8807                    .bytes_in_range(start..snapshot.max_point())
 8808                    .flatten()
 8809                    .copied();
 8810
 8811                // If this line currently begins with the line comment prefix, then record
 8812                // the range containing the prefix.
 8813                if line_bytes
 8814                    .by_ref()
 8815                    .take(comment_prefix.len())
 8816                    .eq(comment_prefix.bytes())
 8817                {
 8818                    // Include any whitespace that matches the comment prefix.
 8819                    let matching_whitespace_len = line_bytes
 8820                        .zip(comment_prefix_whitespace.bytes())
 8821                        .take_while(|(a, b)| a == b)
 8822                        .count() as u32;
 8823                    let end = Point::new(
 8824                        start.row,
 8825                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8826                    );
 8827                    start..end
 8828                } else {
 8829                    start..start
 8830                }
 8831            }
 8832
 8833            fn comment_suffix_range(
 8834                snapshot: &MultiBufferSnapshot,
 8835                row: MultiBufferRow,
 8836                comment_suffix: &str,
 8837                comment_suffix_has_leading_space: bool,
 8838            ) -> Range<Point> {
 8839                let end = Point::new(row.0, snapshot.line_len(row));
 8840                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8841
 8842                let mut line_end_bytes = snapshot
 8843                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8844                    .flatten()
 8845                    .copied();
 8846
 8847                let leading_space_len = if suffix_start_column > 0
 8848                    && line_end_bytes.next() == Some(b' ')
 8849                    && comment_suffix_has_leading_space
 8850                {
 8851                    1
 8852                } else {
 8853                    0
 8854                };
 8855
 8856                // If this line currently begins with the line comment prefix, then record
 8857                // the range containing the prefix.
 8858                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8859                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8860                    start..end
 8861                } else {
 8862                    end..end
 8863                }
 8864            }
 8865
 8866            // TODO: Handle selections that cross excerpts
 8867            for selection in &mut selections {
 8868                let start_column = snapshot
 8869                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8870                    .len;
 8871                let language = if let Some(language) =
 8872                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8873                {
 8874                    language
 8875                } else {
 8876                    continue;
 8877                };
 8878
 8879                selection_edit_ranges.clear();
 8880
 8881                // If multiple selections contain a given row, avoid processing that
 8882                // row more than once.
 8883                let mut start_row = MultiBufferRow(selection.start.row);
 8884                if last_toggled_row == Some(start_row) {
 8885                    start_row = start_row.next_row();
 8886                }
 8887                let end_row =
 8888                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8889                        MultiBufferRow(selection.end.row - 1)
 8890                    } else {
 8891                        MultiBufferRow(selection.end.row)
 8892                    };
 8893                last_toggled_row = Some(end_row);
 8894
 8895                if start_row > end_row {
 8896                    continue;
 8897                }
 8898
 8899                // If the language has line comments, toggle those.
 8900                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8901
 8902                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8903                if ignore_indent {
 8904                    full_comment_prefixes = full_comment_prefixes
 8905                        .into_iter()
 8906                        .map(|s| Arc::from(s.trim_end()))
 8907                        .collect();
 8908                }
 8909
 8910                if !full_comment_prefixes.is_empty() {
 8911                    let first_prefix = full_comment_prefixes
 8912                        .first()
 8913                        .expect("prefixes is non-empty");
 8914                    let prefix_trimmed_lengths = full_comment_prefixes
 8915                        .iter()
 8916                        .map(|p| p.trim_end_matches(' ').len())
 8917                        .collect::<SmallVec<[usize; 4]>>();
 8918
 8919                    let mut all_selection_lines_are_comments = true;
 8920
 8921                    for row in start_row.0..=end_row.0 {
 8922                        let row = MultiBufferRow(row);
 8923                        if start_row < end_row && snapshot.is_line_blank(row) {
 8924                            continue;
 8925                        }
 8926
 8927                        let prefix_range = full_comment_prefixes
 8928                            .iter()
 8929                            .zip(prefix_trimmed_lengths.iter().copied())
 8930                            .map(|(prefix, trimmed_prefix_len)| {
 8931                                comment_prefix_range(
 8932                                    snapshot.deref(),
 8933                                    row,
 8934                                    &prefix[..trimmed_prefix_len],
 8935                                    &prefix[trimmed_prefix_len..],
 8936                                    ignore_indent,
 8937                                )
 8938                            })
 8939                            .max_by_key(|range| range.end.column - range.start.column)
 8940                            .expect("prefixes is non-empty");
 8941
 8942                        if prefix_range.is_empty() {
 8943                            all_selection_lines_are_comments = false;
 8944                        }
 8945
 8946                        selection_edit_ranges.push(prefix_range);
 8947                    }
 8948
 8949                    if all_selection_lines_are_comments {
 8950                        edits.extend(
 8951                            selection_edit_ranges
 8952                                .iter()
 8953                                .cloned()
 8954                                .map(|range| (range, empty_str.clone())),
 8955                        );
 8956                    } else {
 8957                        let min_column = selection_edit_ranges
 8958                            .iter()
 8959                            .map(|range| range.start.column)
 8960                            .min()
 8961                            .unwrap_or(0);
 8962                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8963                            let position = Point::new(range.start.row, min_column);
 8964                            (position..position, first_prefix.clone())
 8965                        }));
 8966                    }
 8967                } else if let Some((full_comment_prefix, comment_suffix)) =
 8968                    language.block_comment_delimiters()
 8969                {
 8970                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8971                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8972                    let prefix_range = comment_prefix_range(
 8973                        snapshot.deref(),
 8974                        start_row,
 8975                        comment_prefix,
 8976                        comment_prefix_whitespace,
 8977                        ignore_indent,
 8978                    );
 8979                    let suffix_range = comment_suffix_range(
 8980                        snapshot.deref(),
 8981                        end_row,
 8982                        comment_suffix.trim_start_matches(' '),
 8983                        comment_suffix.starts_with(' '),
 8984                    );
 8985
 8986                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8987                        edits.push((
 8988                            prefix_range.start..prefix_range.start,
 8989                            full_comment_prefix.clone(),
 8990                        ));
 8991                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8992                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8993                    } else {
 8994                        edits.push((prefix_range, empty_str.clone()));
 8995                        edits.push((suffix_range, empty_str.clone()));
 8996                    }
 8997                } else {
 8998                    continue;
 8999                }
 9000            }
 9001
 9002            drop(snapshot);
 9003            this.buffer.update(cx, |buffer, cx| {
 9004                buffer.edit(edits, None, cx);
 9005            });
 9006
 9007            // Adjust selections so that they end before any comment suffixes that
 9008            // were inserted.
 9009            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9010            let mut selections = this.selections.all::<Point>(cx);
 9011            let snapshot = this.buffer.read(cx).read(cx);
 9012            for selection in &mut selections {
 9013                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9014                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9015                        Ordering::Less => {
 9016                            suffixes_inserted.next();
 9017                            continue;
 9018                        }
 9019                        Ordering::Greater => break,
 9020                        Ordering::Equal => {
 9021                            if selection.end.column == snapshot.line_len(row) {
 9022                                if selection.is_empty() {
 9023                                    selection.start.column -= suffix_len as u32;
 9024                                }
 9025                                selection.end.column -= suffix_len as u32;
 9026                            }
 9027                            break;
 9028                        }
 9029                    }
 9030                }
 9031            }
 9032
 9033            drop(snapshot);
 9034            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9035
 9036            let selections = this.selections.all::<Point>(cx);
 9037            let selections_on_single_row = selections.windows(2).all(|selections| {
 9038                selections[0].start.row == selections[1].start.row
 9039                    && selections[0].end.row == selections[1].end.row
 9040                    && selections[0].start.row == selections[0].end.row
 9041            });
 9042            let selections_selecting = selections
 9043                .iter()
 9044                .any(|selection| selection.start != selection.end);
 9045            let advance_downwards = action.advance_downwards
 9046                && selections_on_single_row
 9047                && !selections_selecting
 9048                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9049
 9050            if advance_downwards {
 9051                let snapshot = this.buffer.read(cx).snapshot(cx);
 9052
 9053                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9054                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9055                        let mut point = display_point.to_point(display_snapshot);
 9056                        point.row += 1;
 9057                        point = snapshot.clip_point(point, Bias::Left);
 9058                        let display_point = point.to_display_point(display_snapshot);
 9059                        let goal = SelectionGoal::HorizontalPosition(
 9060                            display_snapshot
 9061                                .x_for_display_point(display_point, text_layout_details)
 9062                                .into(),
 9063                        );
 9064                        (display_point, goal)
 9065                    })
 9066                });
 9067            }
 9068        });
 9069    }
 9070
 9071    pub fn select_enclosing_symbol(
 9072        &mut self,
 9073        _: &SelectEnclosingSymbol,
 9074        cx: &mut ViewContext<Self>,
 9075    ) {
 9076        let buffer = self.buffer.read(cx).snapshot(cx);
 9077        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9078
 9079        fn update_selection(
 9080            selection: &Selection<usize>,
 9081            buffer_snap: &MultiBufferSnapshot,
 9082        ) -> Option<Selection<usize>> {
 9083            let cursor = selection.head();
 9084            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9085            for symbol in symbols.iter().rev() {
 9086                let start = symbol.range.start.to_offset(buffer_snap);
 9087                let end = symbol.range.end.to_offset(buffer_snap);
 9088                let new_range = start..end;
 9089                if start < selection.start || end > selection.end {
 9090                    return Some(Selection {
 9091                        id: selection.id,
 9092                        start: new_range.start,
 9093                        end: new_range.end,
 9094                        goal: SelectionGoal::None,
 9095                        reversed: selection.reversed,
 9096                    });
 9097                }
 9098            }
 9099            None
 9100        }
 9101
 9102        let mut selected_larger_symbol = false;
 9103        let new_selections = old_selections
 9104            .iter()
 9105            .map(|selection| match update_selection(selection, &buffer) {
 9106                Some(new_selection) => {
 9107                    if new_selection.range() != selection.range() {
 9108                        selected_larger_symbol = true;
 9109                    }
 9110                    new_selection
 9111                }
 9112                None => selection.clone(),
 9113            })
 9114            .collect::<Vec<_>>();
 9115
 9116        if selected_larger_symbol {
 9117            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9118                s.select(new_selections);
 9119            });
 9120        }
 9121    }
 9122
 9123    pub fn select_larger_syntax_node(
 9124        &mut self,
 9125        _: &SelectLargerSyntaxNode,
 9126        cx: &mut ViewContext<Self>,
 9127    ) {
 9128        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9129        let buffer = self.buffer.read(cx).snapshot(cx);
 9130        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9131
 9132        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9133        let mut selected_larger_node = false;
 9134        let new_selections = old_selections
 9135            .iter()
 9136            .map(|selection| {
 9137                let old_range = selection.start..selection.end;
 9138                let mut new_range = old_range.clone();
 9139                while let Some(containing_range) =
 9140                    buffer.range_for_syntax_ancestor(new_range.clone())
 9141                {
 9142                    new_range = containing_range;
 9143                    if !display_map.intersects_fold(new_range.start)
 9144                        && !display_map.intersects_fold(new_range.end)
 9145                    {
 9146                        break;
 9147                    }
 9148                }
 9149
 9150                selected_larger_node |= new_range != old_range;
 9151                Selection {
 9152                    id: selection.id,
 9153                    start: new_range.start,
 9154                    end: new_range.end,
 9155                    goal: SelectionGoal::None,
 9156                    reversed: selection.reversed,
 9157                }
 9158            })
 9159            .collect::<Vec<_>>();
 9160
 9161        if selected_larger_node {
 9162            stack.push(old_selections);
 9163            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9164                s.select(new_selections);
 9165            });
 9166        }
 9167        self.select_larger_syntax_node_stack = stack;
 9168    }
 9169
 9170    pub fn select_smaller_syntax_node(
 9171        &mut self,
 9172        _: &SelectSmallerSyntaxNode,
 9173        cx: &mut ViewContext<Self>,
 9174    ) {
 9175        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9176        if let Some(selections) = stack.pop() {
 9177            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9178                s.select(selections.to_vec());
 9179            });
 9180        }
 9181        self.select_larger_syntax_node_stack = stack;
 9182    }
 9183
 9184    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9185        if !EditorSettings::get_global(cx).gutter.runnables {
 9186            self.clear_tasks();
 9187            return Task::ready(());
 9188        }
 9189        let project = self.project.clone();
 9190        cx.spawn(|this, mut cx| async move {
 9191            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9192                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9193            }) else {
 9194                return;
 9195            };
 9196
 9197            let Some(project) = project else {
 9198                return;
 9199            };
 9200
 9201            let hide_runnables = project
 9202                .update(&mut cx, |project, cx| {
 9203                    // Do not display any test indicators in non-dev server remote projects.
 9204                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9205                })
 9206                .unwrap_or(true);
 9207            if hide_runnables {
 9208                return;
 9209            }
 9210            let new_rows =
 9211                cx.background_executor()
 9212                    .spawn({
 9213                        let snapshot = display_snapshot.clone();
 9214                        async move {
 9215                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9216                        }
 9217                    })
 9218                    .await;
 9219            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9220
 9221            this.update(&mut cx, |this, _| {
 9222                this.clear_tasks();
 9223                for (key, value) in rows {
 9224                    this.insert_tasks(key, value);
 9225                }
 9226            })
 9227            .ok();
 9228        })
 9229    }
 9230    fn fetch_runnable_ranges(
 9231        snapshot: &DisplaySnapshot,
 9232        range: Range<Anchor>,
 9233    ) -> Vec<language::RunnableRange> {
 9234        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9235    }
 9236
 9237    fn runnable_rows(
 9238        project: Model<Project>,
 9239        snapshot: DisplaySnapshot,
 9240        runnable_ranges: Vec<RunnableRange>,
 9241        mut cx: AsyncWindowContext,
 9242    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9243        runnable_ranges
 9244            .into_iter()
 9245            .filter_map(|mut runnable| {
 9246                let tasks = cx
 9247                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9248                    .ok()?;
 9249                if tasks.is_empty() {
 9250                    return None;
 9251                }
 9252
 9253                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9254
 9255                let row = snapshot
 9256                    .buffer_snapshot
 9257                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9258                    .1
 9259                    .start
 9260                    .row;
 9261
 9262                let context_range =
 9263                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9264                Some((
 9265                    (runnable.buffer_id, row),
 9266                    RunnableTasks {
 9267                        templates: tasks,
 9268                        offset: MultiBufferOffset(runnable.run_range.start),
 9269                        context_range,
 9270                        column: point.column,
 9271                        extra_variables: runnable.extra_captures,
 9272                    },
 9273                ))
 9274            })
 9275            .collect()
 9276    }
 9277
 9278    fn templates_with_tags(
 9279        project: &Model<Project>,
 9280        runnable: &mut Runnable,
 9281        cx: &WindowContext<'_>,
 9282    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9283        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9284            let (worktree_id, file) = project
 9285                .buffer_for_id(runnable.buffer, cx)
 9286                .and_then(|buffer| buffer.read(cx).file())
 9287                .map(|file| (file.worktree_id(cx), file.clone()))
 9288                .unzip();
 9289
 9290            (
 9291                project.task_store().read(cx).task_inventory().cloned(),
 9292                worktree_id,
 9293                file,
 9294            )
 9295        });
 9296
 9297        let tags = mem::take(&mut runnable.tags);
 9298        let mut tags: Vec<_> = tags
 9299            .into_iter()
 9300            .flat_map(|tag| {
 9301                let tag = tag.0.clone();
 9302                inventory
 9303                    .as_ref()
 9304                    .into_iter()
 9305                    .flat_map(|inventory| {
 9306                        inventory.read(cx).list_tasks(
 9307                            file.clone(),
 9308                            Some(runnable.language.clone()),
 9309                            worktree_id,
 9310                            cx,
 9311                        )
 9312                    })
 9313                    .filter(move |(_, template)| {
 9314                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9315                    })
 9316            })
 9317            .sorted_by_key(|(kind, _)| kind.to_owned())
 9318            .collect();
 9319        if let Some((leading_tag_source, _)) = tags.first() {
 9320            // Strongest source wins; if we have worktree tag binding, prefer that to
 9321            // global and language bindings;
 9322            // if we have a global binding, prefer that to language binding.
 9323            let first_mismatch = tags
 9324                .iter()
 9325                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9326            if let Some(index) = first_mismatch {
 9327                tags.truncate(index);
 9328            }
 9329        }
 9330
 9331        tags
 9332    }
 9333
 9334    pub fn move_to_enclosing_bracket(
 9335        &mut self,
 9336        _: &MoveToEnclosingBracket,
 9337        cx: &mut ViewContext<Self>,
 9338    ) {
 9339        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9340            s.move_offsets_with(|snapshot, selection| {
 9341                let Some(enclosing_bracket_ranges) =
 9342                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9343                else {
 9344                    return;
 9345                };
 9346
 9347                let mut best_length = usize::MAX;
 9348                let mut best_inside = false;
 9349                let mut best_in_bracket_range = false;
 9350                let mut best_destination = None;
 9351                for (open, close) in enclosing_bracket_ranges {
 9352                    let close = close.to_inclusive();
 9353                    let length = close.end() - open.start;
 9354                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9355                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9356                        || close.contains(&selection.head());
 9357
 9358                    // If best is next to a bracket and current isn't, skip
 9359                    if !in_bracket_range && best_in_bracket_range {
 9360                        continue;
 9361                    }
 9362
 9363                    // Prefer smaller lengths unless best is inside and current isn't
 9364                    if length > best_length && (best_inside || !inside) {
 9365                        continue;
 9366                    }
 9367
 9368                    best_length = length;
 9369                    best_inside = inside;
 9370                    best_in_bracket_range = in_bracket_range;
 9371                    best_destination = Some(
 9372                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9373                            if inside {
 9374                                open.end
 9375                            } else {
 9376                                open.start
 9377                            }
 9378                        } else if inside {
 9379                            *close.start()
 9380                        } else {
 9381                            *close.end()
 9382                        },
 9383                    );
 9384                }
 9385
 9386                if let Some(destination) = best_destination {
 9387                    selection.collapse_to(destination, SelectionGoal::None);
 9388                }
 9389            })
 9390        });
 9391    }
 9392
 9393    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9394        self.end_selection(cx);
 9395        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9396        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9397            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9398            self.select_next_state = entry.select_next_state;
 9399            self.select_prev_state = entry.select_prev_state;
 9400            self.add_selections_state = entry.add_selections_state;
 9401            self.request_autoscroll(Autoscroll::newest(), cx);
 9402        }
 9403        self.selection_history.mode = SelectionHistoryMode::Normal;
 9404    }
 9405
 9406    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9407        self.end_selection(cx);
 9408        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9409        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9410            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9411            self.select_next_state = entry.select_next_state;
 9412            self.select_prev_state = entry.select_prev_state;
 9413            self.add_selections_state = entry.add_selections_state;
 9414            self.request_autoscroll(Autoscroll::newest(), cx);
 9415        }
 9416        self.selection_history.mode = SelectionHistoryMode::Normal;
 9417    }
 9418
 9419    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9420        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9421    }
 9422
 9423    pub fn expand_excerpts_down(
 9424        &mut self,
 9425        action: &ExpandExcerptsDown,
 9426        cx: &mut ViewContext<Self>,
 9427    ) {
 9428        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9429    }
 9430
 9431    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9432        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9433    }
 9434
 9435    pub fn expand_excerpts_for_direction(
 9436        &mut self,
 9437        lines: u32,
 9438        direction: ExpandExcerptDirection,
 9439        cx: &mut ViewContext<Self>,
 9440    ) {
 9441        let selections = self.selections.disjoint_anchors();
 9442
 9443        let lines = if lines == 0 {
 9444            EditorSettings::get_global(cx).expand_excerpt_lines
 9445        } else {
 9446            lines
 9447        };
 9448
 9449        self.buffer.update(cx, |buffer, cx| {
 9450            buffer.expand_excerpts(
 9451                selections
 9452                    .iter()
 9453                    .map(|selection| selection.head().excerpt_id)
 9454                    .dedup(),
 9455                lines,
 9456                direction,
 9457                cx,
 9458            )
 9459        })
 9460    }
 9461
 9462    pub fn expand_excerpt(
 9463        &mut self,
 9464        excerpt: ExcerptId,
 9465        direction: ExpandExcerptDirection,
 9466        cx: &mut ViewContext<Self>,
 9467    ) {
 9468        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9469        self.buffer.update(cx, |buffer, cx| {
 9470            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9471        })
 9472    }
 9473
 9474    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9475        self.go_to_diagnostic_impl(Direction::Next, cx)
 9476    }
 9477
 9478    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9479        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9480    }
 9481
 9482    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9483        let buffer = self.buffer.read(cx).snapshot(cx);
 9484        let selection = self.selections.newest::<usize>(cx);
 9485
 9486        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9487        if direction == Direction::Next {
 9488            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9489                let (group_id, jump_to) = popover.activation_info();
 9490                if self.activate_diagnostics(group_id, cx) {
 9491                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9492                        let mut new_selection = s.newest_anchor().clone();
 9493                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9494                        s.select_anchors(vec![new_selection.clone()]);
 9495                    });
 9496                }
 9497                return;
 9498            }
 9499        }
 9500
 9501        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9502            active_diagnostics
 9503                .primary_range
 9504                .to_offset(&buffer)
 9505                .to_inclusive()
 9506        });
 9507        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9508            if active_primary_range.contains(&selection.head()) {
 9509                *active_primary_range.start()
 9510            } else {
 9511                selection.head()
 9512            }
 9513        } else {
 9514            selection.head()
 9515        };
 9516        let snapshot = self.snapshot(cx);
 9517        loop {
 9518            let diagnostics = if direction == Direction::Prev {
 9519                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9520            } else {
 9521                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9522            }
 9523            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9524            let group = diagnostics
 9525                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9526                // be sorted in a stable way
 9527                // skip until we are at current active diagnostic, if it exists
 9528                .skip_while(|entry| {
 9529                    (match direction {
 9530                        Direction::Prev => entry.range.start >= search_start,
 9531                        Direction::Next => entry.range.start <= search_start,
 9532                    }) && self
 9533                        .active_diagnostics
 9534                        .as_ref()
 9535                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9536                })
 9537                .find_map(|entry| {
 9538                    if entry.diagnostic.is_primary
 9539                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9540                        && !entry.range.is_empty()
 9541                        // if we match with the active diagnostic, skip it
 9542                        && Some(entry.diagnostic.group_id)
 9543                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9544                    {
 9545                        Some((entry.range, entry.diagnostic.group_id))
 9546                    } else {
 9547                        None
 9548                    }
 9549                });
 9550
 9551            if let Some((primary_range, group_id)) = group {
 9552                if self.activate_diagnostics(group_id, cx) {
 9553                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9554                        s.select(vec![Selection {
 9555                            id: selection.id,
 9556                            start: primary_range.start,
 9557                            end: primary_range.start,
 9558                            reversed: false,
 9559                            goal: SelectionGoal::None,
 9560                        }]);
 9561                    });
 9562                }
 9563                break;
 9564            } else {
 9565                // Cycle around to the start of the buffer, potentially moving back to the start of
 9566                // the currently active diagnostic.
 9567                active_primary_range.take();
 9568                if direction == Direction::Prev {
 9569                    if search_start == buffer.len() {
 9570                        break;
 9571                    } else {
 9572                        search_start = buffer.len();
 9573                    }
 9574                } else if search_start == 0 {
 9575                    break;
 9576                } else {
 9577                    search_start = 0;
 9578                }
 9579            }
 9580        }
 9581    }
 9582
 9583    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9584        let snapshot = self
 9585            .display_map
 9586            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9587        let selection = self.selections.newest::<Point>(cx);
 9588        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9589    }
 9590
 9591    fn go_to_hunk_after_position(
 9592        &mut self,
 9593        snapshot: &DisplaySnapshot,
 9594        position: Point,
 9595        cx: &mut ViewContext<'_, Editor>,
 9596    ) -> Option<MultiBufferDiffHunk> {
 9597        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9598            snapshot,
 9599            position,
 9600            false,
 9601            snapshot
 9602                .buffer_snapshot
 9603                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9604            cx,
 9605        ) {
 9606            return Some(hunk);
 9607        }
 9608
 9609        let wrapped_point = Point::zero();
 9610        self.go_to_next_hunk_in_direction(
 9611            snapshot,
 9612            wrapped_point,
 9613            true,
 9614            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9615                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9616            ),
 9617            cx,
 9618        )
 9619    }
 9620
 9621    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9622        let snapshot = self
 9623            .display_map
 9624            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9625        let selection = self.selections.newest::<Point>(cx);
 9626
 9627        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9628    }
 9629
 9630    fn go_to_hunk_before_position(
 9631        &mut self,
 9632        snapshot: &DisplaySnapshot,
 9633        position: Point,
 9634        cx: &mut ViewContext<'_, Editor>,
 9635    ) -> Option<MultiBufferDiffHunk> {
 9636        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9637            snapshot,
 9638            position,
 9639            false,
 9640            snapshot
 9641                .buffer_snapshot
 9642                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9643            cx,
 9644        ) {
 9645            return Some(hunk);
 9646        }
 9647
 9648        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9649        self.go_to_next_hunk_in_direction(
 9650            snapshot,
 9651            wrapped_point,
 9652            true,
 9653            snapshot
 9654                .buffer_snapshot
 9655                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9656            cx,
 9657        )
 9658    }
 9659
 9660    fn go_to_next_hunk_in_direction(
 9661        &mut self,
 9662        snapshot: &DisplaySnapshot,
 9663        initial_point: Point,
 9664        is_wrapped: bool,
 9665        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9666        cx: &mut ViewContext<Editor>,
 9667    ) -> Option<MultiBufferDiffHunk> {
 9668        let display_point = initial_point.to_display_point(snapshot);
 9669        let mut hunks = hunks
 9670            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9671            .filter(|(display_hunk, _)| {
 9672                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9673            })
 9674            .dedup();
 9675
 9676        if let Some((display_hunk, hunk)) = hunks.next() {
 9677            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9678                let row = display_hunk.start_display_row();
 9679                let point = DisplayPoint::new(row, 0);
 9680                s.select_display_ranges([point..point]);
 9681            });
 9682
 9683            Some(hunk)
 9684        } else {
 9685            None
 9686        }
 9687    }
 9688
 9689    pub fn go_to_definition(
 9690        &mut self,
 9691        _: &GoToDefinition,
 9692        cx: &mut ViewContext<Self>,
 9693    ) -> Task<Result<Navigated>> {
 9694        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9695        cx.spawn(|editor, mut cx| async move {
 9696            if definition.await? == Navigated::Yes {
 9697                return Ok(Navigated::Yes);
 9698            }
 9699            match editor.update(&mut cx, |editor, cx| {
 9700                editor.find_all_references(&FindAllReferences, cx)
 9701            })? {
 9702                Some(references) => references.await,
 9703                None => Ok(Navigated::No),
 9704            }
 9705        })
 9706    }
 9707
 9708    pub fn go_to_declaration(
 9709        &mut self,
 9710        _: &GoToDeclaration,
 9711        cx: &mut ViewContext<Self>,
 9712    ) -> Task<Result<Navigated>> {
 9713        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9714    }
 9715
 9716    pub fn go_to_declaration_split(
 9717        &mut self,
 9718        _: &GoToDeclaration,
 9719        cx: &mut ViewContext<Self>,
 9720    ) -> Task<Result<Navigated>> {
 9721        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9722    }
 9723
 9724    pub fn go_to_implementation(
 9725        &mut self,
 9726        _: &GoToImplementation,
 9727        cx: &mut ViewContext<Self>,
 9728    ) -> Task<Result<Navigated>> {
 9729        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9730    }
 9731
 9732    pub fn go_to_implementation_split(
 9733        &mut self,
 9734        _: &GoToImplementationSplit,
 9735        cx: &mut ViewContext<Self>,
 9736    ) -> Task<Result<Navigated>> {
 9737        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9738    }
 9739
 9740    pub fn go_to_type_definition(
 9741        &mut self,
 9742        _: &GoToTypeDefinition,
 9743        cx: &mut ViewContext<Self>,
 9744    ) -> Task<Result<Navigated>> {
 9745        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9746    }
 9747
 9748    pub fn go_to_definition_split(
 9749        &mut self,
 9750        _: &GoToDefinitionSplit,
 9751        cx: &mut ViewContext<Self>,
 9752    ) -> Task<Result<Navigated>> {
 9753        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9754    }
 9755
 9756    pub fn go_to_type_definition_split(
 9757        &mut self,
 9758        _: &GoToTypeDefinitionSplit,
 9759        cx: &mut ViewContext<Self>,
 9760    ) -> Task<Result<Navigated>> {
 9761        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9762    }
 9763
 9764    fn go_to_definition_of_kind(
 9765        &mut self,
 9766        kind: GotoDefinitionKind,
 9767        split: bool,
 9768        cx: &mut ViewContext<Self>,
 9769    ) -> Task<Result<Navigated>> {
 9770        let Some(provider) = self.semantics_provider.clone() else {
 9771            return Task::ready(Ok(Navigated::No));
 9772        };
 9773        let head = self.selections.newest::<usize>(cx).head();
 9774        let buffer = self.buffer.read(cx);
 9775        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9776            text_anchor
 9777        } else {
 9778            return Task::ready(Ok(Navigated::No));
 9779        };
 9780
 9781        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9782            return Task::ready(Ok(Navigated::No));
 9783        };
 9784
 9785        cx.spawn(|editor, mut cx| async move {
 9786            let definitions = definitions.await?;
 9787            let navigated = editor
 9788                .update(&mut cx, |editor, cx| {
 9789                    editor.navigate_to_hover_links(
 9790                        Some(kind),
 9791                        definitions
 9792                            .into_iter()
 9793                            .filter(|location| {
 9794                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9795                            })
 9796                            .map(HoverLink::Text)
 9797                            .collect::<Vec<_>>(),
 9798                        split,
 9799                        cx,
 9800                    )
 9801                })?
 9802                .await?;
 9803            anyhow::Ok(navigated)
 9804        })
 9805    }
 9806
 9807    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9808        let position = self.selections.newest_anchor().head();
 9809        let Some((buffer, buffer_position)) =
 9810            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9811        else {
 9812            return;
 9813        };
 9814
 9815        cx.spawn(|editor, mut cx| async move {
 9816            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9817                editor.update(&mut cx, |_, cx| {
 9818                    cx.open_url(&url);
 9819                })
 9820            } else {
 9821                Ok(())
 9822            }
 9823        })
 9824        .detach();
 9825    }
 9826
 9827    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9828        let Some(workspace) = self.workspace() else {
 9829            return;
 9830        };
 9831
 9832        let position = self.selections.newest_anchor().head();
 9833
 9834        let Some((buffer, buffer_position)) =
 9835            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9836        else {
 9837            return;
 9838        };
 9839
 9840        let project = self.project.clone();
 9841
 9842        cx.spawn(|_, mut cx| async move {
 9843            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9844
 9845            if let Some((_, path)) = result {
 9846                workspace
 9847                    .update(&mut cx, |workspace, cx| {
 9848                        workspace.open_resolved_path(path, cx)
 9849                    })?
 9850                    .await?;
 9851            }
 9852            anyhow::Ok(())
 9853        })
 9854        .detach();
 9855    }
 9856
 9857    pub(crate) fn navigate_to_hover_links(
 9858        &mut self,
 9859        kind: Option<GotoDefinitionKind>,
 9860        mut definitions: Vec<HoverLink>,
 9861        split: bool,
 9862        cx: &mut ViewContext<Editor>,
 9863    ) -> Task<Result<Navigated>> {
 9864        // If there is one definition, just open it directly
 9865        if definitions.len() == 1 {
 9866            let definition = definitions.pop().unwrap();
 9867
 9868            enum TargetTaskResult {
 9869                Location(Option<Location>),
 9870                AlreadyNavigated,
 9871            }
 9872
 9873            let target_task = match definition {
 9874                HoverLink::Text(link) => {
 9875                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9876                }
 9877                HoverLink::InlayHint(lsp_location, server_id) => {
 9878                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9879                    cx.background_executor().spawn(async move {
 9880                        let location = computation.await?;
 9881                        Ok(TargetTaskResult::Location(location))
 9882                    })
 9883                }
 9884                HoverLink::Url(url) => {
 9885                    cx.open_url(&url);
 9886                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9887                }
 9888                HoverLink::File(path) => {
 9889                    if let Some(workspace) = self.workspace() {
 9890                        cx.spawn(|_, mut cx| async move {
 9891                            workspace
 9892                                .update(&mut cx, |workspace, cx| {
 9893                                    workspace.open_resolved_path(path, cx)
 9894                                })?
 9895                                .await
 9896                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9897                        })
 9898                    } else {
 9899                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9900                    }
 9901                }
 9902            };
 9903            cx.spawn(|editor, mut cx| async move {
 9904                let target = match target_task.await.context("target resolution task")? {
 9905                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9906                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9907                    TargetTaskResult::Location(Some(target)) => target,
 9908                };
 9909
 9910                editor.update(&mut cx, |editor, cx| {
 9911                    let Some(workspace) = editor.workspace() else {
 9912                        return Navigated::No;
 9913                    };
 9914                    let pane = workspace.read(cx).active_pane().clone();
 9915
 9916                    let range = target.range.to_offset(target.buffer.read(cx));
 9917                    let range = editor.range_for_match(&range);
 9918
 9919                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9920                        let buffer = target.buffer.read(cx);
 9921                        let range = check_multiline_range(buffer, range);
 9922                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9923                            s.select_ranges([range]);
 9924                        });
 9925                    } else {
 9926                        cx.window_context().defer(move |cx| {
 9927                            let target_editor: View<Self> =
 9928                                workspace.update(cx, |workspace, cx| {
 9929                                    let pane = if split {
 9930                                        workspace.adjacent_pane(cx)
 9931                                    } else {
 9932                                        workspace.active_pane().clone()
 9933                                    };
 9934
 9935                                    workspace.open_project_item(
 9936                                        pane,
 9937                                        target.buffer.clone(),
 9938                                        true,
 9939                                        true,
 9940                                        cx,
 9941                                    )
 9942                                });
 9943                            target_editor.update(cx, |target_editor, cx| {
 9944                                // When selecting a definition in a different buffer, disable the nav history
 9945                                // to avoid creating a history entry at the previous cursor location.
 9946                                pane.update(cx, |pane, _| pane.disable_history());
 9947                                let buffer = target.buffer.read(cx);
 9948                                let range = check_multiline_range(buffer, range);
 9949                                target_editor.change_selections(
 9950                                    Some(Autoscroll::focused()),
 9951                                    cx,
 9952                                    |s| {
 9953                                        s.select_ranges([range]);
 9954                                    },
 9955                                );
 9956                                pane.update(cx, |pane, _| pane.enable_history());
 9957                            });
 9958                        });
 9959                    }
 9960                    Navigated::Yes
 9961                })
 9962            })
 9963        } else if !definitions.is_empty() {
 9964            cx.spawn(|editor, mut cx| async move {
 9965                let (title, location_tasks, workspace) = editor
 9966                    .update(&mut cx, |editor, cx| {
 9967                        let tab_kind = match kind {
 9968                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9969                            _ => "Definitions",
 9970                        };
 9971                        let title = definitions
 9972                            .iter()
 9973                            .find_map(|definition| match definition {
 9974                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9975                                    let buffer = origin.buffer.read(cx);
 9976                                    format!(
 9977                                        "{} for {}",
 9978                                        tab_kind,
 9979                                        buffer
 9980                                            .text_for_range(origin.range.clone())
 9981                                            .collect::<String>()
 9982                                    )
 9983                                }),
 9984                                HoverLink::InlayHint(_, _) => None,
 9985                                HoverLink::Url(_) => None,
 9986                                HoverLink::File(_) => None,
 9987                            })
 9988                            .unwrap_or(tab_kind.to_string());
 9989                        let location_tasks = definitions
 9990                            .into_iter()
 9991                            .map(|definition| match definition {
 9992                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9993                                HoverLink::InlayHint(lsp_location, server_id) => {
 9994                                    editor.compute_target_location(lsp_location, server_id, cx)
 9995                                }
 9996                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9997                                HoverLink::File(_) => Task::ready(Ok(None)),
 9998                            })
 9999                            .collect::<Vec<_>>();
10000                        (title, location_tasks, editor.workspace().clone())
10001                    })
10002                    .context("location tasks preparation")?;
10003
10004                let locations = future::join_all(location_tasks)
10005                    .await
10006                    .into_iter()
10007                    .filter_map(|location| location.transpose())
10008                    .collect::<Result<_>>()
10009                    .context("location tasks")?;
10010
10011                let Some(workspace) = workspace else {
10012                    return Ok(Navigated::No);
10013                };
10014                let opened = workspace
10015                    .update(&mut cx, |workspace, cx| {
10016                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10017                    })
10018                    .ok();
10019
10020                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10021            })
10022        } else {
10023            Task::ready(Ok(Navigated::No))
10024        }
10025    }
10026
10027    fn compute_target_location(
10028        &self,
10029        lsp_location: lsp::Location,
10030        server_id: LanguageServerId,
10031        cx: &mut ViewContext<Self>,
10032    ) -> Task<anyhow::Result<Option<Location>>> {
10033        let Some(project) = self.project.clone() else {
10034            return Task::Ready(Some(Ok(None)));
10035        };
10036
10037        cx.spawn(move |editor, mut cx| async move {
10038            let location_task = editor.update(&mut cx, |_, cx| {
10039                project.update(cx, |project, cx| {
10040                    let language_server_name = project
10041                        .language_server_statuses(cx)
10042                        .find(|(id, _)| server_id == *id)
10043                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10044                    language_server_name.map(|language_server_name| {
10045                        project.open_local_buffer_via_lsp(
10046                            lsp_location.uri.clone(),
10047                            server_id,
10048                            language_server_name,
10049                            cx,
10050                        )
10051                    })
10052                })
10053            })?;
10054            let location = match location_task {
10055                Some(task) => Some({
10056                    let target_buffer_handle = task.await.context("open local buffer")?;
10057                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10058                        let target_start = target_buffer
10059                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10060                        let target_end = target_buffer
10061                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10062                        target_buffer.anchor_after(target_start)
10063                            ..target_buffer.anchor_before(target_end)
10064                    })?;
10065                    Location {
10066                        buffer: target_buffer_handle,
10067                        range,
10068                    }
10069                }),
10070                None => None,
10071            };
10072            Ok(location)
10073        })
10074    }
10075
10076    pub fn find_all_references(
10077        &mut self,
10078        _: &FindAllReferences,
10079        cx: &mut ViewContext<Self>,
10080    ) -> Option<Task<Result<Navigated>>> {
10081        let selection = self.selections.newest::<usize>(cx);
10082        let multi_buffer = self.buffer.read(cx);
10083        let head = selection.head();
10084
10085        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10086        let head_anchor = multi_buffer_snapshot.anchor_at(
10087            head,
10088            if head < selection.tail() {
10089                Bias::Right
10090            } else {
10091                Bias::Left
10092            },
10093        );
10094
10095        match self
10096            .find_all_references_task_sources
10097            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10098        {
10099            Ok(_) => {
10100                log::info!(
10101                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10102                );
10103                return None;
10104            }
10105            Err(i) => {
10106                self.find_all_references_task_sources.insert(i, head_anchor);
10107            }
10108        }
10109
10110        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10111        let workspace = self.workspace()?;
10112        let project = workspace.read(cx).project().clone();
10113        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10114        Some(cx.spawn(|editor, mut cx| async move {
10115            let _cleanup = defer({
10116                let mut cx = cx.clone();
10117                move || {
10118                    let _ = editor.update(&mut cx, |editor, _| {
10119                        if let Ok(i) =
10120                            editor
10121                                .find_all_references_task_sources
10122                                .binary_search_by(|anchor| {
10123                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10124                                })
10125                        {
10126                            editor.find_all_references_task_sources.remove(i);
10127                        }
10128                    });
10129                }
10130            });
10131
10132            let locations = references.await?;
10133            if locations.is_empty() {
10134                return anyhow::Ok(Navigated::No);
10135            }
10136
10137            workspace.update(&mut cx, |workspace, cx| {
10138                let title = locations
10139                    .first()
10140                    .as_ref()
10141                    .map(|location| {
10142                        let buffer = location.buffer.read(cx);
10143                        format!(
10144                            "References to `{}`",
10145                            buffer
10146                                .text_for_range(location.range.clone())
10147                                .collect::<String>()
10148                        )
10149                    })
10150                    .unwrap();
10151                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10152                Navigated::Yes
10153            })
10154        }))
10155    }
10156
10157    /// Opens a multibuffer with the given project locations in it
10158    pub fn open_locations_in_multibuffer(
10159        workspace: &mut Workspace,
10160        mut locations: Vec<Location>,
10161        title: String,
10162        split: bool,
10163        cx: &mut ViewContext<Workspace>,
10164    ) {
10165        // If there are multiple definitions, open them in a multibuffer
10166        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10167        let mut locations = locations.into_iter().peekable();
10168        let mut ranges_to_highlight = Vec::new();
10169        let capability = workspace.project().read(cx).capability();
10170
10171        let excerpt_buffer = cx.new_model(|cx| {
10172            let mut multibuffer = MultiBuffer::new(capability);
10173            while let Some(location) = locations.next() {
10174                let buffer = location.buffer.read(cx);
10175                let mut ranges_for_buffer = Vec::new();
10176                let range = location.range.to_offset(buffer);
10177                ranges_for_buffer.push(range.clone());
10178
10179                while let Some(next_location) = locations.peek() {
10180                    if next_location.buffer == location.buffer {
10181                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10182                        locations.next();
10183                    } else {
10184                        break;
10185                    }
10186                }
10187
10188                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10189                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10190                    location.buffer.clone(),
10191                    ranges_for_buffer,
10192                    DEFAULT_MULTIBUFFER_CONTEXT,
10193                    cx,
10194                ))
10195            }
10196
10197            multibuffer.with_title(title)
10198        });
10199
10200        let editor = cx.new_view(|cx| {
10201            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10202        });
10203        editor.update(cx, |editor, cx| {
10204            if let Some(first_range) = ranges_to_highlight.first() {
10205                editor.change_selections(None, cx, |selections| {
10206                    selections.clear_disjoint();
10207                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10208                });
10209            }
10210            editor.highlight_background::<Self>(
10211                &ranges_to_highlight,
10212                |theme| theme.editor_highlighted_line_background,
10213                cx,
10214            );
10215        });
10216
10217        let item = Box::new(editor);
10218        let item_id = item.item_id();
10219
10220        if split {
10221            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10222        } else {
10223            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10224                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10225                    pane.close_current_preview_item(cx)
10226                } else {
10227                    None
10228                }
10229            });
10230            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10231        }
10232        workspace.active_pane().update(cx, |pane, cx| {
10233            pane.set_preview_item_id(Some(item_id), cx);
10234        });
10235    }
10236
10237    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10238        use language::ToOffset as _;
10239
10240        let provider = self.semantics_provider.clone()?;
10241        let selection = self.selections.newest_anchor().clone();
10242        let (cursor_buffer, cursor_buffer_position) = self
10243            .buffer
10244            .read(cx)
10245            .text_anchor_for_position(selection.head(), cx)?;
10246        let (tail_buffer, cursor_buffer_position_end) = self
10247            .buffer
10248            .read(cx)
10249            .text_anchor_for_position(selection.tail(), cx)?;
10250        if tail_buffer != cursor_buffer {
10251            return None;
10252        }
10253
10254        let snapshot = cursor_buffer.read(cx).snapshot();
10255        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10256        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10257        let prepare_rename = provider
10258            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10259            .unwrap_or_else(|| Task::ready(Ok(None)));
10260        drop(snapshot);
10261
10262        Some(cx.spawn(|this, mut cx| async move {
10263            let rename_range = if let Some(range) = prepare_rename.await? {
10264                Some(range)
10265            } else {
10266                this.update(&mut cx, |this, cx| {
10267                    let buffer = this.buffer.read(cx).snapshot(cx);
10268                    let mut buffer_highlights = this
10269                        .document_highlights_for_position(selection.head(), &buffer)
10270                        .filter(|highlight| {
10271                            highlight.start.excerpt_id == selection.head().excerpt_id
10272                                && highlight.end.excerpt_id == selection.head().excerpt_id
10273                        });
10274                    buffer_highlights
10275                        .next()
10276                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10277                })?
10278            };
10279            if let Some(rename_range) = rename_range {
10280                this.update(&mut cx, |this, cx| {
10281                    let snapshot = cursor_buffer.read(cx).snapshot();
10282                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10283                    let cursor_offset_in_rename_range =
10284                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10285                    let cursor_offset_in_rename_range_end =
10286                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10287
10288                    this.take_rename(false, cx);
10289                    let buffer = this.buffer.read(cx).read(cx);
10290                    let cursor_offset = selection.head().to_offset(&buffer);
10291                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10292                    let rename_end = rename_start + rename_buffer_range.len();
10293                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10294                    let mut old_highlight_id = None;
10295                    let old_name: Arc<str> = buffer
10296                        .chunks(rename_start..rename_end, true)
10297                        .map(|chunk| {
10298                            if old_highlight_id.is_none() {
10299                                old_highlight_id = chunk.syntax_highlight_id;
10300                            }
10301                            chunk.text
10302                        })
10303                        .collect::<String>()
10304                        .into();
10305
10306                    drop(buffer);
10307
10308                    // Position the selection in the rename editor so that it matches the current selection.
10309                    this.show_local_selections = false;
10310                    let rename_editor = cx.new_view(|cx| {
10311                        let mut editor = Editor::single_line(cx);
10312                        editor.buffer.update(cx, |buffer, cx| {
10313                            buffer.edit([(0..0, old_name.clone())], None, cx)
10314                        });
10315                        let rename_selection_range = match cursor_offset_in_rename_range
10316                            .cmp(&cursor_offset_in_rename_range_end)
10317                        {
10318                            Ordering::Equal => {
10319                                editor.select_all(&SelectAll, cx);
10320                                return editor;
10321                            }
10322                            Ordering::Less => {
10323                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10324                            }
10325                            Ordering::Greater => {
10326                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10327                            }
10328                        };
10329                        if rename_selection_range.end > old_name.len() {
10330                            editor.select_all(&SelectAll, cx);
10331                        } else {
10332                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10333                                s.select_ranges([rename_selection_range]);
10334                            });
10335                        }
10336                        editor
10337                    });
10338                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10339                        if e == &EditorEvent::Focused {
10340                            cx.emit(EditorEvent::FocusedIn)
10341                        }
10342                    })
10343                    .detach();
10344
10345                    let write_highlights =
10346                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10347                    let read_highlights =
10348                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10349                    let ranges = write_highlights
10350                        .iter()
10351                        .flat_map(|(_, ranges)| ranges.iter())
10352                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10353                        .cloned()
10354                        .collect();
10355
10356                    this.highlight_text::<Rename>(
10357                        ranges,
10358                        HighlightStyle {
10359                            fade_out: Some(0.6),
10360                            ..Default::default()
10361                        },
10362                        cx,
10363                    );
10364                    let rename_focus_handle = rename_editor.focus_handle(cx);
10365                    cx.focus(&rename_focus_handle);
10366                    let block_id = this.insert_blocks(
10367                        [BlockProperties {
10368                            style: BlockStyle::Flex,
10369                            placement: BlockPlacement::Below(range.start),
10370                            height: 1,
10371                            render: Box::new({
10372                                let rename_editor = rename_editor.clone();
10373                                move |cx: &mut BlockContext| {
10374                                    let mut text_style = cx.editor_style.text.clone();
10375                                    if let Some(highlight_style) = old_highlight_id
10376                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10377                                    {
10378                                        text_style = text_style.highlight(highlight_style);
10379                                    }
10380                                    div()
10381                                        .pl(cx.anchor_x)
10382                                        .child(EditorElement::new(
10383                                            &rename_editor,
10384                                            EditorStyle {
10385                                                background: cx.theme().system().transparent,
10386                                                local_player: cx.editor_style.local_player,
10387                                                text: text_style,
10388                                                scrollbar_width: cx.editor_style.scrollbar_width,
10389                                                syntax: cx.editor_style.syntax.clone(),
10390                                                status: cx.editor_style.status.clone(),
10391                                                inlay_hints_style: HighlightStyle {
10392                                                    font_weight: Some(FontWeight::BOLD),
10393                                                    ..make_inlay_hints_style(cx)
10394                                                },
10395                                                suggestions_style: HighlightStyle {
10396                                                    color: Some(cx.theme().status().predictive),
10397                                                    ..HighlightStyle::default()
10398                                                },
10399                                                ..EditorStyle::default()
10400                                            },
10401                                        ))
10402                                        .into_any_element()
10403                                }
10404                            }),
10405                            priority: 0,
10406                        }],
10407                        Some(Autoscroll::fit()),
10408                        cx,
10409                    )[0];
10410                    this.pending_rename = Some(RenameState {
10411                        range,
10412                        old_name,
10413                        editor: rename_editor,
10414                        block_id,
10415                    });
10416                })?;
10417            }
10418
10419            Ok(())
10420        }))
10421    }
10422
10423    pub fn confirm_rename(
10424        &mut self,
10425        _: &ConfirmRename,
10426        cx: &mut ViewContext<Self>,
10427    ) -> Option<Task<Result<()>>> {
10428        let rename = self.take_rename(false, cx)?;
10429        let workspace = self.workspace()?.downgrade();
10430        let (buffer, start) = self
10431            .buffer
10432            .read(cx)
10433            .text_anchor_for_position(rename.range.start, cx)?;
10434        let (end_buffer, _) = self
10435            .buffer
10436            .read(cx)
10437            .text_anchor_for_position(rename.range.end, cx)?;
10438        if buffer != end_buffer {
10439            return None;
10440        }
10441
10442        let old_name = rename.old_name;
10443        let new_name = rename.editor.read(cx).text(cx);
10444
10445        let rename = self.semantics_provider.as_ref()?.perform_rename(
10446            &buffer,
10447            start,
10448            new_name.clone(),
10449            cx,
10450        )?;
10451
10452        Some(cx.spawn(|editor, mut cx| async move {
10453            let project_transaction = rename.await?;
10454            Self::open_project_transaction(
10455                &editor,
10456                workspace,
10457                project_transaction,
10458                format!("Rename: {}{}", old_name, new_name),
10459                cx.clone(),
10460            )
10461            .await?;
10462
10463            editor.update(&mut cx, |editor, cx| {
10464                editor.refresh_document_highlights(cx);
10465            })?;
10466            Ok(())
10467        }))
10468    }
10469
10470    fn take_rename(
10471        &mut self,
10472        moving_cursor: bool,
10473        cx: &mut ViewContext<Self>,
10474    ) -> Option<RenameState> {
10475        let rename = self.pending_rename.take()?;
10476        if rename.editor.focus_handle(cx).is_focused(cx) {
10477            cx.focus(&self.focus_handle);
10478        }
10479
10480        self.remove_blocks(
10481            [rename.block_id].into_iter().collect(),
10482            Some(Autoscroll::fit()),
10483            cx,
10484        );
10485        self.clear_highlights::<Rename>(cx);
10486        self.show_local_selections = true;
10487
10488        if moving_cursor {
10489            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10490                editor.selections.newest::<usize>(cx).head()
10491            });
10492
10493            // Update the selection to match the position of the selection inside
10494            // the rename editor.
10495            let snapshot = self.buffer.read(cx).read(cx);
10496            let rename_range = rename.range.to_offset(&snapshot);
10497            let cursor_in_editor = snapshot
10498                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10499                .min(rename_range.end);
10500            drop(snapshot);
10501
10502            self.change_selections(None, cx, |s| {
10503                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10504            });
10505        } else {
10506            self.refresh_document_highlights(cx);
10507        }
10508
10509        Some(rename)
10510    }
10511
10512    pub fn pending_rename(&self) -> Option<&RenameState> {
10513        self.pending_rename.as_ref()
10514    }
10515
10516    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10517        let project = match &self.project {
10518            Some(project) => project.clone(),
10519            None => return None,
10520        };
10521
10522        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10523    }
10524
10525    fn format_selections(
10526        &mut self,
10527        _: &FormatSelections,
10528        cx: &mut ViewContext<Self>,
10529    ) -> Option<Task<Result<()>>> {
10530        let project = match &self.project {
10531            Some(project) => project.clone(),
10532            None => return None,
10533        };
10534
10535        let selections = self
10536            .selections
10537            .all_adjusted(cx)
10538            .into_iter()
10539            .filter(|s| !s.is_empty())
10540            .collect_vec();
10541
10542        Some(self.perform_format(
10543            project,
10544            FormatTrigger::Manual,
10545            FormatTarget::Ranges(selections),
10546            cx,
10547        ))
10548    }
10549
10550    fn perform_format(
10551        &mut self,
10552        project: Model<Project>,
10553        trigger: FormatTrigger,
10554        target: FormatTarget,
10555        cx: &mut ViewContext<Self>,
10556    ) -> Task<Result<()>> {
10557        let buffer = self.buffer().clone();
10558        let mut buffers = buffer.read(cx).all_buffers();
10559        if trigger == FormatTrigger::Save {
10560            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10561        }
10562
10563        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10564        let format = project.update(cx, |project, cx| {
10565            project.format(buffers, true, trigger, target, cx)
10566        });
10567
10568        cx.spawn(|_, mut cx| async move {
10569            let transaction = futures::select_biased! {
10570                () = timeout => {
10571                    log::warn!("timed out waiting for formatting");
10572                    None
10573                }
10574                transaction = format.log_err().fuse() => transaction,
10575            };
10576
10577            buffer
10578                .update(&mut cx, |buffer, cx| {
10579                    if let Some(transaction) = transaction {
10580                        if !buffer.is_singleton() {
10581                            buffer.push_transaction(&transaction.0, cx);
10582                        }
10583                    }
10584
10585                    cx.notify();
10586                })
10587                .ok();
10588
10589            Ok(())
10590        })
10591    }
10592
10593    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10594        if let Some(project) = self.project.clone() {
10595            self.buffer.update(cx, |multi_buffer, cx| {
10596                project.update(cx, |project, cx| {
10597                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10598                });
10599            })
10600        }
10601    }
10602
10603    fn cancel_language_server_work(
10604        &mut self,
10605        _: &actions::CancelLanguageServerWork,
10606        cx: &mut ViewContext<Self>,
10607    ) {
10608        if let Some(project) = self.project.clone() {
10609            self.buffer.update(cx, |multi_buffer, cx| {
10610                project.update(cx, |project, cx| {
10611                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10612                });
10613            })
10614        }
10615    }
10616
10617    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10618        cx.show_character_palette();
10619    }
10620
10621    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10622        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10623            let buffer = self.buffer.read(cx).snapshot(cx);
10624            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10625            let is_valid = buffer
10626                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10627                .any(|entry| {
10628                    entry.diagnostic.is_primary
10629                        && !entry.range.is_empty()
10630                        && entry.range.start == primary_range_start
10631                        && entry.diagnostic.message == active_diagnostics.primary_message
10632                });
10633
10634            if is_valid != active_diagnostics.is_valid {
10635                active_diagnostics.is_valid = is_valid;
10636                let mut new_styles = HashMap::default();
10637                for (block_id, diagnostic) in &active_diagnostics.blocks {
10638                    new_styles.insert(
10639                        *block_id,
10640                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10641                    );
10642                }
10643                self.display_map.update(cx, |display_map, _cx| {
10644                    display_map.replace_blocks(new_styles)
10645                });
10646            }
10647        }
10648    }
10649
10650    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10651        self.dismiss_diagnostics(cx);
10652        let snapshot = self.snapshot(cx);
10653        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10654            let buffer = self.buffer.read(cx).snapshot(cx);
10655
10656            let mut primary_range = None;
10657            let mut primary_message = None;
10658            let mut group_end = Point::zero();
10659            let diagnostic_group = buffer
10660                .diagnostic_group::<MultiBufferPoint>(group_id)
10661                .filter_map(|entry| {
10662                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10663                        && (entry.range.start.row == entry.range.end.row
10664                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10665                    {
10666                        return None;
10667                    }
10668                    if entry.range.end > group_end {
10669                        group_end = entry.range.end;
10670                    }
10671                    if entry.diagnostic.is_primary {
10672                        primary_range = Some(entry.range.clone());
10673                        primary_message = Some(entry.diagnostic.message.clone());
10674                    }
10675                    Some(entry)
10676                })
10677                .collect::<Vec<_>>();
10678            let primary_range = primary_range?;
10679            let primary_message = primary_message?;
10680            let primary_range =
10681                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10682
10683            let blocks = display_map
10684                .insert_blocks(
10685                    diagnostic_group.iter().map(|entry| {
10686                        let diagnostic = entry.diagnostic.clone();
10687                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10688                        BlockProperties {
10689                            style: BlockStyle::Fixed,
10690                            placement: BlockPlacement::Below(
10691                                buffer.anchor_after(entry.range.start),
10692                            ),
10693                            height: message_height,
10694                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10695                            priority: 0,
10696                        }
10697                    }),
10698                    cx,
10699                )
10700                .into_iter()
10701                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10702                .collect();
10703
10704            Some(ActiveDiagnosticGroup {
10705                primary_range,
10706                primary_message,
10707                group_id,
10708                blocks,
10709                is_valid: true,
10710            })
10711        });
10712        self.active_diagnostics.is_some()
10713    }
10714
10715    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10716        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10717            self.display_map.update(cx, |display_map, cx| {
10718                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10719            });
10720            cx.notify();
10721        }
10722    }
10723
10724    pub fn set_selections_from_remote(
10725        &mut self,
10726        selections: Vec<Selection<Anchor>>,
10727        pending_selection: Option<Selection<Anchor>>,
10728        cx: &mut ViewContext<Self>,
10729    ) {
10730        let old_cursor_position = self.selections.newest_anchor().head();
10731        self.selections.change_with(cx, |s| {
10732            s.select_anchors(selections);
10733            if let Some(pending_selection) = pending_selection {
10734                s.set_pending(pending_selection, SelectMode::Character);
10735            } else {
10736                s.clear_pending();
10737            }
10738        });
10739        self.selections_did_change(false, &old_cursor_position, true, cx);
10740    }
10741
10742    fn push_to_selection_history(&mut self) {
10743        self.selection_history.push(SelectionHistoryEntry {
10744            selections: self.selections.disjoint_anchors(),
10745            select_next_state: self.select_next_state.clone(),
10746            select_prev_state: self.select_prev_state.clone(),
10747            add_selections_state: self.add_selections_state.clone(),
10748        });
10749    }
10750
10751    pub fn transact(
10752        &mut self,
10753        cx: &mut ViewContext<Self>,
10754        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10755    ) -> Option<TransactionId> {
10756        self.start_transaction_at(Instant::now(), cx);
10757        update(self, cx);
10758        self.end_transaction_at(Instant::now(), cx)
10759    }
10760
10761    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10762        self.end_selection(cx);
10763        if let Some(tx_id) = self
10764            .buffer
10765            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10766        {
10767            self.selection_history
10768                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10769            cx.emit(EditorEvent::TransactionBegun {
10770                transaction_id: tx_id,
10771            })
10772        }
10773    }
10774
10775    fn end_transaction_at(
10776        &mut self,
10777        now: Instant,
10778        cx: &mut ViewContext<Self>,
10779    ) -> Option<TransactionId> {
10780        if let Some(transaction_id) = self
10781            .buffer
10782            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10783        {
10784            if let Some((_, end_selections)) =
10785                self.selection_history.transaction_mut(transaction_id)
10786            {
10787                *end_selections = Some(self.selections.disjoint_anchors());
10788            } else {
10789                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10790            }
10791
10792            cx.emit(EditorEvent::Edited { transaction_id });
10793            Some(transaction_id)
10794        } else {
10795            None
10796        }
10797    }
10798
10799    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10800        let selection = self.selections.newest::<Point>(cx);
10801
10802        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10803        let range = if selection.is_empty() {
10804            let point = selection.head().to_display_point(&display_map);
10805            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10806            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10807                .to_point(&display_map);
10808            start..end
10809        } else {
10810            selection.range()
10811        };
10812        if display_map.folds_in_range(range).next().is_some() {
10813            self.unfold_lines(&Default::default(), cx)
10814        } else {
10815            self.fold(&Default::default(), cx)
10816        }
10817    }
10818
10819    pub fn toggle_fold_recursive(
10820        &mut self,
10821        _: &actions::ToggleFoldRecursive,
10822        cx: &mut ViewContext<Self>,
10823    ) {
10824        let selection = self.selections.newest::<Point>(cx);
10825
10826        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10827        let range = if selection.is_empty() {
10828            let point = selection.head().to_display_point(&display_map);
10829            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10830            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10831                .to_point(&display_map);
10832            start..end
10833        } else {
10834            selection.range()
10835        };
10836        if display_map.folds_in_range(range).next().is_some() {
10837            self.unfold_recursive(&Default::default(), cx)
10838        } else {
10839            self.fold_recursive(&Default::default(), cx)
10840        }
10841    }
10842
10843    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10844        let mut fold_ranges = Vec::new();
10845        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10846        let selections = self.selections.all_adjusted(cx);
10847
10848        for selection in selections {
10849            let range = selection.range().sorted();
10850            let buffer_start_row = range.start.row;
10851
10852            if range.start.row != range.end.row {
10853                let mut found = false;
10854                let mut row = range.start.row;
10855                while row <= range.end.row {
10856                    if let Some((foldable_range, fold_text)) =
10857                        { display_map.foldable_range(MultiBufferRow(row)) }
10858                    {
10859                        found = true;
10860                        row = foldable_range.end.row + 1;
10861                        fold_ranges.push((foldable_range, fold_text));
10862                    } else {
10863                        row += 1
10864                    }
10865                }
10866                if found {
10867                    continue;
10868                }
10869            }
10870
10871            for row in (0..=range.start.row).rev() {
10872                if let Some((foldable_range, fold_text)) =
10873                    display_map.foldable_range(MultiBufferRow(row))
10874                {
10875                    if foldable_range.end.row >= buffer_start_row {
10876                        fold_ranges.push((foldable_range, fold_text));
10877                        if row <= range.start.row {
10878                            break;
10879                        }
10880                    }
10881                }
10882            }
10883        }
10884
10885        self.fold_ranges(fold_ranges, true, cx);
10886    }
10887
10888    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10889        let fold_at_level = fold_at.level;
10890        let snapshot = self.buffer.read(cx).snapshot(cx);
10891        let mut fold_ranges = Vec::new();
10892        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10893
10894        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10895            while start_row < end_row {
10896                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10897                    Some(foldable_range) => {
10898                        let nested_start_row = foldable_range.0.start.row + 1;
10899                        let nested_end_row = foldable_range.0.end.row;
10900
10901                        if current_level < fold_at_level {
10902                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10903                        } else if current_level == fold_at_level {
10904                            fold_ranges.push(foldable_range);
10905                        }
10906
10907                        start_row = nested_end_row + 1;
10908                    }
10909                    None => start_row += 1,
10910                }
10911            }
10912        }
10913
10914        self.fold_ranges(fold_ranges, true, cx);
10915    }
10916
10917    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10918        let mut fold_ranges = Vec::new();
10919        let snapshot = self.buffer.read(cx).snapshot(cx);
10920
10921        for row in 0..snapshot.max_buffer_row().0 {
10922            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10923                fold_ranges.push(foldable_range);
10924            }
10925        }
10926
10927        self.fold_ranges(fold_ranges, true, cx);
10928    }
10929
10930    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10931        let mut fold_ranges = Vec::new();
10932        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10933        let selections = self.selections.all_adjusted(cx);
10934
10935        for selection in selections {
10936            let range = selection.range().sorted();
10937            let buffer_start_row = range.start.row;
10938
10939            if range.start.row != range.end.row {
10940                let mut found = false;
10941                for row in range.start.row..=range.end.row {
10942                    if let Some((foldable_range, fold_text)) =
10943                        { display_map.foldable_range(MultiBufferRow(row)) }
10944                    {
10945                        found = true;
10946                        fold_ranges.push((foldable_range, fold_text));
10947                    }
10948                }
10949                if found {
10950                    continue;
10951                }
10952            }
10953
10954            for row in (0..=range.start.row).rev() {
10955                if let Some((foldable_range, fold_text)) =
10956                    display_map.foldable_range(MultiBufferRow(row))
10957                {
10958                    if foldable_range.end.row >= buffer_start_row {
10959                        fold_ranges.push((foldable_range, fold_text));
10960                    } else {
10961                        break;
10962                    }
10963                }
10964            }
10965        }
10966
10967        self.fold_ranges(fold_ranges, true, cx);
10968    }
10969
10970    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10971        let buffer_row = fold_at.buffer_row;
10972        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10973
10974        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10975            let autoscroll = self
10976                .selections
10977                .all::<Point>(cx)
10978                .iter()
10979                .any(|selection| fold_range.overlaps(&selection.range()));
10980
10981            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10982        }
10983    }
10984
10985    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10986        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10987        let buffer = &display_map.buffer_snapshot;
10988        let selections = self.selections.all::<Point>(cx);
10989        let ranges = selections
10990            .iter()
10991            .map(|s| {
10992                let range = s.display_range(&display_map).sorted();
10993                let mut start = range.start.to_point(&display_map);
10994                let mut end = range.end.to_point(&display_map);
10995                start.column = 0;
10996                end.column = buffer.line_len(MultiBufferRow(end.row));
10997                start..end
10998            })
10999            .collect::<Vec<_>>();
11000
11001        self.unfold_ranges(&ranges, true, true, cx);
11002    }
11003
11004    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11005        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11006        let selections = self.selections.all::<Point>(cx);
11007        let ranges = selections
11008            .iter()
11009            .map(|s| {
11010                let mut range = s.display_range(&display_map).sorted();
11011                *range.start.column_mut() = 0;
11012                *range.end.column_mut() = display_map.line_len(range.end.row());
11013                let start = range.start.to_point(&display_map);
11014                let end = range.end.to_point(&display_map);
11015                start..end
11016            })
11017            .collect::<Vec<_>>();
11018
11019        self.unfold_ranges(&ranges, true, true, cx);
11020    }
11021
11022    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11023        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11024
11025        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11026            ..Point::new(
11027                unfold_at.buffer_row.0,
11028                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11029            );
11030
11031        let autoscroll = self
11032            .selections
11033            .all::<Point>(cx)
11034            .iter()
11035            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11036
11037        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11038    }
11039
11040    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11041        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11042        self.unfold_ranges(
11043            &[Point::zero()..display_map.max_point().to_point(&display_map)],
11044            true,
11045            true,
11046            cx,
11047        );
11048    }
11049
11050    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11051        let selections = self.selections.all::<Point>(cx);
11052        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11053        let line_mode = self.selections.line_mode;
11054        let ranges = selections.into_iter().map(|s| {
11055            if line_mode {
11056                let start = Point::new(s.start.row, 0);
11057                let end = Point::new(
11058                    s.end.row,
11059                    display_map
11060                        .buffer_snapshot
11061                        .line_len(MultiBufferRow(s.end.row)),
11062                );
11063                (start..end, display_map.fold_placeholder.clone())
11064            } else {
11065                (s.start..s.end, display_map.fold_placeholder.clone())
11066            }
11067        });
11068        self.fold_ranges(ranges, true, cx);
11069    }
11070
11071    pub fn fold_ranges<T: ToOffset + Clone>(
11072        &mut self,
11073        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11074        auto_scroll: bool,
11075        cx: &mut ViewContext<Self>,
11076    ) {
11077        let mut fold_ranges = Vec::new();
11078        let mut buffers_affected = HashMap::default();
11079        let multi_buffer = self.buffer().read(cx);
11080        for (fold_range, fold_text) in ranges {
11081            if let Some((_, buffer, _)) =
11082                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11083            {
11084                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11085            };
11086            fold_ranges.push((fold_range, fold_text));
11087        }
11088
11089        let mut ranges = fold_ranges.into_iter().peekable();
11090        if ranges.peek().is_some() {
11091            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11092
11093            if auto_scroll {
11094                self.request_autoscroll(Autoscroll::fit(), cx);
11095            }
11096
11097            for buffer in buffers_affected.into_values() {
11098                self.sync_expanded_diff_hunks(buffer, cx);
11099            }
11100
11101            cx.notify();
11102
11103            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11104                // Clear diagnostics block when folding a range that contains it.
11105                let snapshot = self.snapshot(cx);
11106                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11107                    drop(snapshot);
11108                    self.active_diagnostics = Some(active_diagnostics);
11109                    self.dismiss_diagnostics(cx);
11110                } else {
11111                    self.active_diagnostics = Some(active_diagnostics);
11112                }
11113            }
11114
11115            self.scrollbar_marker_state.dirty = true;
11116        }
11117    }
11118
11119    /// Removes any folds whose ranges intersect any of the given ranges.
11120    pub fn unfold_ranges<T: ToOffset + Clone>(
11121        &mut self,
11122        ranges: &[Range<T>],
11123        inclusive: bool,
11124        auto_scroll: bool,
11125        cx: &mut ViewContext<Self>,
11126    ) {
11127        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11128            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11129        });
11130    }
11131
11132    /// Removes any folds with the given ranges.
11133    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11134        &mut self,
11135        ranges: &[Range<T>],
11136        type_id: TypeId,
11137        auto_scroll: bool,
11138        cx: &mut ViewContext<Self>,
11139    ) {
11140        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11141            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11142        });
11143    }
11144
11145    fn remove_folds_with<T: ToOffset + Clone>(
11146        &mut self,
11147        ranges: &[Range<T>],
11148        auto_scroll: bool,
11149        cx: &mut ViewContext<Self>,
11150        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11151    ) {
11152        if ranges.is_empty() {
11153            return;
11154        }
11155
11156        let mut buffers_affected = HashMap::default();
11157        let multi_buffer = self.buffer().read(cx);
11158        for range in ranges {
11159            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11160                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11161            };
11162        }
11163
11164        self.display_map.update(cx, update);
11165        if auto_scroll {
11166            self.request_autoscroll(Autoscroll::fit(), cx);
11167        }
11168
11169        for buffer in buffers_affected.into_values() {
11170            self.sync_expanded_diff_hunks(buffer, cx);
11171        }
11172
11173        cx.notify();
11174        self.scrollbar_marker_state.dirty = true;
11175        self.active_indent_guides_state.dirty = true;
11176    }
11177
11178    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11179        self.display_map.read(cx).fold_placeholder.clone()
11180    }
11181
11182    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11183        if hovered != self.gutter_hovered {
11184            self.gutter_hovered = hovered;
11185            cx.notify();
11186        }
11187    }
11188
11189    pub fn insert_blocks(
11190        &mut self,
11191        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11192        autoscroll: Option<Autoscroll>,
11193        cx: &mut ViewContext<Self>,
11194    ) -> Vec<CustomBlockId> {
11195        let blocks = self
11196            .display_map
11197            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11198        if let Some(autoscroll) = autoscroll {
11199            self.request_autoscroll(autoscroll, cx);
11200        }
11201        cx.notify();
11202        blocks
11203    }
11204
11205    pub fn resize_blocks(
11206        &mut self,
11207        heights: HashMap<CustomBlockId, u32>,
11208        autoscroll: Option<Autoscroll>,
11209        cx: &mut ViewContext<Self>,
11210    ) {
11211        self.display_map
11212            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11213        if let Some(autoscroll) = autoscroll {
11214            self.request_autoscroll(autoscroll, cx);
11215        }
11216        cx.notify();
11217    }
11218
11219    pub fn replace_blocks(
11220        &mut self,
11221        renderers: HashMap<CustomBlockId, RenderBlock>,
11222        autoscroll: Option<Autoscroll>,
11223        cx: &mut ViewContext<Self>,
11224    ) {
11225        self.display_map
11226            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11227        if let Some(autoscroll) = autoscroll {
11228            self.request_autoscroll(autoscroll, cx);
11229        }
11230        cx.notify();
11231    }
11232
11233    pub fn remove_blocks(
11234        &mut self,
11235        block_ids: HashSet<CustomBlockId>,
11236        autoscroll: Option<Autoscroll>,
11237        cx: &mut ViewContext<Self>,
11238    ) {
11239        self.display_map.update(cx, |display_map, cx| {
11240            display_map.remove_blocks(block_ids, cx)
11241        });
11242        if let Some(autoscroll) = autoscroll {
11243            self.request_autoscroll(autoscroll, cx);
11244        }
11245        cx.notify();
11246    }
11247
11248    pub fn row_for_block(
11249        &self,
11250        block_id: CustomBlockId,
11251        cx: &mut ViewContext<Self>,
11252    ) -> Option<DisplayRow> {
11253        self.display_map
11254            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11255    }
11256
11257    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11258        self.focused_block = Some(focused_block);
11259    }
11260
11261    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11262        self.focused_block.take()
11263    }
11264
11265    pub fn insert_creases(
11266        &mut self,
11267        creases: impl IntoIterator<Item = Crease>,
11268        cx: &mut ViewContext<Self>,
11269    ) -> Vec<CreaseId> {
11270        self.display_map
11271            .update(cx, |map, cx| map.insert_creases(creases, cx))
11272    }
11273
11274    pub fn remove_creases(
11275        &mut self,
11276        ids: impl IntoIterator<Item = CreaseId>,
11277        cx: &mut ViewContext<Self>,
11278    ) {
11279        self.display_map
11280            .update(cx, |map, cx| map.remove_creases(ids, cx));
11281    }
11282
11283    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11284        self.display_map
11285            .update(cx, |map, cx| map.snapshot(cx))
11286            .longest_row()
11287    }
11288
11289    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11290        self.display_map
11291            .update(cx, |map, cx| map.snapshot(cx))
11292            .max_point()
11293    }
11294
11295    pub fn text(&self, cx: &AppContext) -> String {
11296        self.buffer.read(cx).read(cx).text()
11297    }
11298
11299    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11300        let text = self.text(cx);
11301        let text = text.trim();
11302
11303        if text.is_empty() {
11304            return None;
11305        }
11306
11307        Some(text.to_string())
11308    }
11309
11310    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11311        self.transact(cx, |this, cx| {
11312            this.buffer
11313                .read(cx)
11314                .as_singleton()
11315                .expect("you can only call set_text on editors for singleton buffers")
11316                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11317        });
11318    }
11319
11320    pub fn display_text(&self, cx: &mut AppContext) -> String {
11321        self.display_map
11322            .update(cx, |map, cx| map.snapshot(cx))
11323            .text()
11324    }
11325
11326    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11327        let mut wrap_guides = smallvec::smallvec![];
11328
11329        if self.show_wrap_guides == Some(false) {
11330            return wrap_guides;
11331        }
11332
11333        let settings = self.buffer.read(cx).settings_at(0, cx);
11334        if settings.show_wrap_guides {
11335            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11336                wrap_guides.push((soft_wrap as usize, true));
11337            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11338                wrap_guides.push((soft_wrap as usize, true));
11339            }
11340            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11341        }
11342
11343        wrap_guides
11344    }
11345
11346    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11347        let settings = self.buffer.read(cx).settings_at(0, cx);
11348        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11349        match mode {
11350            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11351                SoftWrap::None
11352            }
11353            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11354            language_settings::SoftWrap::PreferredLineLength => {
11355                SoftWrap::Column(settings.preferred_line_length)
11356            }
11357            language_settings::SoftWrap::Bounded => {
11358                SoftWrap::Bounded(settings.preferred_line_length)
11359            }
11360        }
11361    }
11362
11363    pub fn set_soft_wrap_mode(
11364        &mut self,
11365        mode: language_settings::SoftWrap,
11366        cx: &mut ViewContext<Self>,
11367    ) {
11368        self.soft_wrap_mode_override = Some(mode);
11369        cx.notify();
11370    }
11371
11372    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11373        self.text_style_refinement = Some(style);
11374    }
11375
11376    /// called by the Element so we know what style we were most recently rendered with.
11377    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11378        let rem_size = cx.rem_size();
11379        self.display_map.update(cx, |map, cx| {
11380            map.set_font(
11381                style.text.font(),
11382                style.text.font_size.to_pixels(rem_size),
11383                cx,
11384            )
11385        });
11386        self.style = Some(style);
11387    }
11388
11389    pub fn style(&self) -> Option<&EditorStyle> {
11390        self.style.as_ref()
11391    }
11392
11393    // Called by the element. This method is not designed to be called outside of the editor
11394    // element's layout code because it does not notify when rewrapping is computed synchronously.
11395    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11396        self.display_map
11397            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11398    }
11399
11400    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11401        if self.soft_wrap_mode_override.is_some() {
11402            self.soft_wrap_mode_override.take();
11403        } else {
11404            let soft_wrap = match self.soft_wrap_mode(cx) {
11405                SoftWrap::GitDiff => return,
11406                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11407                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11408                    language_settings::SoftWrap::None
11409                }
11410            };
11411            self.soft_wrap_mode_override = Some(soft_wrap);
11412        }
11413        cx.notify();
11414    }
11415
11416    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11417        let Some(workspace) = self.workspace() else {
11418            return;
11419        };
11420        let fs = workspace.read(cx).app_state().fs.clone();
11421        let current_show = TabBarSettings::get_global(cx).show;
11422        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11423            setting.show = Some(!current_show);
11424        });
11425    }
11426
11427    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11428        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11429            self.buffer
11430                .read(cx)
11431                .settings_at(0, cx)
11432                .indent_guides
11433                .enabled
11434        });
11435        self.show_indent_guides = Some(!currently_enabled);
11436        cx.notify();
11437    }
11438
11439    fn should_show_indent_guides(&self) -> Option<bool> {
11440        self.show_indent_guides
11441    }
11442
11443    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11444        let mut editor_settings = EditorSettings::get_global(cx).clone();
11445        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11446        EditorSettings::override_global(editor_settings, cx);
11447    }
11448
11449    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11450        self.use_relative_line_numbers
11451            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11452    }
11453
11454    pub fn toggle_relative_line_numbers(
11455        &mut self,
11456        _: &ToggleRelativeLineNumbers,
11457        cx: &mut ViewContext<Self>,
11458    ) {
11459        let is_relative = self.should_use_relative_line_numbers(cx);
11460        self.set_relative_line_number(Some(!is_relative), cx)
11461    }
11462
11463    pub fn set_relative_line_number(
11464        &mut self,
11465        is_relative: Option<bool>,
11466        cx: &mut ViewContext<Self>,
11467    ) {
11468        self.use_relative_line_numbers = is_relative;
11469        cx.notify();
11470    }
11471
11472    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11473        self.show_gutter = show_gutter;
11474        cx.notify();
11475    }
11476
11477    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11478        self.show_line_numbers = Some(show_line_numbers);
11479        cx.notify();
11480    }
11481
11482    pub fn set_show_git_diff_gutter(
11483        &mut self,
11484        show_git_diff_gutter: bool,
11485        cx: &mut ViewContext<Self>,
11486    ) {
11487        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11488        cx.notify();
11489    }
11490
11491    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11492        self.show_code_actions = Some(show_code_actions);
11493        cx.notify();
11494    }
11495
11496    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11497        self.show_runnables = Some(show_runnables);
11498        cx.notify();
11499    }
11500
11501    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11502        if self.display_map.read(cx).masked != masked {
11503            self.display_map.update(cx, |map, _| map.masked = masked);
11504        }
11505        cx.notify()
11506    }
11507
11508    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11509        self.show_wrap_guides = Some(show_wrap_guides);
11510        cx.notify();
11511    }
11512
11513    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11514        self.show_indent_guides = Some(show_indent_guides);
11515        cx.notify();
11516    }
11517
11518    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11519        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11520            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11521                if let Some(dir) = file.abs_path(cx).parent() {
11522                    return Some(dir.to_owned());
11523                }
11524            }
11525
11526            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11527                return Some(project_path.path.to_path_buf());
11528            }
11529        }
11530
11531        None
11532    }
11533
11534    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11535        self.active_excerpt(cx)?
11536            .1
11537            .read(cx)
11538            .file()
11539            .and_then(|f| f.as_local())
11540    }
11541
11542    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11543        if let Some(target) = self.target_file(cx) {
11544            cx.reveal_path(&target.abs_path(cx));
11545        }
11546    }
11547
11548    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11549        if let Some(file) = self.target_file(cx) {
11550            if let Some(path) = file.abs_path(cx).to_str() {
11551                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11552            }
11553        }
11554    }
11555
11556    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11557        if let Some(file) = self.target_file(cx) {
11558            if let Some(path) = file.path().to_str() {
11559                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11560            }
11561        }
11562    }
11563
11564    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11565        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11566
11567        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11568            self.start_git_blame(true, cx);
11569        }
11570
11571        cx.notify();
11572    }
11573
11574    pub fn toggle_git_blame_inline(
11575        &mut self,
11576        _: &ToggleGitBlameInline,
11577        cx: &mut ViewContext<Self>,
11578    ) {
11579        self.toggle_git_blame_inline_internal(true, cx);
11580        cx.notify();
11581    }
11582
11583    pub fn git_blame_inline_enabled(&self) -> bool {
11584        self.git_blame_inline_enabled
11585    }
11586
11587    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11588        self.show_selection_menu = self
11589            .show_selection_menu
11590            .map(|show_selections_menu| !show_selections_menu)
11591            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11592
11593        cx.notify();
11594    }
11595
11596    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11597        self.show_selection_menu
11598            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11599    }
11600
11601    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11602        if let Some(project) = self.project.as_ref() {
11603            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11604                return;
11605            };
11606
11607            if buffer.read(cx).file().is_none() {
11608                return;
11609            }
11610
11611            let focused = self.focus_handle(cx).contains_focused(cx);
11612
11613            let project = project.clone();
11614            let blame =
11615                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11616            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11617            self.blame = Some(blame);
11618        }
11619    }
11620
11621    fn toggle_git_blame_inline_internal(
11622        &mut self,
11623        user_triggered: bool,
11624        cx: &mut ViewContext<Self>,
11625    ) {
11626        if self.git_blame_inline_enabled {
11627            self.git_blame_inline_enabled = false;
11628            self.show_git_blame_inline = false;
11629            self.show_git_blame_inline_delay_task.take();
11630        } else {
11631            self.git_blame_inline_enabled = true;
11632            self.start_git_blame_inline(user_triggered, cx);
11633        }
11634
11635        cx.notify();
11636    }
11637
11638    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11639        self.start_git_blame(user_triggered, cx);
11640
11641        if ProjectSettings::get_global(cx)
11642            .git
11643            .inline_blame_delay()
11644            .is_some()
11645        {
11646            self.start_inline_blame_timer(cx);
11647        } else {
11648            self.show_git_blame_inline = true
11649        }
11650    }
11651
11652    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11653        self.blame.as_ref()
11654    }
11655
11656    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11657        self.show_git_blame_gutter && self.has_blame_entries(cx)
11658    }
11659
11660    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11661        self.show_git_blame_inline
11662            && self.focus_handle.is_focused(cx)
11663            && !self.newest_selection_head_on_empty_line(cx)
11664            && self.has_blame_entries(cx)
11665    }
11666
11667    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11668        self.blame()
11669            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11670    }
11671
11672    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11673        let cursor_anchor = self.selections.newest_anchor().head();
11674
11675        let snapshot = self.buffer.read(cx).snapshot(cx);
11676        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11677
11678        snapshot.line_len(buffer_row) == 0
11679    }
11680
11681    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11682        let buffer_and_selection = maybe!({
11683            let selection = self.selections.newest::<Point>(cx);
11684            let selection_range = selection.range();
11685
11686            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11687                (buffer, selection_range.start.row..selection_range.end.row)
11688            } else {
11689                let buffer_ranges = self
11690                    .buffer()
11691                    .read(cx)
11692                    .range_to_buffer_ranges(selection_range, cx);
11693
11694                let (buffer, range, _) = if selection.reversed {
11695                    buffer_ranges.first()
11696                } else {
11697                    buffer_ranges.last()
11698                }?;
11699
11700                let snapshot = buffer.read(cx).snapshot();
11701                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11702                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11703                (buffer.clone(), selection)
11704            };
11705
11706            Some((buffer, selection))
11707        });
11708
11709        let Some((buffer, selection)) = buffer_and_selection else {
11710            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11711        };
11712
11713        let Some(project) = self.project.as_ref() else {
11714            return Task::ready(Err(anyhow!("editor does not have project")));
11715        };
11716
11717        project.update(cx, |project, cx| {
11718            project.get_permalink_to_line(&buffer, selection, cx)
11719        })
11720    }
11721
11722    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11723        let permalink_task = self.get_permalink_to_line(cx);
11724        let workspace = self.workspace();
11725
11726        cx.spawn(|_, mut cx| async move {
11727            match permalink_task.await {
11728                Ok(permalink) => {
11729                    cx.update(|cx| {
11730                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11731                    })
11732                    .ok();
11733                }
11734                Err(err) => {
11735                    let message = format!("Failed to copy permalink: {err}");
11736
11737                    Err::<(), anyhow::Error>(err).log_err();
11738
11739                    if let Some(workspace) = workspace {
11740                        workspace
11741                            .update(&mut cx, |workspace, cx| {
11742                                struct CopyPermalinkToLine;
11743
11744                                workspace.show_toast(
11745                                    Toast::new(
11746                                        NotificationId::unique::<CopyPermalinkToLine>(),
11747                                        message,
11748                                    ),
11749                                    cx,
11750                                )
11751                            })
11752                            .ok();
11753                    }
11754                }
11755            }
11756        })
11757        .detach();
11758    }
11759
11760    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11761        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11762        if let Some(file) = self.target_file(cx) {
11763            if let Some(path) = file.path().to_str() {
11764                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11765            }
11766        }
11767    }
11768
11769    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11770        let permalink_task = self.get_permalink_to_line(cx);
11771        let workspace = self.workspace();
11772
11773        cx.spawn(|_, mut cx| async move {
11774            match permalink_task.await {
11775                Ok(permalink) => {
11776                    cx.update(|cx| {
11777                        cx.open_url(permalink.as_ref());
11778                    })
11779                    .ok();
11780                }
11781                Err(err) => {
11782                    let message = format!("Failed to open permalink: {err}");
11783
11784                    Err::<(), anyhow::Error>(err).log_err();
11785
11786                    if let Some(workspace) = workspace {
11787                        workspace
11788                            .update(&mut cx, |workspace, cx| {
11789                                struct OpenPermalinkToLine;
11790
11791                                workspace.show_toast(
11792                                    Toast::new(
11793                                        NotificationId::unique::<OpenPermalinkToLine>(),
11794                                        message,
11795                                    ),
11796                                    cx,
11797                                )
11798                            })
11799                            .ok();
11800                    }
11801                }
11802            }
11803        })
11804        .detach();
11805    }
11806
11807    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11808    /// last highlight added will be used.
11809    ///
11810    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11811    pub fn highlight_rows<T: 'static>(
11812        &mut self,
11813        range: Range<Anchor>,
11814        color: Hsla,
11815        should_autoscroll: bool,
11816        cx: &mut ViewContext<Self>,
11817    ) {
11818        let snapshot = self.buffer().read(cx).snapshot(cx);
11819        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11820        let ix = row_highlights.binary_search_by(|highlight| {
11821            Ordering::Equal
11822                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11823                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11824        });
11825
11826        if let Err(mut ix) = ix {
11827            let index = post_inc(&mut self.highlight_order);
11828
11829            // If this range intersects with the preceding highlight, then merge it with
11830            // the preceding highlight. Otherwise insert a new highlight.
11831            let mut merged = false;
11832            if ix > 0 {
11833                let prev_highlight = &mut row_highlights[ix - 1];
11834                if prev_highlight
11835                    .range
11836                    .end
11837                    .cmp(&range.start, &snapshot)
11838                    .is_ge()
11839                {
11840                    ix -= 1;
11841                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11842                        prev_highlight.range.end = range.end;
11843                    }
11844                    merged = true;
11845                    prev_highlight.index = index;
11846                    prev_highlight.color = color;
11847                    prev_highlight.should_autoscroll = should_autoscroll;
11848                }
11849            }
11850
11851            if !merged {
11852                row_highlights.insert(
11853                    ix,
11854                    RowHighlight {
11855                        range: range.clone(),
11856                        index,
11857                        color,
11858                        should_autoscroll,
11859                    },
11860                );
11861            }
11862
11863            // If any of the following highlights intersect with this one, merge them.
11864            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11865                let highlight = &row_highlights[ix];
11866                if next_highlight
11867                    .range
11868                    .start
11869                    .cmp(&highlight.range.end, &snapshot)
11870                    .is_le()
11871                {
11872                    if next_highlight
11873                        .range
11874                        .end
11875                        .cmp(&highlight.range.end, &snapshot)
11876                        .is_gt()
11877                    {
11878                        row_highlights[ix].range.end = next_highlight.range.end;
11879                    }
11880                    row_highlights.remove(ix + 1);
11881                } else {
11882                    break;
11883                }
11884            }
11885        }
11886    }
11887
11888    /// Remove any highlighted row ranges of the given type that intersect the
11889    /// given ranges.
11890    pub fn remove_highlighted_rows<T: 'static>(
11891        &mut self,
11892        ranges_to_remove: Vec<Range<Anchor>>,
11893        cx: &mut ViewContext<Self>,
11894    ) {
11895        let snapshot = self.buffer().read(cx).snapshot(cx);
11896        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11897        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11898        row_highlights.retain(|highlight| {
11899            while let Some(range_to_remove) = ranges_to_remove.peek() {
11900                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11901                    Ordering::Less | Ordering::Equal => {
11902                        ranges_to_remove.next();
11903                    }
11904                    Ordering::Greater => {
11905                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11906                            Ordering::Less | Ordering::Equal => {
11907                                return false;
11908                            }
11909                            Ordering::Greater => break,
11910                        }
11911                    }
11912                }
11913            }
11914
11915            true
11916        })
11917    }
11918
11919    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11920    pub fn clear_row_highlights<T: 'static>(&mut self) {
11921        self.highlighted_rows.remove(&TypeId::of::<T>());
11922    }
11923
11924    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11925    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11926        self.highlighted_rows
11927            .get(&TypeId::of::<T>())
11928            .map_or(&[] as &[_], |vec| vec.as_slice())
11929            .iter()
11930            .map(|highlight| (highlight.range.clone(), highlight.color))
11931    }
11932
11933    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11934    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11935    /// Allows to ignore certain kinds of highlights.
11936    pub fn highlighted_display_rows(
11937        &mut self,
11938        cx: &mut WindowContext,
11939    ) -> BTreeMap<DisplayRow, Hsla> {
11940        let snapshot = self.snapshot(cx);
11941        let mut used_highlight_orders = HashMap::default();
11942        self.highlighted_rows
11943            .iter()
11944            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11945            .fold(
11946                BTreeMap::<DisplayRow, Hsla>::new(),
11947                |mut unique_rows, highlight| {
11948                    let start = highlight.range.start.to_display_point(&snapshot);
11949                    let end = highlight.range.end.to_display_point(&snapshot);
11950                    let start_row = start.row().0;
11951                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11952                        && end.column() == 0
11953                    {
11954                        end.row().0.saturating_sub(1)
11955                    } else {
11956                        end.row().0
11957                    };
11958                    for row in start_row..=end_row {
11959                        let used_index =
11960                            used_highlight_orders.entry(row).or_insert(highlight.index);
11961                        if highlight.index >= *used_index {
11962                            *used_index = highlight.index;
11963                            unique_rows.insert(DisplayRow(row), highlight.color);
11964                        }
11965                    }
11966                    unique_rows
11967                },
11968            )
11969    }
11970
11971    pub fn highlighted_display_row_for_autoscroll(
11972        &self,
11973        snapshot: &DisplaySnapshot,
11974    ) -> Option<DisplayRow> {
11975        self.highlighted_rows
11976            .values()
11977            .flat_map(|highlighted_rows| highlighted_rows.iter())
11978            .filter_map(|highlight| {
11979                if highlight.should_autoscroll {
11980                    Some(highlight.range.start.to_display_point(snapshot).row())
11981                } else {
11982                    None
11983                }
11984            })
11985            .min()
11986    }
11987
11988    pub fn set_search_within_ranges(
11989        &mut self,
11990        ranges: &[Range<Anchor>],
11991        cx: &mut ViewContext<Self>,
11992    ) {
11993        self.highlight_background::<SearchWithinRange>(
11994            ranges,
11995            |colors| colors.editor_document_highlight_read_background,
11996            cx,
11997        )
11998    }
11999
12000    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12001        self.breadcrumb_header = Some(new_header);
12002    }
12003
12004    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12005        self.clear_background_highlights::<SearchWithinRange>(cx);
12006    }
12007
12008    pub fn highlight_background<T: 'static>(
12009        &mut self,
12010        ranges: &[Range<Anchor>],
12011        color_fetcher: fn(&ThemeColors) -> Hsla,
12012        cx: &mut ViewContext<Self>,
12013    ) {
12014        self.background_highlights
12015            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12016        self.scrollbar_marker_state.dirty = true;
12017        cx.notify();
12018    }
12019
12020    pub fn clear_background_highlights<T: 'static>(
12021        &mut self,
12022        cx: &mut ViewContext<Self>,
12023    ) -> Option<BackgroundHighlight> {
12024        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12025        if !text_highlights.1.is_empty() {
12026            self.scrollbar_marker_state.dirty = true;
12027            cx.notify();
12028        }
12029        Some(text_highlights)
12030    }
12031
12032    pub fn highlight_gutter<T: 'static>(
12033        &mut self,
12034        ranges: &[Range<Anchor>],
12035        color_fetcher: fn(&AppContext) -> Hsla,
12036        cx: &mut ViewContext<Self>,
12037    ) {
12038        self.gutter_highlights
12039            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12040        cx.notify();
12041    }
12042
12043    pub fn clear_gutter_highlights<T: 'static>(
12044        &mut self,
12045        cx: &mut ViewContext<Self>,
12046    ) -> Option<GutterHighlight> {
12047        cx.notify();
12048        self.gutter_highlights.remove(&TypeId::of::<T>())
12049    }
12050
12051    #[cfg(feature = "test-support")]
12052    pub fn all_text_background_highlights(
12053        &mut self,
12054        cx: &mut ViewContext<Self>,
12055    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12056        let snapshot = self.snapshot(cx);
12057        let buffer = &snapshot.buffer_snapshot;
12058        let start = buffer.anchor_before(0);
12059        let end = buffer.anchor_after(buffer.len());
12060        let theme = cx.theme().colors();
12061        self.background_highlights_in_range(start..end, &snapshot, theme)
12062    }
12063
12064    #[cfg(feature = "test-support")]
12065    pub fn search_background_highlights(
12066        &mut self,
12067        cx: &mut ViewContext<Self>,
12068    ) -> Vec<Range<Point>> {
12069        let snapshot = self.buffer().read(cx).snapshot(cx);
12070
12071        let highlights = self
12072            .background_highlights
12073            .get(&TypeId::of::<items::BufferSearchHighlights>());
12074
12075        if let Some((_color, ranges)) = highlights {
12076            ranges
12077                .iter()
12078                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12079                .collect_vec()
12080        } else {
12081            vec![]
12082        }
12083    }
12084
12085    fn document_highlights_for_position<'a>(
12086        &'a self,
12087        position: Anchor,
12088        buffer: &'a MultiBufferSnapshot,
12089    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12090        let read_highlights = self
12091            .background_highlights
12092            .get(&TypeId::of::<DocumentHighlightRead>())
12093            .map(|h| &h.1);
12094        let write_highlights = self
12095            .background_highlights
12096            .get(&TypeId::of::<DocumentHighlightWrite>())
12097            .map(|h| &h.1);
12098        let left_position = position.bias_left(buffer);
12099        let right_position = position.bias_right(buffer);
12100        read_highlights
12101            .into_iter()
12102            .chain(write_highlights)
12103            .flat_map(move |ranges| {
12104                let start_ix = match ranges.binary_search_by(|probe| {
12105                    let cmp = probe.end.cmp(&left_position, buffer);
12106                    if cmp.is_ge() {
12107                        Ordering::Greater
12108                    } else {
12109                        Ordering::Less
12110                    }
12111                }) {
12112                    Ok(i) | Err(i) => i,
12113                };
12114
12115                ranges[start_ix..]
12116                    .iter()
12117                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12118            })
12119    }
12120
12121    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12122        self.background_highlights
12123            .get(&TypeId::of::<T>())
12124            .map_or(false, |(_, highlights)| !highlights.is_empty())
12125    }
12126
12127    pub fn background_highlights_in_range(
12128        &self,
12129        search_range: Range<Anchor>,
12130        display_snapshot: &DisplaySnapshot,
12131        theme: &ThemeColors,
12132    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12133        let mut results = Vec::new();
12134        for (color_fetcher, ranges) in self.background_highlights.values() {
12135            let color = color_fetcher(theme);
12136            let start_ix = match ranges.binary_search_by(|probe| {
12137                let cmp = probe
12138                    .end
12139                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12140                if cmp.is_gt() {
12141                    Ordering::Greater
12142                } else {
12143                    Ordering::Less
12144                }
12145            }) {
12146                Ok(i) | Err(i) => i,
12147            };
12148            for range in &ranges[start_ix..] {
12149                if range
12150                    .start
12151                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12152                    .is_ge()
12153                {
12154                    break;
12155                }
12156
12157                let start = range.start.to_display_point(display_snapshot);
12158                let end = range.end.to_display_point(display_snapshot);
12159                results.push((start..end, color))
12160            }
12161        }
12162        results
12163    }
12164
12165    pub fn background_highlight_row_ranges<T: 'static>(
12166        &self,
12167        search_range: Range<Anchor>,
12168        display_snapshot: &DisplaySnapshot,
12169        count: usize,
12170    ) -> Vec<RangeInclusive<DisplayPoint>> {
12171        let mut results = Vec::new();
12172        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12173            return vec![];
12174        };
12175
12176        let start_ix = match ranges.binary_search_by(|probe| {
12177            let cmp = probe
12178                .end
12179                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12180            if cmp.is_gt() {
12181                Ordering::Greater
12182            } else {
12183                Ordering::Less
12184            }
12185        }) {
12186            Ok(i) | Err(i) => i,
12187        };
12188        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12189            if let (Some(start_display), Some(end_display)) = (start, end) {
12190                results.push(
12191                    start_display.to_display_point(display_snapshot)
12192                        ..=end_display.to_display_point(display_snapshot),
12193                );
12194            }
12195        };
12196        let mut start_row: Option<Point> = None;
12197        let mut end_row: Option<Point> = None;
12198        if ranges.len() > count {
12199            return Vec::new();
12200        }
12201        for range in &ranges[start_ix..] {
12202            if range
12203                .start
12204                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12205                .is_ge()
12206            {
12207                break;
12208            }
12209            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12210            if let Some(current_row) = &end_row {
12211                if end.row == current_row.row {
12212                    continue;
12213                }
12214            }
12215            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12216            if start_row.is_none() {
12217                assert_eq!(end_row, None);
12218                start_row = Some(start);
12219                end_row = Some(end);
12220                continue;
12221            }
12222            if let Some(current_end) = end_row.as_mut() {
12223                if start.row > current_end.row + 1 {
12224                    push_region(start_row, end_row);
12225                    start_row = Some(start);
12226                    end_row = Some(end);
12227                } else {
12228                    // Merge two hunks.
12229                    *current_end = end;
12230                }
12231            } else {
12232                unreachable!();
12233            }
12234        }
12235        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12236        push_region(start_row, end_row);
12237        results
12238    }
12239
12240    pub fn gutter_highlights_in_range(
12241        &self,
12242        search_range: Range<Anchor>,
12243        display_snapshot: &DisplaySnapshot,
12244        cx: &AppContext,
12245    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12246        let mut results = Vec::new();
12247        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12248            let color = color_fetcher(cx);
12249            let start_ix = match ranges.binary_search_by(|probe| {
12250                let cmp = probe
12251                    .end
12252                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12253                if cmp.is_gt() {
12254                    Ordering::Greater
12255                } else {
12256                    Ordering::Less
12257                }
12258            }) {
12259                Ok(i) | Err(i) => i,
12260            };
12261            for range in &ranges[start_ix..] {
12262                if range
12263                    .start
12264                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12265                    .is_ge()
12266                {
12267                    break;
12268                }
12269
12270                let start = range.start.to_display_point(display_snapshot);
12271                let end = range.end.to_display_point(display_snapshot);
12272                results.push((start..end, color))
12273            }
12274        }
12275        results
12276    }
12277
12278    /// Get the text ranges corresponding to the redaction query
12279    pub fn redacted_ranges(
12280        &self,
12281        search_range: Range<Anchor>,
12282        display_snapshot: &DisplaySnapshot,
12283        cx: &WindowContext,
12284    ) -> Vec<Range<DisplayPoint>> {
12285        display_snapshot
12286            .buffer_snapshot
12287            .redacted_ranges(search_range, |file| {
12288                if let Some(file) = file {
12289                    file.is_private()
12290                        && EditorSettings::get(
12291                            Some(SettingsLocation {
12292                                worktree_id: file.worktree_id(cx),
12293                                path: file.path().as_ref(),
12294                            }),
12295                            cx,
12296                        )
12297                        .redact_private_values
12298                } else {
12299                    false
12300                }
12301            })
12302            .map(|range| {
12303                range.start.to_display_point(display_snapshot)
12304                    ..range.end.to_display_point(display_snapshot)
12305            })
12306            .collect()
12307    }
12308
12309    pub fn highlight_text<T: 'static>(
12310        &mut self,
12311        ranges: Vec<Range<Anchor>>,
12312        style: HighlightStyle,
12313        cx: &mut ViewContext<Self>,
12314    ) {
12315        self.display_map.update(cx, |map, _| {
12316            map.highlight_text(TypeId::of::<T>(), ranges, style)
12317        });
12318        cx.notify();
12319    }
12320
12321    pub(crate) fn highlight_inlays<T: 'static>(
12322        &mut self,
12323        highlights: Vec<InlayHighlight>,
12324        style: HighlightStyle,
12325        cx: &mut ViewContext<Self>,
12326    ) {
12327        self.display_map.update(cx, |map, _| {
12328            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12329        });
12330        cx.notify();
12331    }
12332
12333    pub fn text_highlights<'a, T: 'static>(
12334        &'a self,
12335        cx: &'a AppContext,
12336    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12337        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12338    }
12339
12340    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12341        let cleared = self
12342            .display_map
12343            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12344        if cleared {
12345            cx.notify();
12346        }
12347    }
12348
12349    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12350        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12351            && self.focus_handle.is_focused(cx)
12352    }
12353
12354    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12355        self.show_cursor_when_unfocused = is_enabled;
12356        cx.notify();
12357    }
12358
12359    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12360        cx.notify();
12361    }
12362
12363    fn on_buffer_event(
12364        &mut self,
12365        multibuffer: Model<MultiBuffer>,
12366        event: &multi_buffer::Event,
12367        cx: &mut ViewContext<Self>,
12368    ) {
12369        match event {
12370            multi_buffer::Event::Edited {
12371                singleton_buffer_edited,
12372            } => {
12373                self.scrollbar_marker_state.dirty = true;
12374                self.active_indent_guides_state.dirty = true;
12375                self.refresh_active_diagnostics(cx);
12376                self.refresh_code_actions(cx);
12377                if self.has_active_inline_completion(cx) {
12378                    self.update_visible_inline_completion(cx);
12379                }
12380                cx.emit(EditorEvent::BufferEdited);
12381                cx.emit(SearchEvent::MatchesInvalidated);
12382                if *singleton_buffer_edited {
12383                    if let Some(project) = &self.project {
12384                        let project = project.read(cx);
12385                        #[allow(clippy::mutable_key_type)]
12386                        let languages_affected = multibuffer
12387                            .read(cx)
12388                            .all_buffers()
12389                            .into_iter()
12390                            .filter_map(|buffer| {
12391                                let buffer = buffer.read(cx);
12392                                let language = buffer.language()?;
12393                                if project.is_local()
12394                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12395                                {
12396                                    None
12397                                } else {
12398                                    Some(language)
12399                                }
12400                            })
12401                            .cloned()
12402                            .collect::<HashSet<_>>();
12403                        if !languages_affected.is_empty() {
12404                            self.refresh_inlay_hints(
12405                                InlayHintRefreshReason::BufferEdited(languages_affected),
12406                                cx,
12407                            );
12408                        }
12409                    }
12410                }
12411
12412                let Some(project) = &self.project else { return };
12413                let (telemetry, is_via_ssh) = {
12414                    let project = project.read(cx);
12415                    let telemetry = project.client().telemetry().clone();
12416                    let is_via_ssh = project.is_via_ssh();
12417                    (telemetry, is_via_ssh)
12418                };
12419                refresh_linked_ranges(self, cx);
12420                telemetry.log_edit_event("editor", is_via_ssh);
12421            }
12422            multi_buffer::Event::ExcerptsAdded {
12423                buffer,
12424                predecessor,
12425                excerpts,
12426            } => {
12427                self.tasks_update_task = Some(self.refresh_runnables(cx));
12428                cx.emit(EditorEvent::ExcerptsAdded {
12429                    buffer: buffer.clone(),
12430                    predecessor: *predecessor,
12431                    excerpts: excerpts.clone(),
12432                });
12433                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12434            }
12435            multi_buffer::Event::ExcerptsRemoved { ids } => {
12436                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12437                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12438            }
12439            multi_buffer::Event::ExcerptsEdited { ids } => {
12440                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12441            }
12442            multi_buffer::Event::ExcerptsExpanded { ids } => {
12443                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12444            }
12445            multi_buffer::Event::Reparsed(buffer_id) => {
12446                self.tasks_update_task = Some(self.refresh_runnables(cx));
12447
12448                cx.emit(EditorEvent::Reparsed(*buffer_id));
12449            }
12450            multi_buffer::Event::LanguageChanged(buffer_id) => {
12451                linked_editing_ranges::refresh_linked_ranges(self, cx);
12452                cx.emit(EditorEvent::Reparsed(*buffer_id));
12453                cx.notify();
12454            }
12455            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12456            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12457            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12458                cx.emit(EditorEvent::TitleChanged)
12459            }
12460            multi_buffer::Event::DiffBaseChanged => {
12461                self.scrollbar_marker_state.dirty = true;
12462                cx.emit(EditorEvent::DiffBaseChanged);
12463                cx.notify();
12464            }
12465            multi_buffer::Event::DiffUpdated { buffer } => {
12466                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12467                cx.notify();
12468            }
12469            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12470            multi_buffer::Event::DiagnosticsUpdated => {
12471                self.refresh_active_diagnostics(cx);
12472                self.scrollbar_marker_state.dirty = true;
12473                cx.notify();
12474            }
12475            _ => {}
12476        };
12477    }
12478
12479    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12480        cx.notify();
12481    }
12482
12483    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12484        self.tasks_update_task = Some(self.refresh_runnables(cx));
12485        self.refresh_inline_completion(true, false, cx);
12486        self.refresh_inlay_hints(
12487            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12488                self.selections.newest_anchor().head(),
12489                &self.buffer.read(cx).snapshot(cx),
12490                cx,
12491            )),
12492            cx,
12493        );
12494
12495        let old_cursor_shape = self.cursor_shape;
12496
12497        {
12498            let editor_settings = EditorSettings::get_global(cx);
12499            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12500            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12501            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12502        }
12503
12504        if old_cursor_shape != self.cursor_shape {
12505            cx.emit(EditorEvent::CursorShapeChanged);
12506        }
12507
12508        let project_settings = ProjectSettings::get_global(cx);
12509        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12510
12511        if self.mode == EditorMode::Full {
12512            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12513            if self.git_blame_inline_enabled != inline_blame_enabled {
12514                self.toggle_git_blame_inline_internal(false, cx);
12515            }
12516        }
12517
12518        cx.notify();
12519    }
12520
12521    pub fn set_searchable(&mut self, searchable: bool) {
12522        self.searchable = searchable;
12523    }
12524
12525    pub fn searchable(&self) -> bool {
12526        self.searchable
12527    }
12528
12529    fn open_proposed_changes_editor(
12530        &mut self,
12531        _: &OpenProposedChangesEditor,
12532        cx: &mut ViewContext<Self>,
12533    ) {
12534        let Some(workspace) = self.workspace() else {
12535            cx.propagate();
12536            return;
12537        };
12538
12539        let selections = self.selections.all::<usize>(cx);
12540        let buffer = self.buffer.read(cx);
12541        let mut new_selections_by_buffer = HashMap::default();
12542        for selection in selections {
12543            for (buffer, range, _) in
12544                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12545            {
12546                let mut range = range.to_point(buffer.read(cx));
12547                range.start.column = 0;
12548                range.end.column = buffer.read(cx).line_len(range.end.row);
12549                new_selections_by_buffer
12550                    .entry(buffer)
12551                    .or_insert(Vec::new())
12552                    .push(range)
12553            }
12554        }
12555
12556        let proposed_changes_buffers = new_selections_by_buffer
12557            .into_iter()
12558            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12559            .collect::<Vec<_>>();
12560        let proposed_changes_editor = cx.new_view(|cx| {
12561            ProposedChangesEditor::new(
12562                "Proposed changes",
12563                proposed_changes_buffers,
12564                self.project.clone(),
12565                cx,
12566            )
12567        });
12568
12569        cx.window_context().defer(move |cx| {
12570            workspace.update(cx, |workspace, cx| {
12571                workspace.active_pane().update(cx, |pane, cx| {
12572                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12573                });
12574            });
12575        });
12576    }
12577
12578    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12579        self.open_excerpts_common(true, cx)
12580    }
12581
12582    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12583        self.open_excerpts_common(false, cx)
12584    }
12585
12586    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12587        let selections = self.selections.all::<usize>(cx);
12588        let buffer = self.buffer.read(cx);
12589        if buffer.is_singleton() {
12590            cx.propagate();
12591            return;
12592        }
12593
12594        let Some(workspace) = self.workspace() else {
12595            cx.propagate();
12596            return;
12597        };
12598
12599        let mut new_selections_by_buffer = HashMap::default();
12600        for selection in selections {
12601            for (mut buffer_handle, mut range, _) in
12602                buffer.range_to_buffer_ranges(selection.range(), cx)
12603            {
12604                // When editing branch buffers, jump to the corresponding location
12605                // in their base buffer.
12606                let buffer = buffer_handle.read(cx);
12607                if let Some(base_buffer) = buffer.diff_base_buffer() {
12608                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12609                    buffer_handle = base_buffer;
12610                }
12611
12612                if selection.reversed {
12613                    mem::swap(&mut range.start, &mut range.end);
12614                }
12615                new_selections_by_buffer
12616                    .entry(buffer_handle)
12617                    .or_insert(Vec::new())
12618                    .push(range)
12619            }
12620        }
12621
12622        // We defer the pane interaction because we ourselves are a workspace item
12623        // and activating a new item causes the pane to call a method on us reentrantly,
12624        // which panics if we're on the stack.
12625        cx.window_context().defer(move |cx| {
12626            workspace.update(cx, |workspace, cx| {
12627                let pane = if split {
12628                    workspace.adjacent_pane(cx)
12629                } else {
12630                    workspace.active_pane().clone()
12631                };
12632
12633                for (buffer, ranges) in new_selections_by_buffer {
12634                    let editor =
12635                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12636                    editor.update(cx, |editor, cx| {
12637                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12638                            s.select_ranges(ranges);
12639                        });
12640                    });
12641                }
12642            })
12643        });
12644    }
12645
12646    fn jump(
12647        &mut self,
12648        path: ProjectPath,
12649        position: Point,
12650        anchor: language::Anchor,
12651        offset_from_top: u32,
12652        cx: &mut ViewContext<Self>,
12653    ) {
12654        let workspace = self.workspace();
12655        cx.spawn(|_, mut cx| async move {
12656            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12657            let editor = workspace.update(&mut cx, |workspace, cx| {
12658                // Reset the preview item id before opening the new item
12659                workspace.active_pane().update(cx, |pane, cx| {
12660                    pane.set_preview_item_id(None, cx);
12661                });
12662                workspace.open_path_preview(path, None, true, true, cx)
12663            })?;
12664            let editor = editor
12665                .await?
12666                .downcast::<Editor>()
12667                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12668                .downgrade();
12669            editor.update(&mut cx, |editor, cx| {
12670                let buffer = editor
12671                    .buffer()
12672                    .read(cx)
12673                    .as_singleton()
12674                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12675                let buffer = buffer.read(cx);
12676                let cursor = if buffer.can_resolve(&anchor) {
12677                    language::ToPoint::to_point(&anchor, buffer)
12678                } else {
12679                    buffer.clip_point(position, Bias::Left)
12680                };
12681
12682                let nav_history = editor.nav_history.take();
12683                editor.change_selections(
12684                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12685                    cx,
12686                    |s| {
12687                        s.select_ranges([cursor..cursor]);
12688                    },
12689                );
12690                editor.nav_history = nav_history;
12691
12692                anyhow::Ok(())
12693            })??;
12694
12695            anyhow::Ok(())
12696        })
12697        .detach_and_log_err(cx);
12698    }
12699
12700    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12701        let snapshot = self.buffer.read(cx).read(cx);
12702        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12703        Some(
12704            ranges
12705                .iter()
12706                .map(move |range| {
12707                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12708                })
12709                .collect(),
12710        )
12711    }
12712
12713    fn selection_replacement_ranges(
12714        &self,
12715        range: Range<OffsetUtf16>,
12716        cx: &mut AppContext,
12717    ) -> Vec<Range<OffsetUtf16>> {
12718        let selections = self.selections.all::<OffsetUtf16>(cx);
12719        let newest_selection = selections
12720            .iter()
12721            .max_by_key(|selection| selection.id)
12722            .unwrap();
12723        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12724        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12725        let snapshot = self.buffer.read(cx).read(cx);
12726        selections
12727            .into_iter()
12728            .map(|mut selection| {
12729                selection.start.0 =
12730                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12731                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12732                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12733                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12734            })
12735            .collect()
12736    }
12737
12738    fn report_editor_event(
12739        &self,
12740        operation: &'static str,
12741        file_extension: Option<String>,
12742        cx: &AppContext,
12743    ) {
12744        if cfg!(any(test, feature = "test-support")) {
12745            return;
12746        }
12747
12748        let Some(project) = &self.project else { return };
12749
12750        // If None, we are in a file without an extension
12751        let file = self
12752            .buffer
12753            .read(cx)
12754            .as_singleton()
12755            .and_then(|b| b.read(cx).file());
12756        let file_extension = file_extension.or(file
12757            .as_ref()
12758            .and_then(|file| Path::new(file.file_name(cx)).extension())
12759            .and_then(|e| e.to_str())
12760            .map(|a| a.to_string()));
12761
12762        let vim_mode = cx
12763            .global::<SettingsStore>()
12764            .raw_user_settings()
12765            .get("vim_mode")
12766            == Some(&serde_json::Value::Bool(true));
12767
12768        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12769            == language::language_settings::InlineCompletionProvider::Copilot;
12770        let copilot_enabled_for_language = self
12771            .buffer
12772            .read(cx)
12773            .settings_at(0, cx)
12774            .show_inline_completions;
12775
12776        let project = project.read(cx);
12777        let telemetry = project.client().telemetry().clone();
12778        telemetry.report_editor_event(
12779            file_extension,
12780            vim_mode,
12781            operation,
12782            copilot_enabled,
12783            copilot_enabled_for_language,
12784            project.is_via_ssh(),
12785        )
12786    }
12787
12788    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12789    /// with each line being an array of {text, highlight} objects.
12790    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12791        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12792            return;
12793        };
12794
12795        #[derive(Serialize)]
12796        struct Chunk<'a> {
12797            text: String,
12798            highlight: Option<&'a str>,
12799        }
12800
12801        let snapshot = buffer.read(cx).snapshot();
12802        let range = self
12803            .selected_text_range(false, cx)
12804            .and_then(|selection| {
12805                if selection.range.is_empty() {
12806                    None
12807                } else {
12808                    Some(selection.range)
12809                }
12810            })
12811            .unwrap_or_else(|| 0..snapshot.len());
12812
12813        let chunks = snapshot.chunks(range, true);
12814        let mut lines = Vec::new();
12815        let mut line: VecDeque<Chunk> = VecDeque::new();
12816
12817        let Some(style) = self.style.as_ref() else {
12818            return;
12819        };
12820
12821        for chunk in chunks {
12822            let highlight = chunk
12823                .syntax_highlight_id
12824                .and_then(|id| id.name(&style.syntax));
12825            let mut chunk_lines = chunk.text.split('\n').peekable();
12826            while let Some(text) = chunk_lines.next() {
12827                let mut merged_with_last_token = false;
12828                if let Some(last_token) = line.back_mut() {
12829                    if last_token.highlight == highlight {
12830                        last_token.text.push_str(text);
12831                        merged_with_last_token = true;
12832                    }
12833                }
12834
12835                if !merged_with_last_token {
12836                    line.push_back(Chunk {
12837                        text: text.into(),
12838                        highlight,
12839                    });
12840                }
12841
12842                if chunk_lines.peek().is_some() {
12843                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12844                        line.pop_front();
12845                    }
12846                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12847                        line.pop_back();
12848                    }
12849
12850                    lines.push(mem::take(&mut line));
12851                }
12852            }
12853        }
12854
12855        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12856            return;
12857        };
12858        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12859    }
12860
12861    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12862        &self.inlay_hint_cache
12863    }
12864
12865    pub fn replay_insert_event(
12866        &mut self,
12867        text: &str,
12868        relative_utf16_range: Option<Range<isize>>,
12869        cx: &mut ViewContext<Self>,
12870    ) {
12871        if !self.input_enabled {
12872            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12873            return;
12874        }
12875        if let Some(relative_utf16_range) = relative_utf16_range {
12876            let selections = self.selections.all::<OffsetUtf16>(cx);
12877            self.change_selections(None, cx, |s| {
12878                let new_ranges = selections.into_iter().map(|range| {
12879                    let start = OffsetUtf16(
12880                        range
12881                            .head()
12882                            .0
12883                            .saturating_add_signed(relative_utf16_range.start),
12884                    );
12885                    let end = OffsetUtf16(
12886                        range
12887                            .head()
12888                            .0
12889                            .saturating_add_signed(relative_utf16_range.end),
12890                    );
12891                    start..end
12892                });
12893                s.select_ranges(new_ranges);
12894            });
12895        }
12896
12897        self.handle_input(text, cx);
12898    }
12899
12900    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12901        let Some(provider) = self.semantics_provider.as_ref() else {
12902            return false;
12903        };
12904
12905        let mut supports = false;
12906        self.buffer().read(cx).for_each_buffer(|buffer| {
12907            supports |= provider.supports_inlay_hints(buffer, cx);
12908        });
12909        supports
12910    }
12911
12912    pub fn focus(&self, cx: &mut WindowContext) {
12913        cx.focus(&self.focus_handle)
12914    }
12915
12916    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12917        self.focus_handle.is_focused(cx)
12918    }
12919
12920    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12921        cx.emit(EditorEvent::Focused);
12922
12923        if let Some(descendant) = self
12924            .last_focused_descendant
12925            .take()
12926            .and_then(|descendant| descendant.upgrade())
12927        {
12928            cx.focus(&descendant);
12929        } else {
12930            if let Some(blame) = self.blame.as_ref() {
12931                blame.update(cx, GitBlame::focus)
12932            }
12933
12934            self.blink_manager.update(cx, BlinkManager::enable);
12935            self.show_cursor_names(cx);
12936            self.buffer.update(cx, |buffer, cx| {
12937                buffer.finalize_last_transaction(cx);
12938                if self.leader_peer_id.is_none() {
12939                    buffer.set_active_selections(
12940                        &self.selections.disjoint_anchors(),
12941                        self.selections.line_mode,
12942                        self.cursor_shape,
12943                        cx,
12944                    );
12945                }
12946            });
12947        }
12948    }
12949
12950    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12951        cx.emit(EditorEvent::FocusedIn)
12952    }
12953
12954    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12955        if event.blurred != self.focus_handle {
12956            self.last_focused_descendant = Some(event.blurred);
12957        }
12958    }
12959
12960    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12961        self.blink_manager.update(cx, BlinkManager::disable);
12962        self.buffer
12963            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12964
12965        if let Some(blame) = self.blame.as_ref() {
12966            blame.update(cx, GitBlame::blur)
12967        }
12968        if !self.hover_state.focused(cx) {
12969            hide_hover(self, cx);
12970        }
12971
12972        self.hide_context_menu(cx);
12973        cx.emit(EditorEvent::Blurred);
12974        cx.notify();
12975    }
12976
12977    pub fn register_action<A: Action>(
12978        &mut self,
12979        listener: impl Fn(&A, &mut WindowContext) + 'static,
12980    ) -> Subscription {
12981        let id = self.next_editor_action_id.post_inc();
12982        let listener = Arc::new(listener);
12983        self.editor_actions.borrow_mut().insert(
12984            id,
12985            Box::new(move |cx| {
12986                let cx = cx.window_context();
12987                let listener = listener.clone();
12988                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12989                    let action = action.downcast_ref().unwrap();
12990                    if phase == DispatchPhase::Bubble {
12991                        listener(action, cx)
12992                    }
12993                })
12994            }),
12995        );
12996
12997        let editor_actions = self.editor_actions.clone();
12998        Subscription::new(move || {
12999            editor_actions.borrow_mut().remove(&id);
13000        })
13001    }
13002
13003    pub fn file_header_size(&self) -> u32 {
13004        FILE_HEADER_HEIGHT
13005    }
13006
13007    pub fn revert(
13008        &mut self,
13009        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13010        cx: &mut ViewContext<Self>,
13011    ) {
13012        self.buffer().update(cx, |multi_buffer, cx| {
13013            for (buffer_id, changes) in revert_changes {
13014                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13015                    buffer.update(cx, |buffer, cx| {
13016                        buffer.edit(
13017                            changes.into_iter().map(|(range, text)| {
13018                                (range, text.to_string().map(Arc::<str>::from))
13019                            }),
13020                            None,
13021                            cx,
13022                        );
13023                    });
13024                }
13025            }
13026        });
13027        self.change_selections(None, cx, |selections| selections.refresh());
13028    }
13029
13030    pub fn to_pixel_point(
13031        &mut self,
13032        source: multi_buffer::Anchor,
13033        editor_snapshot: &EditorSnapshot,
13034        cx: &mut ViewContext<Self>,
13035    ) -> Option<gpui::Point<Pixels>> {
13036        let source_point = source.to_display_point(editor_snapshot);
13037        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13038    }
13039
13040    pub fn display_to_pixel_point(
13041        &mut self,
13042        source: DisplayPoint,
13043        editor_snapshot: &EditorSnapshot,
13044        cx: &mut ViewContext<Self>,
13045    ) -> Option<gpui::Point<Pixels>> {
13046        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13047        let text_layout_details = self.text_layout_details(cx);
13048        let scroll_top = text_layout_details
13049            .scroll_anchor
13050            .scroll_position(editor_snapshot)
13051            .y;
13052
13053        if source.row().as_f32() < scroll_top.floor() {
13054            return None;
13055        }
13056        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13057        let source_y = line_height * (source.row().as_f32() - scroll_top);
13058        Some(gpui::Point::new(source_x, source_y))
13059    }
13060
13061    pub fn has_active_completions_menu(&self) -> bool {
13062        self.context_menu.read().as_ref().map_or(false, |menu| {
13063            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13064        })
13065    }
13066
13067    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13068        self.addons
13069            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13070    }
13071
13072    pub fn unregister_addon<T: Addon>(&mut self) {
13073        self.addons.remove(&std::any::TypeId::of::<T>());
13074    }
13075
13076    pub fn addon<T: Addon>(&self) -> Option<&T> {
13077        let type_id = std::any::TypeId::of::<T>();
13078        self.addons
13079            .get(&type_id)
13080            .and_then(|item| item.to_any().downcast_ref::<T>())
13081    }
13082}
13083
13084fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13085    let tab_size = tab_size.get() as usize;
13086    let mut width = offset;
13087
13088    for ch in text.chars() {
13089        width += if ch == '\t' {
13090            tab_size - (width % tab_size)
13091        } else {
13092            1
13093        };
13094    }
13095
13096    width - offset
13097}
13098
13099#[cfg(test)]
13100mod tests {
13101    use super::*;
13102
13103    #[test]
13104    fn test_string_size_with_expanded_tabs() {
13105        let nz = |val| NonZeroU32::new(val).unwrap();
13106        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13107        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13108        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13109        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13110        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13111        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13112        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13113        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13114    }
13115}
13116
13117/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13118struct WordBreakingTokenizer<'a> {
13119    input: &'a str,
13120}
13121
13122impl<'a> WordBreakingTokenizer<'a> {
13123    fn new(input: &'a str) -> Self {
13124        Self { input }
13125    }
13126}
13127
13128fn is_char_ideographic(ch: char) -> bool {
13129    use unicode_script::Script::*;
13130    use unicode_script::UnicodeScript;
13131    matches!(ch.script(), Han | Tangut | Yi)
13132}
13133
13134fn is_grapheme_ideographic(text: &str) -> bool {
13135    text.chars().any(is_char_ideographic)
13136}
13137
13138fn is_grapheme_whitespace(text: &str) -> bool {
13139    text.chars().any(|x| x.is_whitespace())
13140}
13141
13142fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13143    text.chars().next().map_or(false, |ch| {
13144        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13145    })
13146}
13147
13148#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13149struct WordBreakToken<'a> {
13150    token: &'a str,
13151    grapheme_len: usize,
13152    is_whitespace: bool,
13153}
13154
13155impl<'a> Iterator for WordBreakingTokenizer<'a> {
13156    /// Yields a span, the count of graphemes in the token, and whether it was
13157    /// whitespace. Note that it also breaks at word boundaries.
13158    type Item = WordBreakToken<'a>;
13159
13160    fn next(&mut self) -> Option<Self::Item> {
13161        use unicode_segmentation::UnicodeSegmentation;
13162        if self.input.is_empty() {
13163            return None;
13164        }
13165
13166        let mut iter = self.input.graphemes(true).peekable();
13167        let mut offset = 0;
13168        let mut graphemes = 0;
13169        if let Some(first_grapheme) = iter.next() {
13170            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13171            offset += first_grapheme.len();
13172            graphemes += 1;
13173            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13174                if let Some(grapheme) = iter.peek().copied() {
13175                    if should_stay_with_preceding_ideograph(grapheme) {
13176                        offset += grapheme.len();
13177                        graphemes += 1;
13178                    }
13179                }
13180            } else {
13181                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13182                let mut next_word_bound = words.peek().copied();
13183                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13184                    next_word_bound = words.next();
13185                }
13186                while let Some(grapheme) = iter.peek().copied() {
13187                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13188                        break;
13189                    };
13190                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13191                        break;
13192                    };
13193                    offset += grapheme.len();
13194                    graphemes += 1;
13195                    iter.next();
13196                }
13197            }
13198            let token = &self.input[..offset];
13199            self.input = &self.input[offset..];
13200            if is_whitespace {
13201                Some(WordBreakToken {
13202                    token: " ",
13203                    grapheme_len: 1,
13204                    is_whitespace: true,
13205                })
13206            } else {
13207                Some(WordBreakToken {
13208                    token,
13209                    grapheme_len: graphemes,
13210                    is_whitespace: false,
13211                })
13212            }
13213        } else {
13214            None
13215        }
13216    }
13217}
13218
13219#[test]
13220fn test_word_breaking_tokenizer() {
13221    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13222        ("", &[]),
13223        ("  ", &[(" ", 1, true)]),
13224        ("Ʒ", &[("Ʒ", 1, false)]),
13225        ("Ǽ", &[("Ǽ", 1, false)]),
13226        ("", &[("", 1, false)]),
13227        ("⋑⋑", &[("⋑⋑", 2, false)]),
13228        (
13229            "原理,进而",
13230            &[
13231                ("", 1, false),
13232                ("理,", 2, false),
13233                ("", 1, false),
13234                ("", 1, false),
13235            ],
13236        ),
13237        (
13238            "hello world",
13239            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13240        ),
13241        (
13242            "hello, world",
13243            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13244        ),
13245        (
13246            "  hello world",
13247            &[
13248                (" ", 1, true),
13249                ("hello", 5, false),
13250                (" ", 1, true),
13251                ("world", 5, false),
13252            ],
13253        ),
13254        (
13255            "这是什么 \n 钢笔",
13256            &[
13257                ("", 1, false),
13258                ("", 1, false),
13259                ("", 1, false),
13260                ("", 1, false),
13261                (" ", 1, true),
13262                ("", 1, false),
13263                ("", 1, false),
13264            ],
13265        ),
13266        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13267    ];
13268
13269    for (input, result) in tests {
13270        assert_eq!(
13271            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13272            result
13273                .iter()
13274                .copied()
13275                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13276                    token,
13277                    grapheme_len,
13278                    is_whitespace,
13279                })
13280                .collect::<Vec<_>>()
13281        );
13282    }
13283}
13284
13285fn wrap_with_prefix(
13286    line_prefix: String,
13287    unwrapped_text: String,
13288    wrap_column: usize,
13289    tab_size: NonZeroU32,
13290) -> String {
13291    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13292    let mut wrapped_text = String::new();
13293    let mut current_line = line_prefix.clone();
13294
13295    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13296    let mut current_line_len = line_prefix_len;
13297    for WordBreakToken {
13298        token,
13299        grapheme_len,
13300        is_whitespace,
13301    } in tokenizer
13302    {
13303        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13304            wrapped_text.push_str(current_line.trim_end());
13305            wrapped_text.push('\n');
13306            current_line.truncate(line_prefix.len());
13307            current_line_len = line_prefix_len;
13308            if !is_whitespace {
13309                current_line.push_str(token);
13310                current_line_len += grapheme_len;
13311            }
13312        } else if !is_whitespace {
13313            current_line.push_str(token);
13314            current_line_len += grapheme_len;
13315        } else if current_line_len != line_prefix_len {
13316            current_line.push(' ');
13317            current_line_len += 1;
13318        }
13319    }
13320
13321    if !current_line.is_empty() {
13322        wrapped_text.push_str(&current_line);
13323    }
13324    wrapped_text
13325}
13326
13327#[test]
13328fn test_wrap_with_prefix() {
13329    assert_eq!(
13330        wrap_with_prefix(
13331            "# ".to_string(),
13332            "abcdefg".to_string(),
13333            4,
13334            NonZeroU32::new(4).unwrap()
13335        ),
13336        "# abcdefg"
13337    );
13338    assert_eq!(
13339        wrap_with_prefix(
13340            "".to_string(),
13341            "\thello world".to_string(),
13342            8,
13343            NonZeroU32::new(4).unwrap()
13344        ),
13345        "hello\nworld"
13346    );
13347    assert_eq!(
13348        wrap_with_prefix(
13349            "// ".to_string(),
13350            "xx \nyy zz aa bb cc".to_string(),
13351            12,
13352            NonZeroU32::new(4).unwrap()
13353        ),
13354        "// xx yy zz\n// aa bb cc"
13355    );
13356    assert_eq!(
13357        wrap_with_prefix(
13358            String::new(),
13359            "这是什么 \n 钢笔".to_string(),
13360            3,
13361            NonZeroU32::new(4).unwrap()
13362        ),
13363        "这是什\n么 钢\n"
13364    );
13365}
13366
13367fn hunks_for_selections(
13368    multi_buffer_snapshot: &MultiBufferSnapshot,
13369    selections: &[Selection<Anchor>],
13370) -> Vec<MultiBufferDiffHunk> {
13371    let buffer_rows_for_selections = selections.iter().map(|selection| {
13372        let head = selection.head();
13373        let tail = selection.tail();
13374        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13375        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13376        if start > end {
13377            end..start
13378        } else {
13379            start..end
13380        }
13381    });
13382
13383    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13384}
13385
13386pub fn hunks_for_rows(
13387    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13388    multi_buffer_snapshot: &MultiBufferSnapshot,
13389) -> Vec<MultiBufferDiffHunk> {
13390    let mut hunks = Vec::new();
13391    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13392        HashMap::default();
13393    for selected_multi_buffer_rows in rows {
13394        let query_rows =
13395            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13396        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13397            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13398            // when the caret is just above or just below the deleted hunk.
13399            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13400            let related_to_selection = if allow_adjacent {
13401                hunk.row_range.overlaps(&query_rows)
13402                    || hunk.row_range.start == query_rows.end
13403                    || hunk.row_range.end == query_rows.start
13404            } else {
13405                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13406                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13407                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13408                    || selected_multi_buffer_rows.end == hunk.row_range.start
13409            };
13410            if related_to_selection {
13411                if !processed_buffer_rows
13412                    .entry(hunk.buffer_id)
13413                    .or_default()
13414                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13415                {
13416                    continue;
13417                }
13418                hunks.push(hunk);
13419            }
13420        }
13421    }
13422
13423    hunks
13424}
13425
13426pub trait CollaborationHub {
13427    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13428    fn user_participant_indices<'a>(
13429        &self,
13430        cx: &'a AppContext,
13431    ) -> &'a HashMap<u64, ParticipantIndex>;
13432    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13433}
13434
13435impl CollaborationHub for Model<Project> {
13436    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13437        self.read(cx).collaborators()
13438    }
13439
13440    fn user_participant_indices<'a>(
13441        &self,
13442        cx: &'a AppContext,
13443    ) -> &'a HashMap<u64, ParticipantIndex> {
13444        self.read(cx).user_store().read(cx).participant_indices()
13445    }
13446
13447    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13448        let this = self.read(cx);
13449        let user_ids = this.collaborators().values().map(|c| c.user_id);
13450        this.user_store().read_with(cx, |user_store, cx| {
13451            user_store.participant_names(user_ids, cx)
13452        })
13453    }
13454}
13455
13456pub trait SemanticsProvider {
13457    fn hover(
13458        &self,
13459        buffer: &Model<Buffer>,
13460        position: text::Anchor,
13461        cx: &mut AppContext,
13462    ) -> Option<Task<Vec<project::Hover>>>;
13463
13464    fn inlay_hints(
13465        &self,
13466        buffer_handle: Model<Buffer>,
13467        range: Range<text::Anchor>,
13468        cx: &mut AppContext,
13469    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13470
13471    fn resolve_inlay_hint(
13472        &self,
13473        hint: InlayHint,
13474        buffer_handle: Model<Buffer>,
13475        server_id: LanguageServerId,
13476        cx: &mut AppContext,
13477    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13478
13479    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13480
13481    fn document_highlights(
13482        &self,
13483        buffer: &Model<Buffer>,
13484        position: text::Anchor,
13485        cx: &mut AppContext,
13486    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13487
13488    fn definitions(
13489        &self,
13490        buffer: &Model<Buffer>,
13491        position: text::Anchor,
13492        kind: GotoDefinitionKind,
13493        cx: &mut AppContext,
13494    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13495
13496    fn range_for_rename(
13497        &self,
13498        buffer: &Model<Buffer>,
13499        position: text::Anchor,
13500        cx: &mut AppContext,
13501    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13502
13503    fn perform_rename(
13504        &self,
13505        buffer: &Model<Buffer>,
13506        position: text::Anchor,
13507        new_name: String,
13508        cx: &mut AppContext,
13509    ) -> Option<Task<Result<ProjectTransaction>>>;
13510}
13511
13512pub trait CompletionProvider {
13513    fn completions(
13514        &self,
13515        buffer: &Model<Buffer>,
13516        buffer_position: text::Anchor,
13517        trigger: CompletionContext,
13518        cx: &mut ViewContext<Editor>,
13519    ) -> Task<Result<Vec<Completion>>>;
13520
13521    fn resolve_completions(
13522        &self,
13523        buffer: Model<Buffer>,
13524        completion_indices: Vec<usize>,
13525        completions: Arc<RwLock<Box<[Completion]>>>,
13526        cx: &mut ViewContext<Editor>,
13527    ) -> Task<Result<bool>>;
13528
13529    fn apply_additional_edits_for_completion(
13530        &self,
13531        buffer: Model<Buffer>,
13532        completion: Completion,
13533        push_to_history: bool,
13534        cx: &mut ViewContext<Editor>,
13535    ) -> Task<Result<Option<language::Transaction>>>;
13536
13537    fn is_completion_trigger(
13538        &self,
13539        buffer: &Model<Buffer>,
13540        position: language::Anchor,
13541        text: &str,
13542        trigger_in_words: bool,
13543        cx: &mut ViewContext<Editor>,
13544    ) -> bool;
13545
13546    fn sort_completions(&self) -> bool {
13547        true
13548    }
13549}
13550
13551pub trait CodeActionProvider {
13552    fn code_actions(
13553        &self,
13554        buffer: &Model<Buffer>,
13555        range: Range<text::Anchor>,
13556        cx: &mut WindowContext,
13557    ) -> Task<Result<Vec<CodeAction>>>;
13558
13559    fn apply_code_action(
13560        &self,
13561        buffer_handle: Model<Buffer>,
13562        action: CodeAction,
13563        excerpt_id: ExcerptId,
13564        push_to_history: bool,
13565        cx: &mut WindowContext,
13566    ) -> Task<Result<ProjectTransaction>>;
13567}
13568
13569impl CodeActionProvider for Model<Project> {
13570    fn code_actions(
13571        &self,
13572        buffer: &Model<Buffer>,
13573        range: Range<text::Anchor>,
13574        cx: &mut WindowContext,
13575    ) -> Task<Result<Vec<CodeAction>>> {
13576        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13577    }
13578
13579    fn apply_code_action(
13580        &self,
13581        buffer_handle: Model<Buffer>,
13582        action: CodeAction,
13583        _excerpt_id: ExcerptId,
13584        push_to_history: bool,
13585        cx: &mut WindowContext,
13586    ) -> Task<Result<ProjectTransaction>> {
13587        self.update(cx, |project, cx| {
13588            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13589        })
13590    }
13591}
13592
13593fn snippet_completions(
13594    project: &Project,
13595    buffer: &Model<Buffer>,
13596    buffer_position: text::Anchor,
13597    cx: &mut AppContext,
13598) -> Vec<Completion> {
13599    let language = buffer.read(cx).language_at(buffer_position);
13600    let language_name = language.as_ref().map(|language| language.lsp_id());
13601    let snippet_store = project.snippets().read(cx);
13602    let snippets = snippet_store.snippets_for(language_name, cx);
13603
13604    if snippets.is_empty() {
13605        return vec![];
13606    }
13607    let snapshot = buffer.read(cx).text_snapshot();
13608    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13609
13610    let scope = language.map(|language| language.default_scope());
13611    let classifier = CharClassifier::new(scope).for_completion(true);
13612    let mut last_word = chars
13613        .take_while(|c| classifier.is_word(*c))
13614        .collect::<String>();
13615    last_word = last_word.chars().rev().collect();
13616    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13617    let to_lsp = |point: &text::Anchor| {
13618        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13619        point_to_lsp(end)
13620    };
13621    let lsp_end = to_lsp(&buffer_position);
13622    snippets
13623        .into_iter()
13624        .filter_map(|snippet| {
13625            let matching_prefix = snippet
13626                .prefix
13627                .iter()
13628                .find(|prefix| prefix.starts_with(&last_word))?;
13629            let start = as_offset - last_word.len();
13630            let start = snapshot.anchor_before(start);
13631            let range = start..buffer_position;
13632            let lsp_start = to_lsp(&start);
13633            let lsp_range = lsp::Range {
13634                start: lsp_start,
13635                end: lsp_end,
13636            };
13637            Some(Completion {
13638                old_range: range,
13639                new_text: snippet.body.clone(),
13640                label: CodeLabel {
13641                    text: matching_prefix.clone(),
13642                    runs: vec![],
13643                    filter_range: 0..matching_prefix.len(),
13644                },
13645                server_id: LanguageServerId(usize::MAX),
13646                documentation: snippet.description.clone().map(Documentation::SingleLine),
13647                lsp_completion: lsp::CompletionItem {
13648                    label: snippet.prefix.first().unwrap().clone(),
13649                    kind: Some(CompletionItemKind::SNIPPET),
13650                    label_details: snippet.description.as_ref().map(|description| {
13651                        lsp::CompletionItemLabelDetails {
13652                            detail: Some(description.clone()),
13653                            description: None,
13654                        }
13655                    }),
13656                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13657                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13658                        lsp::InsertReplaceEdit {
13659                            new_text: snippet.body.clone(),
13660                            insert: lsp_range,
13661                            replace: lsp_range,
13662                        },
13663                    )),
13664                    filter_text: Some(snippet.body.clone()),
13665                    sort_text: Some(char::MAX.to_string()),
13666                    ..Default::default()
13667                },
13668                confirm: None,
13669            })
13670        })
13671        .collect()
13672}
13673
13674impl CompletionProvider for Model<Project> {
13675    fn completions(
13676        &self,
13677        buffer: &Model<Buffer>,
13678        buffer_position: text::Anchor,
13679        options: CompletionContext,
13680        cx: &mut ViewContext<Editor>,
13681    ) -> Task<Result<Vec<Completion>>> {
13682        self.update(cx, |project, cx| {
13683            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13684            let project_completions = project.completions(buffer, buffer_position, options, cx);
13685            cx.background_executor().spawn(async move {
13686                let mut completions = project_completions.await?;
13687                //let snippets = snippets.into_iter().;
13688                completions.extend(snippets);
13689                Ok(completions)
13690            })
13691        })
13692    }
13693
13694    fn resolve_completions(
13695        &self,
13696        buffer: Model<Buffer>,
13697        completion_indices: Vec<usize>,
13698        completions: Arc<RwLock<Box<[Completion]>>>,
13699        cx: &mut ViewContext<Editor>,
13700    ) -> Task<Result<bool>> {
13701        self.update(cx, |project, cx| {
13702            project.resolve_completions(buffer, completion_indices, completions, cx)
13703        })
13704    }
13705
13706    fn apply_additional_edits_for_completion(
13707        &self,
13708        buffer: Model<Buffer>,
13709        completion: Completion,
13710        push_to_history: bool,
13711        cx: &mut ViewContext<Editor>,
13712    ) -> Task<Result<Option<language::Transaction>>> {
13713        self.update(cx, |project, cx| {
13714            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13715        })
13716    }
13717
13718    fn is_completion_trigger(
13719        &self,
13720        buffer: &Model<Buffer>,
13721        position: language::Anchor,
13722        text: &str,
13723        trigger_in_words: bool,
13724        cx: &mut ViewContext<Editor>,
13725    ) -> bool {
13726        if !EditorSettings::get_global(cx).show_completions_on_input {
13727            return false;
13728        }
13729
13730        let mut chars = text.chars();
13731        let char = if let Some(char) = chars.next() {
13732            char
13733        } else {
13734            return false;
13735        };
13736        if chars.next().is_some() {
13737            return false;
13738        }
13739
13740        let buffer = buffer.read(cx);
13741        let classifier = buffer
13742            .snapshot()
13743            .char_classifier_at(position)
13744            .for_completion(true);
13745        if trigger_in_words && classifier.is_word(char) {
13746            return true;
13747        }
13748
13749        buffer
13750            .completion_triggers()
13751            .iter()
13752            .any(|string| string == text)
13753    }
13754}
13755
13756impl SemanticsProvider for Model<Project> {
13757    fn hover(
13758        &self,
13759        buffer: &Model<Buffer>,
13760        position: text::Anchor,
13761        cx: &mut AppContext,
13762    ) -> Option<Task<Vec<project::Hover>>> {
13763        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13764    }
13765
13766    fn document_highlights(
13767        &self,
13768        buffer: &Model<Buffer>,
13769        position: text::Anchor,
13770        cx: &mut AppContext,
13771    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13772        Some(self.update(cx, |project, cx| {
13773            project.document_highlights(buffer, position, cx)
13774        }))
13775    }
13776
13777    fn definitions(
13778        &self,
13779        buffer: &Model<Buffer>,
13780        position: text::Anchor,
13781        kind: GotoDefinitionKind,
13782        cx: &mut AppContext,
13783    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13784        Some(self.update(cx, |project, cx| match kind {
13785            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13786            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13787            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13788            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13789        }))
13790    }
13791
13792    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13793        // TODO: make this work for remote projects
13794        self.read(cx)
13795            .language_servers_for_buffer(buffer.read(cx), cx)
13796            .any(
13797                |(_, server)| match server.capabilities().inlay_hint_provider {
13798                    Some(lsp::OneOf::Left(enabled)) => enabled,
13799                    Some(lsp::OneOf::Right(_)) => true,
13800                    None => false,
13801                },
13802            )
13803    }
13804
13805    fn inlay_hints(
13806        &self,
13807        buffer_handle: Model<Buffer>,
13808        range: Range<text::Anchor>,
13809        cx: &mut AppContext,
13810    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13811        Some(self.update(cx, |project, cx| {
13812            project.inlay_hints(buffer_handle, range, cx)
13813        }))
13814    }
13815
13816    fn resolve_inlay_hint(
13817        &self,
13818        hint: InlayHint,
13819        buffer_handle: Model<Buffer>,
13820        server_id: LanguageServerId,
13821        cx: &mut AppContext,
13822    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13823        Some(self.update(cx, |project, cx| {
13824            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13825        }))
13826    }
13827
13828    fn range_for_rename(
13829        &self,
13830        buffer: &Model<Buffer>,
13831        position: text::Anchor,
13832        cx: &mut AppContext,
13833    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13834        Some(self.update(cx, |project, cx| {
13835            project.prepare_rename(buffer.clone(), position, cx)
13836        }))
13837    }
13838
13839    fn perform_rename(
13840        &self,
13841        buffer: &Model<Buffer>,
13842        position: text::Anchor,
13843        new_name: String,
13844        cx: &mut AppContext,
13845    ) -> Option<Task<Result<ProjectTransaction>>> {
13846        Some(self.update(cx, |project, cx| {
13847            project.perform_rename(buffer.clone(), position, new_name, cx)
13848        }))
13849    }
13850}
13851
13852fn inlay_hint_settings(
13853    location: Anchor,
13854    snapshot: &MultiBufferSnapshot,
13855    cx: &mut ViewContext<'_, Editor>,
13856) -> InlayHintSettings {
13857    let file = snapshot.file_at(location);
13858    let language = snapshot.language_at(location).map(|l| l.name());
13859    language_settings(language, file, cx).inlay_hints
13860}
13861
13862fn consume_contiguous_rows(
13863    contiguous_row_selections: &mut Vec<Selection<Point>>,
13864    selection: &Selection<Point>,
13865    display_map: &DisplaySnapshot,
13866    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13867) -> (MultiBufferRow, MultiBufferRow) {
13868    contiguous_row_selections.push(selection.clone());
13869    let start_row = MultiBufferRow(selection.start.row);
13870    let mut end_row = ending_row(selection, display_map);
13871
13872    while let Some(next_selection) = selections.peek() {
13873        if next_selection.start.row <= end_row.0 {
13874            end_row = ending_row(next_selection, display_map);
13875            contiguous_row_selections.push(selections.next().unwrap().clone());
13876        } else {
13877            break;
13878        }
13879    }
13880    (start_row, end_row)
13881}
13882
13883fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13884    if next_selection.end.column > 0 || next_selection.is_empty() {
13885        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13886    } else {
13887        MultiBufferRow(next_selection.end.row)
13888    }
13889}
13890
13891impl EditorSnapshot {
13892    pub fn remote_selections_in_range<'a>(
13893        &'a self,
13894        range: &'a Range<Anchor>,
13895        collaboration_hub: &dyn CollaborationHub,
13896        cx: &'a AppContext,
13897    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13898        let participant_names = collaboration_hub.user_names(cx);
13899        let participant_indices = collaboration_hub.user_participant_indices(cx);
13900        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13901        let collaborators_by_replica_id = collaborators_by_peer_id
13902            .iter()
13903            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13904            .collect::<HashMap<_, _>>();
13905        self.buffer_snapshot
13906            .selections_in_range(range, false)
13907            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13908                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13909                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13910                let user_name = participant_names.get(&collaborator.user_id).cloned();
13911                Some(RemoteSelection {
13912                    replica_id,
13913                    selection,
13914                    cursor_shape,
13915                    line_mode,
13916                    participant_index,
13917                    peer_id: collaborator.peer_id,
13918                    user_name,
13919                })
13920            })
13921    }
13922
13923    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13924        self.display_snapshot.buffer_snapshot.language_at(position)
13925    }
13926
13927    pub fn is_focused(&self) -> bool {
13928        self.is_focused
13929    }
13930
13931    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13932        self.placeholder_text.as_ref()
13933    }
13934
13935    pub fn scroll_position(&self) -> gpui::Point<f32> {
13936        self.scroll_anchor.scroll_position(&self.display_snapshot)
13937    }
13938
13939    fn gutter_dimensions(
13940        &self,
13941        font_id: FontId,
13942        font_size: Pixels,
13943        em_width: Pixels,
13944        em_advance: Pixels,
13945        max_line_number_width: Pixels,
13946        cx: &AppContext,
13947    ) -> GutterDimensions {
13948        if !self.show_gutter {
13949            return GutterDimensions::default();
13950        }
13951        let descent = cx.text_system().descent(font_id, font_size);
13952
13953        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13954            matches!(
13955                ProjectSettings::get_global(cx).git.git_gutter,
13956                Some(GitGutterSetting::TrackedFiles)
13957            )
13958        });
13959        let gutter_settings = EditorSettings::get_global(cx).gutter;
13960        let show_line_numbers = self
13961            .show_line_numbers
13962            .unwrap_or(gutter_settings.line_numbers);
13963        let line_gutter_width = if show_line_numbers {
13964            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13965            let min_width_for_number_on_gutter = em_advance * 4.0;
13966            max_line_number_width.max(min_width_for_number_on_gutter)
13967        } else {
13968            0.0.into()
13969        };
13970
13971        let show_code_actions = self
13972            .show_code_actions
13973            .unwrap_or(gutter_settings.code_actions);
13974
13975        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13976
13977        let git_blame_entries_width =
13978            self.git_blame_gutter_max_author_length
13979                .map(|max_author_length| {
13980                    // Length of the author name, but also space for the commit hash,
13981                    // the spacing and the timestamp.
13982                    let max_char_count = max_author_length
13983                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13984                        + 7 // length of commit sha
13985                        + 14 // length of max relative timestamp ("60 minutes ago")
13986                        + 4; // gaps and margins
13987
13988                    em_advance * max_char_count
13989                });
13990
13991        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13992        left_padding += if show_code_actions || show_runnables {
13993            em_width * 3.0
13994        } else if show_git_gutter && show_line_numbers {
13995            em_width * 2.0
13996        } else if show_git_gutter || show_line_numbers {
13997            em_width
13998        } else {
13999            px(0.)
14000        };
14001
14002        let right_padding = if gutter_settings.folds && show_line_numbers {
14003            em_width * 4.0
14004        } else if gutter_settings.folds {
14005            em_width * 3.0
14006        } else if show_line_numbers {
14007            em_width
14008        } else {
14009            px(0.)
14010        };
14011
14012        GutterDimensions {
14013            left_padding,
14014            right_padding,
14015            width: line_gutter_width + left_padding + right_padding,
14016            margin: -descent,
14017            git_blame_entries_width,
14018        }
14019    }
14020
14021    pub fn render_fold_toggle(
14022        &self,
14023        buffer_row: MultiBufferRow,
14024        row_contains_cursor: bool,
14025        editor: View<Editor>,
14026        cx: &mut WindowContext,
14027    ) -> Option<AnyElement> {
14028        let folded = self.is_line_folded(buffer_row);
14029
14030        if let Some(crease) = self
14031            .crease_snapshot
14032            .query_row(buffer_row, &self.buffer_snapshot)
14033        {
14034            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14035                if folded {
14036                    editor.update(cx, |editor, cx| {
14037                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14038                    });
14039                } else {
14040                    editor.update(cx, |editor, cx| {
14041                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14042                    });
14043                }
14044            });
14045
14046            Some((crease.render_toggle)(
14047                buffer_row,
14048                folded,
14049                toggle_callback,
14050                cx,
14051            ))
14052        } else if folded
14053            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14054        {
14055            Some(
14056                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14057                    .selected(folded)
14058                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14059                        if folded {
14060                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14061                        } else {
14062                            this.fold_at(&FoldAt { buffer_row }, cx);
14063                        }
14064                    }))
14065                    .into_any_element(),
14066            )
14067        } else {
14068            None
14069        }
14070    }
14071
14072    pub fn render_crease_trailer(
14073        &self,
14074        buffer_row: MultiBufferRow,
14075        cx: &mut WindowContext,
14076    ) -> Option<AnyElement> {
14077        let folded = self.is_line_folded(buffer_row);
14078        let crease = self
14079            .crease_snapshot
14080            .query_row(buffer_row, &self.buffer_snapshot)?;
14081        Some((crease.render_trailer)(buffer_row, folded, cx))
14082    }
14083}
14084
14085impl Deref for EditorSnapshot {
14086    type Target = DisplaySnapshot;
14087
14088    fn deref(&self) -> &Self::Target {
14089        &self.display_snapshot
14090    }
14091}
14092
14093#[derive(Clone, Debug, PartialEq, Eq)]
14094pub enum EditorEvent {
14095    InputIgnored {
14096        text: Arc<str>,
14097    },
14098    InputHandled {
14099        utf16_range_to_replace: Option<Range<isize>>,
14100        text: Arc<str>,
14101    },
14102    ExcerptsAdded {
14103        buffer: Model<Buffer>,
14104        predecessor: ExcerptId,
14105        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14106    },
14107    ExcerptsRemoved {
14108        ids: Vec<ExcerptId>,
14109    },
14110    ExcerptsEdited {
14111        ids: Vec<ExcerptId>,
14112    },
14113    ExcerptsExpanded {
14114        ids: Vec<ExcerptId>,
14115    },
14116    BufferEdited,
14117    Edited {
14118        transaction_id: clock::Lamport,
14119    },
14120    Reparsed(BufferId),
14121    Focused,
14122    FocusedIn,
14123    Blurred,
14124    DirtyChanged,
14125    Saved,
14126    TitleChanged,
14127    DiffBaseChanged,
14128    SelectionsChanged {
14129        local: bool,
14130    },
14131    ScrollPositionChanged {
14132        local: bool,
14133        autoscroll: bool,
14134    },
14135    Closed,
14136    TransactionUndone {
14137        transaction_id: clock::Lamport,
14138    },
14139    TransactionBegun {
14140        transaction_id: clock::Lamport,
14141    },
14142    Reloaded,
14143    CursorShapeChanged,
14144}
14145
14146impl EventEmitter<EditorEvent> for Editor {}
14147
14148impl FocusableView for Editor {
14149    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14150        self.focus_handle.clone()
14151    }
14152}
14153
14154impl Render for Editor {
14155    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14156        let settings = ThemeSettings::get_global(cx);
14157
14158        let mut text_style = match self.mode {
14159            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14160                color: cx.theme().colors().editor_foreground,
14161                font_family: settings.ui_font.family.clone(),
14162                font_features: settings.ui_font.features.clone(),
14163                font_fallbacks: settings.ui_font.fallbacks.clone(),
14164                font_size: rems(0.875).into(),
14165                font_weight: settings.ui_font.weight,
14166                line_height: relative(settings.buffer_line_height.value()),
14167                ..Default::default()
14168            },
14169            EditorMode::Full => TextStyle {
14170                color: cx.theme().colors().editor_foreground,
14171                font_family: settings.buffer_font.family.clone(),
14172                font_features: settings.buffer_font.features.clone(),
14173                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14174                font_size: settings.buffer_font_size(cx).into(),
14175                font_weight: settings.buffer_font.weight,
14176                line_height: relative(settings.buffer_line_height.value()),
14177                ..Default::default()
14178            },
14179        };
14180        if let Some(text_style_refinement) = &self.text_style_refinement {
14181            text_style.refine(text_style_refinement)
14182        }
14183
14184        let background = match self.mode {
14185            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14186            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14187            EditorMode::Full => cx.theme().colors().editor_background,
14188        };
14189
14190        EditorElement::new(
14191            cx.view(),
14192            EditorStyle {
14193                background,
14194                local_player: cx.theme().players().local(),
14195                text: text_style,
14196                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14197                syntax: cx.theme().syntax().clone(),
14198                status: cx.theme().status().clone(),
14199                inlay_hints_style: make_inlay_hints_style(cx),
14200                suggestions_style: HighlightStyle {
14201                    color: Some(cx.theme().status().predictive),
14202                    ..HighlightStyle::default()
14203                },
14204                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14205            },
14206        )
14207    }
14208}
14209
14210impl ViewInputHandler for Editor {
14211    fn text_for_range(
14212        &mut self,
14213        range_utf16: Range<usize>,
14214        cx: &mut ViewContext<Self>,
14215    ) -> Option<String> {
14216        Some(
14217            self.buffer
14218                .read(cx)
14219                .read(cx)
14220                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14221                .collect(),
14222        )
14223    }
14224
14225    fn selected_text_range(
14226        &mut self,
14227        ignore_disabled_input: bool,
14228        cx: &mut ViewContext<Self>,
14229    ) -> Option<UTF16Selection> {
14230        // Prevent the IME menu from appearing when holding down an alphabetic key
14231        // while input is disabled.
14232        if !ignore_disabled_input && !self.input_enabled {
14233            return None;
14234        }
14235
14236        let selection = self.selections.newest::<OffsetUtf16>(cx);
14237        let range = selection.range();
14238
14239        Some(UTF16Selection {
14240            range: range.start.0..range.end.0,
14241            reversed: selection.reversed,
14242        })
14243    }
14244
14245    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14246        let snapshot = self.buffer.read(cx).read(cx);
14247        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14248        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14249    }
14250
14251    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14252        self.clear_highlights::<InputComposition>(cx);
14253        self.ime_transaction.take();
14254    }
14255
14256    fn replace_text_in_range(
14257        &mut self,
14258        range_utf16: Option<Range<usize>>,
14259        text: &str,
14260        cx: &mut ViewContext<Self>,
14261    ) {
14262        if !self.input_enabled {
14263            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14264            return;
14265        }
14266
14267        self.transact(cx, |this, cx| {
14268            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14269                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14270                Some(this.selection_replacement_ranges(range_utf16, cx))
14271            } else {
14272                this.marked_text_ranges(cx)
14273            };
14274
14275            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14276                let newest_selection_id = this.selections.newest_anchor().id;
14277                this.selections
14278                    .all::<OffsetUtf16>(cx)
14279                    .iter()
14280                    .zip(ranges_to_replace.iter())
14281                    .find_map(|(selection, range)| {
14282                        if selection.id == newest_selection_id {
14283                            Some(
14284                                (range.start.0 as isize - selection.head().0 as isize)
14285                                    ..(range.end.0 as isize - selection.head().0 as isize),
14286                            )
14287                        } else {
14288                            None
14289                        }
14290                    })
14291            });
14292
14293            cx.emit(EditorEvent::InputHandled {
14294                utf16_range_to_replace: range_to_replace,
14295                text: text.into(),
14296            });
14297
14298            if let Some(new_selected_ranges) = new_selected_ranges {
14299                this.change_selections(None, cx, |selections| {
14300                    selections.select_ranges(new_selected_ranges)
14301                });
14302                this.backspace(&Default::default(), cx);
14303            }
14304
14305            this.handle_input(text, cx);
14306        });
14307
14308        if let Some(transaction) = self.ime_transaction {
14309            self.buffer.update(cx, |buffer, cx| {
14310                buffer.group_until_transaction(transaction, cx);
14311            });
14312        }
14313
14314        self.unmark_text(cx);
14315    }
14316
14317    fn replace_and_mark_text_in_range(
14318        &mut self,
14319        range_utf16: Option<Range<usize>>,
14320        text: &str,
14321        new_selected_range_utf16: Option<Range<usize>>,
14322        cx: &mut ViewContext<Self>,
14323    ) {
14324        if !self.input_enabled {
14325            return;
14326        }
14327
14328        let transaction = self.transact(cx, |this, cx| {
14329            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14330                let snapshot = this.buffer.read(cx).read(cx);
14331                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14332                    for marked_range in &mut marked_ranges {
14333                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14334                        marked_range.start.0 += relative_range_utf16.start;
14335                        marked_range.start =
14336                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14337                        marked_range.end =
14338                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14339                    }
14340                }
14341                Some(marked_ranges)
14342            } else if let Some(range_utf16) = range_utf16 {
14343                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14344                Some(this.selection_replacement_ranges(range_utf16, cx))
14345            } else {
14346                None
14347            };
14348
14349            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14350                let newest_selection_id = this.selections.newest_anchor().id;
14351                this.selections
14352                    .all::<OffsetUtf16>(cx)
14353                    .iter()
14354                    .zip(ranges_to_replace.iter())
14355                    .find_map(|(selection, range)| {
14356                        if selection.id == newest_selection_id {
14357                            Some(
14358                                (range.start.0 as isize - selection.head().0 as isize)
14359                                    ..(range.end.0 as isize - selection.head().0 as isize),
14360                            )
14361                        } else {
14362                            None
14363                        }
14364                    })
14365            });
14366
14367            cx.emit(EditorEvent::InputHandled {
14368                utf16_range_to_replace: range_to_replace,
14369                text: text.into(),
14370            });
14371
14372            if let Some(ranges) = ranges_to_replace {
14373                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14374            }
14375
14376            let marked_ranges = {
14377                let snapshot = this.buffer.read(cx).read(cx);
14378                this.selections
14379                    .disjoint_anchors()
14380                    .iter()
14381                    .map(|selection| {
14382                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14383                    })
14384                    .collect::<Vec<_>>()
14385            };
14386
14387            if text.is_empty() {
14388                this.unmark_text(cx);
14389            } else {
14390                this.highlight_text::<InputComposition>(
14391                    marked_ranges.clone(),
14392                    HighlightStyle {
14393                        underline: Some(UnderlineStyle {
14394                            thickness: px(1.),
14395                            color: None,
14396                            wavy: false,
14397                        }),
14398                        ..Default::default()
14399                    },
14400                    cx,
14401                );
14402            }
14403
14404            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14405            let use_autoclose = this.use_autoclose;
14406            let use_auto_surround = this.use_auto_surround;
14407            this.set_use_autoclose(false);
14408            this.set_use_auto_surround(false);
14409            this.handle_input(text, cx);
14410            this.set_use_autoclose(use_autoclose);
14411            this.set_use_auto_surround(use_auto_surround);
14412
14413            if let Some(new_selected_range) = new_selected_range_utf16 {
14414                let snapshot = this.buffer.read(cx).read(cx);
14415                let new_selected_ranges = marked_ranges
14416                    .into_iter()
14417                    .map(|marked_range| {
14418                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14419                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14420                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14421                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14422                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14423                    })
14424                    .collect::<Vec<_>>();
14425
14426                drop(snapshot);
14427                this.change_selections(None, cx, |selections| {
14428                    selections.select_ranges(new_selected_ranges)
14429                });
14430            }
14431        });
14432
14433        self.ime_transaction = self.ime_transaction.or(transaction);
14434        if let Some(transaction) = self.ime_transaction {
14435            self.buffer.update(cx, |buffer, cx| {
14436                buffer.group_until_transaction(transaction, cx);
14437            });
14438        }
14439
14440        if self.text_highlights::<InputComposition>(cx).is_none() {
14441            self.ime_transaction.take();
14442        }
14443    }
14444
14445    fn bounds_for_range(
14446        &mut self,
14447        range_utf16: Range<usize>,
14448        element_bounds: gpui::Bounds<Pixels>,
14449        cx: &mut ViewContext<Self>,
14450    ) -> Option<gpui::Bounds<Pixels>> {
14451        let text_layout_details = self.text_layout_details(cx);
14452        let style = &text_layout_details.editor_style;
14453        let font_id = cx.text_system().resolve_font(&style.text.font());
14454        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14455        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14456
14457        let em_width = cx
14458            .text_system()
14459            .typographic_bounds(font_id, font_size, 'm')
14460            .unwrap()
14461            .size
14462            .width;
14463
14464        let snapshot = self.snapshot(cx);
14465        let scroll_position = snapshot.scroll_position();
14466        let scroll_left = scroll_position.x * em_width;
14467
14468        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14469        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14470            + self.gutter_dimensions.width;
14471        let y = line_height * (start.row().as_f32() - scroll_position.y);
14472
14473        Some(Bounds {
14474            origin: element_bounds.origin + point(x, y),
14475            size: size(em_width, line_height),
14476        })
14477    }
14478}
14479
14480trait SelectionExt {
14481    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14482    fn spanned_rows(
14483        &self,
14484        include_end_if_at_line_start: bool,
14485        map: &DisplaySnapshot,
14486    ) -> Range<MultiBufferRow>;
14487}
14488
14489impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14490    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14491        let start = self
14492            .start
14493            .to_point(&map.buffer_snapshot)
14494            .to_display_point(map);
14495        let end = self
14496            .end
14497            .to_point(&map.buffer_snapshot)
14498            .to_display_point(map);
14499        if self.reversed {
14500            end..start
14501        } else {
14502            start..end
14503        }
14504    }
14505
14506    fn spanned_rows(
14507        &self,
14508        include_end_if_at_line_start: bool,
14509        map: &DisplaySnapshot,
14510    ) -> Range<MultiBufferRow> {
14511        let start = self.start.to_point(&map.buffer_snapshot);
14512        let mut end = self.end.to_point(&map.buffer_snapshot);
14513        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14514            end.row -= 1;
14515        }
14516
14517        let buffer_start = map.prev_line_boundary(start).0;
14518        let buffer_end = map.next_line_boundary(end).0;
14519        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14520    }
14521}
14522
14523impl<T: InvalidationRegion> InvalidationStack<T> {
14524    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14525    where
14526        S: Clone + ToOffset,
14527    {
14528        while let Some(region) = self.last() {
14529            let all_selections_inside_invalidation_ranges =
14530                if selections.len() == region.ranges().len() {
14531                    selections
14532                        .iter()
14533                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14534                        .all(|(selection, invalidation_range)| {
14535                            let head = selection.head().to_offset(buffer);
14536                            invalidation_range.start <= head && invalidation_range.end >= head
14537                        })
14538                } else {
14539                    false
14540                };
14541
14542            if all_selections_inside_invalidation_ranges {
14543                break;
14544            } else {
14545                self.pop();
14546            }
14547        }
14548    }
14549}
14550
14551impl<T> Default for InvalidationStack<T> {
14552    fn default() -> Self {
14553        Self(Default::default())
14554    }
14555}
14556
14557impl<T> Deref for InvalidationStack<T> {
14558    type Target = Vec<T>;
14559
14560    fn deref(&self) -> &Self::Target {
14561        &self.0
14562    }
14563}
14564
14565impl<T> DerefMut for InvalidationStack<T> {
14566    fn deref_mut(&mut self) -> &mut Self::Target {
14567        &mut self.0
14568    }
14569}
14570
14571impl InvalidationRegion for SnippetState {
14572    fn ranges(&self) -> &[Range<Anchor>] {
14573        &self.ranges[self.active_index]
14574    }
14575}
14576
14577pub fn diagnostic_block_renderer(
14578    diagnostic: Diagnostic,
14579    max_message_rows: Option<u8>,
14580    allow_closing: bool,
14581    _is_valid: bool,
14582) -> RenderBlock {
14583    let (text_without_backticks, code_ranges) =
14584        highlight_diagnostic_message(&diagnostic, max_message_rows);
14585
14586    Box::new(move |cx: &mut BlockContext| {
14587        let group_id: SharedString = cx.block_id.to_string().into();
14588
14589        let mut text_style = cx.text_style().clone();
14590        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14591        let theme_settings = ThemeSettings::get_global(cx);
14592        text_style.font_family = theme_settings.buffer_font.family.clone();
14593        text_style.font_style = theme_settings.buffer_font.style;
14594        text_style.font_features = theme_settings.buffer_font.features.clone();
14595        text_style.font_weight = theme_settings.buffer_font.weight;
14596
14597        let multi_line_diagnostic = diagnostic.message.contains('\n');
14598
14599        let buttons = |diagnostic: &Diagnostic| {
14600            if multi_line_diagnostic {
14601                v_flex()
14602            } else {
14603                h_flex()
14604            }
14605            .when(allow_closing, |div| {
14606                div.children(diagnostic.is_primary.then(|| {
14607                    IconButton::new("close-block", IconName::XCircle)
14608                        .icon_color(Color::Muted)
14609                        .size(ButtonSize::Compact)
14610                        .style(ButtonStyle::Transparent)
14611                        .visible_on_hover(group_id.clone())
14612                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14613                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14614                }))
14615            })
14616            .child(
14617                IconButton::new("copy-block", IconName::Copy)
14618                    .icon_color(Color::Muted)
14619                    .size(ButtonSize::Compact)
14620                    .style(ButtonStyle::Transparent)
14621                    .visible_on_hover(group_id.clone())
14622                    .on_click({
14623                        let message = diagnostic.message.clone();
14624                        move |_click, cx| {
14625                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14626                        }
14627                    })
14628                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14629            )
14630        };
14631
14632        let icon_size = buttons(&diagnostic)
14633            .into_any_element()
14634            .layout_as_root(AvailableSpace::min_size(), cx);
14635
14636        h_flex()
14637            .id(cx.block_id)
14638            .group(group_id.clone())
14639            .relative()
14640            .size_full()
14641            .pl(cx.gutter_dimensions.width)
14642            .w(cx.max_width - cx.gutter_dimensions.full_width())
14643            .child(
14644                div()
14645                    .flex()
14646                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14647                    .flex_shrink(),
14648            )
14649            .child(buttons(&diagnostic))
14650            .child(div().flex().flex_shrink_0().child(
14651                StyledText::new(text_without_backticks.clone()).with_highlights(
14652                    &text_style,
14653                    code_ranges.iter().map(|range| {
14654                        (
14655                            range.clone(),
14656                            HighlightStyle {
14657                                font_weight: Some(FontWeight::BOLD),
14658                                ..Default::default()
14659                            },
14660                        )
14661                    }),
14662                ),
14663            ))
14664            .into_any_element()
14665    })
14666}
14667
14668pub fn highlight_diagnostic_message(
14669    diagnostic: &Diagnostic,
14670    mut max_message_rows: Option<u8>,
14671) -> (SharedString, Vec<Range<usize>>) {
14672    let mut text_without_backticks = String::new();
14673    let mut code_ranges = Vec::new();
14674
14675    if let Some(source) = &diagnostic.source {
14676        text_without_backticks.push_str(source);
14677        code_ranges.push(0..source.len());
14678        text_without_backticks.push_str(": ");
14679    }
14680
14681    let mut prev_offset = 0;
14682    let mut in_code_block = false;
14683    let has_row_limit = max_message_rows.is_some();
14684    let mut newline_indices = diagnostic
14685        .message
14686        .match_indices('\n')
14687        .filter(|_| has_row_limit)
14688        .map(|(ix, _)| ix)
14689        .fuse()
14690        .peekable();
14691
14692    for (quote_ix, _) in diagnostic
14693        .message
14694        .match_indices('`')
14695        .chain([(diagnostic.message.len(), "")])
14696    {
14697        let mut first_newline_ix = None;
14698        let mut last_newline_ix = None;
14699        while let Some(newline_ix) = newline_indices.peek() {
14700            if *newline_ix < quote_ix {
14701                if first_newline_ix.is_none() {
14702                    first_newline_ix = Some(*newline_ix);
14703                }
14704                last_newline_ix = Some(*newline_ix);
14705
14706                if let Some(rows_left) = &mut max_message_rows {
14707                    if *rows_left == 0 {
14708                        break;
14709                    } else {
14710                        *rows_left -= 1;
14711                    }
14712                }
14713                let _ = newline_indices.next();
14714            } else {
14715                break;
14716            }
14717        }
14718        let prev_len = text_without_backticks.len();
14719        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14720        text_without_backticks.push_str(new_text);
14721        if in_code_block {
14722            code_ranges.push(prev_len..text_without_backticks.len());
14723        }
14724        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14725        in_code_block = !in_code_block;
14726        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14727            text_without_backticks.push_str("...");
14728            break;
14729        }
14730    }
14731
14732    (text_without_backticks.into(), code_ranges)
14733}
14734
14735fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14736    match severity {
14737        DiagnosticSeverity::ERROR => colors.error,
14738        DiagnosticSeverity::WARNING => colors.warning,
14739        DiagnosticSeverity::INFORMATION => colors.info,
14740        DiagnosticSeverity::HINT => colors.info,
14741        _ => colors.ignored,
14742    }
14743}
14744
14745pub fn styled_runs_for_code_label<'a>(
14746    label: &'a CodeLabel,
14747    syntax_theme: &'a theme::SyntaxTheme,
14748) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14749    let fade_out = HighlightStyle {
14750        fade_out: Some(0.35),
14751        ..Default::default()
14752    };
14753
14754    let mut prev_end = label.filter_range.end;
14755    label
14756        .runs
14757        .iter()
14758        .enumerate()
14759        .flat_map(move |(ix, (range, highlight_id))| {
14760            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14761                style
14762            } else {
14763                return Default::default();
14764            };
14765            let mut muted_style = style;
14766            muted_style.highlight(fade_out);
14767
14768            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14769            if range.start >= label.filter_range.end {
14770                if range.start > prev_end {
14771                    runs.push((prev_end..range.start, fade_out));
14772                }
14773                runs.push((range.clone(), muted_style));
14774            } else if range.end <= label.filter_range.end {
14775                runs.push((range.clone(), style));
14776            } else {
14777                runs.push((range.start..label.filter_range.end, style));
14778                runs.push((label.filter_range.end..range.end, muted_style));
14779            }
14780            prev_end = cmp::max(prev_end, range.end);
14781
14782            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14783                runs.push((prev_end..label.text.len(), fade_out));
14784            }
14785
14786            runs
14787        })
14788}
14789
14790pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14791    let mut prev_index = 0;
14792    let mut prev_codepoint: Option<char> = None;
14793    text.char_indices()
14794        .chain([(text.len(), '\0')])
14795        .filter_map(move |(index, codepoint)| {
14796            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14797            let is_boundary = index == text.len()
14798                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14799                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14800            if is_boundary {
14801                let chunk = &text[prev_index..index];
14802                prev_index = index;
14803                Some(chunk)
14804            } else {
14805                None
14806            }
14807        })
14808}
14809
14810pub trait RangeToAnchorExt: Sized {
14811    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14812
14813    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14814        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14815        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14816    }
14817}
14818
14819impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14820    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14821        let start_offset = self.start.to_offset(snapshot);
14822        let end_offset = self.end.to_offset(snapshot);
14823        if start_offset == end_offset {
14824            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14825        } else {
14826            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14827        }
14828    }
14829}
14830
14831pub trait RowExt {
14832    fn as_f32(&self) -> f32;
14833
14834    fn next_row(&self) -> Self;
14835
14836    fn previous_row(&self) -> Self;
14837
14838    fn minus(&self, other: Self) -> u32;
14839}
14840
14841impl RowExt for DisplayRow {
14842    fn as_f32(&self) -> f32 {
14843        self.0 as f32
14844    }
14845
14846    fn next_row(&self) -> Self {
14847        Self(self.0 + 1)
14848    }
14849
14850    fn previous_row(&self) -> Self {
14851        Self(self.0.saturating_sub(1))
14852    }
14853
14854    fn minus(&self, other: Self) -> u32 {
14855        self.0 - other.0
14856    }
14857}
14858
14859impl RowExt for MultiBufferRow {
14860    fn as_f32(&self) -> f32 {
14861        self.0 as f32
14862    }
14863
14864    fn next_row(&self) -> Self {
14865        Self(self.0 + 1)
14866    }
14867
14868    fn previous_row(&self) -> Self {
14869        Self(self.0.saturating_sub(1))
14870    }
14871
14872    fn minus(&self, other: Self) -> u32 {
14873        self.0 - other.0
14874    }
14875}
14876
14877trait RowRangeExt {
14878    type Row;
14879
14880    fn len(&self) -> usize;
14881
14882    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14883}
14884
14885impl RowRangeExt for Range<MultiBufferRow> {
14886    type Row = MultiBufferRow;
14887
14888    fn len(&self) -> usize {
14889        (self.end.0 - self.start.0) as usize
14890    }
14891
14892    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14893        (self.start.0..self.end.0).map(MultiBufferRow)
14894    }
14895}
14896
14897impl RowRangeExt for Range<DisplayRow> {
14898    type Row = DisplayRow;
14899
14900    fn len(&self) -> usize {
14901        (self.end.0 - self.start.0) as usize
14902    }
14903
14904    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14905        (self.start.0..self.end.0).map(DisplayRow)
14906    }
14907}
14908
14909fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14910    if hunk.diff_base_byte_range.is_empty() {
14911        DiffHunkStatus::Added
14912    } else if hunk.row_range.is_empty() {
14913        DiffHunkStatus::Removed
14914    } else {
14915        DiffHunkStatus::Modified
14916    }
14917}
14918
14919/// If select range has more than one line, we
14920/// just point the cursor to range.start.
14921fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14922    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14923        range
14924    } else {
14925        range.start..range.start
14926    }
14927}