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, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   79    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   80    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 task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::RefCell,
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Copy, Clone, PartialEq, Eq)]
  277pub enum Direction {
  278    Prev,
  279    Next,
  280}
  281
  282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  283pub enum Navigated {
  284    Yes,
  285    No,
  286}
  287
  288impl Navigated {
  289    pub fn from_bool(yes: bool) -> Navigated {
  290        if yes {
  291            Navigated::Yes
  292        } else {
  293            Navigated::No
  294        }
  295    }
  296}
  297
  298pub fn init_settings(cx: &mut AppContext) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut AppContext) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new_views(
  310        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  322                Editor::new_file(workspace, &Default::default(), cx)
  323            })
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  331                Editor::new_file(workspace, &Default::default(), cx)
  332            })
  333            .detach();
  334        }
  335    });
  336}
  337
  338pub struct SearchWithinRange;
  339
  340trait InvalidationRegion {
  341    fn ranges(&self) -> &[Range<Anchor>];
  342}
  343
  344#[derive(Clone, Debug, PartialEq)]
  345pub enum SelectPhase {
  346    Begin {
  347        position: DisplayPoint,
  348        add: bool,
  349        click_count: usize,
  350    },
  351    BeginColumnar {
  352        position: DisplayPoint,
  353        reset: bool,
  354        goal_column: u32,
  355    },
  356    Extend {
  357        position: DisplayPoint,
  358        click_count: usize,
  359    },
  360    Update {
  361        position: DisplayPoint,
  362        goal_column: u32,
  363        scroll_delta: gpui::Point<f32>,
  364    },
  365    End,
  366}
  367
  368#[derive(Clone, Debug)]
  369pub enum SelectMode {
  370    Character,
  371    Word(Range<Anchor>),
  372    Line(Range<Anchor>),
  373    All,
  374}
  375
  376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  377pub enum EditorMode {
  378    SingleLine { auto_width: bool },
  379    AutoHeight { max_lines: usize },
  380    Full,
  381}
  382
  383#[derive(Copy, Clone, Debug)]
  384pub enum SoftWrap {
  385    /// Prefer not to wrap at all.
  386    ///
  387    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  388    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  389    GitDiff,
  390    /// Prefer a single line generally, unless an overly long line is encountered.
  391    None,
  392    /// Soft wrap lines that exceed the editor width.
  393    EditorWidth,
  394    /// Soft wrap lines at the preferred line length.
  395    Column(u32),
  396    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  397    Bounded(u32),
  398}
  399
  400#[derive(Clone)]
  401pub struct EditorStyle {
  402    pub background: Hsla,
  403    pub local_player: PlayerColor,
  404    pub text: TextStyle,
  405    pub scrollbar_width: Pixels,
  406    pub syntax: Arc<SyntaxTheme>,
  407    pub status: StatusColors,
  408    pub inlay_hints_style: HighlightStyle,
  409    pub suggestions_style: HighlightStyle,
  410    pub unnecessary_code_fade: f32,
  411}
  412
  413impl Default for EditorStyle {
  414    fn default() -> Self {
  415        Self {
  416            background: Hsla::default(),
  417            local_player: PlayerColor::default(),
  418            text: TextStyle::default(),
  419            scrollbar_width: Pixels::default(),
  420            syntax: Default::default(),
  421            // HACK: Status colors don't have a real default.
  422            // We should look into removing the status colors from the editor
  423            // style and retrieve them directly from the theme.
  424            status: StatusColors::dark(),
  425            inlay_hints_style: HighlightStyle::default(),
  426            suggestions_style: HighlightStyle::default(),
  427            unnecessary_code_fade: Default::default(),
  428        }
  429    }
  430}
  431
  432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  433    let show_background = language_settings::language_settings(None, None, cx)
  434        .inlay_hints
  435        .show_background;
  436
  437    HighlightStyle {
  438        color: Some(cx.theme().status().hint),
  439        background_color: show_background.then(|| cx.theme().status().hint_background),
  440        ..HighlightStyle::default()
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446#[derive(Clone, Debug)]
  447struct CompletionState {
  448    // render_inlay_ids represents the inlay hints that are inserted
  449    // for rendering the inline completions. They may be discontinuous
  450    // in the event that the completion provider returns some intersection
  451    // with the existing content.
  452    render_inlay_ids: Vec<InlayId>,
  453    // text is the resulting rope that is inserted when the user accepts a completion.
  454    text: Rope,
  455    // position is the position of the cursor when the completion was triggered.
  456    position: multi_buffer::Anchor,
  457    // delete_range is the range of text that this completion state covers.
  458    // if the completion is accepted, this range should be deleted.
  459    delete_range: Option<Range<multi_buffer::Anchor>>,
  460}
  461
  462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  463struct EditorActionId(usize);
  464
  465impl EditorActionId {
  466    pub fn post_inc(&mut self) -> Self {
  467        let answer = self.0;
  468
  469        *self = Self(answer + 1);
  470
  471        Self(answer)
  472    }
  473}
  474
  475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  477
  478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  480
  481#[derive(Default)]
  482struct ScrollbarMarkerState {
  483    scrollbar_size: Size<Pixels>,
  484    dirty: bool,
  485    markers: Arc<[PaintQuad]>,
  486    pending_refresh: Option<Task<Result<()>>>,
  487}
  488
  489impl ScrollbarMarkerState {
  490    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  491        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  492    }
  493}
  494
  495#[derive(Clone, Debug)]
  496struct RunnableTasks {
  497    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  498    offset: MultiBufferOffset,
  499    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  500    column: u32,
  501    // Values of all named captures, including those starting with '_'
  502    extra_variables: HashMap<String, String>,
  503    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  504    context_range: Range<BufferOffset>,
  505}
  506
  507impl RunnableTasks {
  508    fn resolve<'a>(
  509        &'a self,
  510        cx: &'a task::TaskContext,
  511    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  512        self.templates.iter().filter_map(|(kind, template)| {
  513            template
  514                .resolve_task(&kind.to_id_base(), cx)
  515                .map(|task| (kind.clone(), task))
  516        })
  517    }
  518}
  519
  520#[derive(Clone)]
  521struct ResolvedTasks {
  522    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  523    position: Anchor,
  524}
  525#[derive(Copy, Clone, Debug)]
  526struct MultiBufferOffset(usize);
  527#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  528struct BufferOffset(usize);
  529
  530// Addons allow storing per-editor state in other crates (e.g. Vim)
  531pub trait Addon: 'static {
  532    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  533
  534    fn to_any(&self) -> &dyn std::any::Any;
  535}
  536
  537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  538///
  539/// See the [module level documentation](self) for more information.
  540pub struct Editor {
  541    focus_handle: FocusHandle,
  542    last_focused_descendant: Option<WeakFocusHandle>,
  543    /// The text buffer being edited
  544    buffer: Model<MultiBuffer>,
  545    /// Map of how text in the buffer should be displayed.
  546    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  547    pub display_map: Model<DisplayMap>,
  548    pub selections: SelectionsCollection,
  549    pub scroll_manager: ScrollManager,
  550    /// When inline assist editors are linked, they all render cursors because
  551    /// typing enters text into each of them, even the ones that aren't focused.
  552    pub(crate) show_cursor_when_unfocused: bool,
  553    columnar_selection_tail: Option<Anchor>,
  554    add_selections_state: Option<AddSelectionsState>,
  555    select_next_state: Option<SelectNextState>,
  556    select_prev_state: Option<SelectNextState>,
  557    selection_history: SelectionHistory,
  558    autoclose_regions: Vec<AutocloseRegion>,
  559    snippet_stack: InvalidationStack<SnippetState>,
  560    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  561    ime_transaction: Option<TransactionId>,
  562    active_diagnostics: Option<ActiveDiagnosticGroup>,
  563    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  564
  565    project: Option<Model<Project>>,
  566    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  567    completion_provider: Option<Box<dyn CompletionProvider>>,
  568    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  569    blink_manager: Model<BlinkManager>,
  570    show_cursor_names: bool,
  571    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  572    pub show_local_selections: bool,
  573    mode: EditorMode,
  574    show_breadcrumbs: bool,
  575    show_gutter: bool,
  576    show_line_numbers: Option<bool>,
  577    use_relative_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    show_wrap_guides: Option<bool>,
  582    show_indent_guides: Option<bool>,
  583    placeholder_text: Option<Arc<str>>,
  584    highlight_order: usize,
  585    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  586    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  587    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  588    scrollbar_marker_state: ScrollbarMarkerState,
  589    active_indent_guides_state: ActiveIndentGuidesState,
  590    nav_history: Option<ItemNavHistory>,
  591    context_menu: RwLock<Option<ContextMenu>>,
  592    mouse_context_menu: Option<MouseContextMenu>,
  593    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  594    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  595    signature_help_state: SignatureHelpState,
  596    auto_signature_help: Option<bool>,
  597    find_all_references_task_sources: Vec<Anchor>,
  598    next_completion_id: CompletionId,
  599    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  600    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  601    code_actions_task: Option<Task<Result<()>>>,
  602    document_highlights_task: Option<Task<()>>,
  603    linked_editing_range_task: Option<Task<Option<()>>>,
  604    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  605    pending_rename: Option<RenameState>,
  606    searchable: bool,
  607    cursor_shape: CursorShape,
  608    current_line_highlight: Option<CurrentLineHighlight>,
  609    collapse_matches: bool,
  610    autoindent_mode: Option<AutoindentMode>,
  611    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  612    input_enabled: bool,
  613    use_modal_editing: bool,
  614    read_only: bool,
  615    leader_peer_id: Option<PeerId>,
  616    remote_id: Option<ViewId>,
  617    hover_state: HoverState,
  618    gutter_hovered: bool,
  619    hovered_link_state: Option<HoveredLinkState>,
  620    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  621    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  622    active_inline_completion: Option<CompletionState>,
  623    // enable_inline_completions is a switch that Vim can use to disable
  624    // inline completions based on its mode.
  625    enable_inline_completions: bool,
  626    show_inline_completions_override: Option<bool>,
  627    inlay_hint_cache: InlayHintCache,
  628    expanded_hunks: ExpandedHunks,
  629    next_inlay_id: usize,
  630    _subscriptions: Vec<Subscription>,
  631    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  632    gutter_dimensions: GutterDimensions,
  633    style: Option<EditorStyle>,
  634    text_style_refinement: Option<TextStyleRefinement>,
  635    next_editor_action_id: EditorActionId,
  636    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  637    use_autoclose: bool,
  638    use_auto_surround: bool,
  639    auto_replace_emoji_shortcode: bool,
  640    show_git_blame_gutter: bool,
  641    show_git_blame_inline: bool,
  642    show_git_blame_inline_delay_task: Option<Task<()>>,
  643    git_blame_inline_enabled: bool,
  644    serialize_dirty_buffers: bool,
  645    show_selection_menu: Option<bool>,
  646    blame: Option<Model<GitBlame>>,
  647    blame_subscription: Option<Subscription>,
  648    custom_context_menu: Option<
  649        Box<
  650            dyn 'static
  651                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  652        >,
  653    >,
  654    last_bounds: Option<Bounds<Pixels>>,
  655    expect_bounds_change: Option<Bounds<Pixels>>,
  656    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  657    tasks_update_task: Option<Task<()>>,
  658    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  659    breadcrumb_header: Option<String>,
  660    focused_block: Option<FocusedBlock>,
  661    next_scroll_position: NextScrollCursorCenterTopBottom,
  662    addons: HashMap<TypeId, Box<dyn Addon>>,
  663    _scroll_cursor_center_top_bottom_task: Task<()>,
  664}
  665
  666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  667enum NextScrollCursorCenterTopBottom {
  668    #[default]
  669    Center,
  670    Top,
  671    Bottom,
  672}
  673
  674impl NextScrollCursorCenterTopBottom {
  675    fn next(&self) -> Self {
  676        match self {
  677            Self::Center => Self::Top,
  678            Self::Top => Self::Bottom,
  679            Self::Bottom => Self::Center,
  680        }
  681    }
  682}
  683
  684#[derive(Clone)]
  685pub struct EditorSnapshot {
  686    pub mode: EditorMode,
  687    show_gutter: bool,
  688    show_line_numbers: Option<bool>,
  689    show_git_diff_gutter: Option<bool>,
  690    show_code_actions: Option<bool>,
  691    show_runnables: Option<bool>,
  692    git_blame_gutter_max_author_length: Option<usize>,
  693    pub display_snapshot: DisplaySnapshot,
  694    pub placeholder_text: Option<Arc<str>>,
  695    is_focused: bool,
  696    scroll_anchor: ScrollAnchor,
  697    ongoing_scroll: OngoingScroll,
  698    current_line_highlight: CurrentLineHighlight,
  699    gutter_hovered: bool,
  700}
  701
  702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  703
  704#[derive(Default, Debug, Clone, Copy)]
  705pub struct GutterDimensions {
  706    pub left_padding: Pixels,
  707    pub right_padding: Pixels,
  708    pub width: Pixels,
  709    pub margin: Pixels,
  710    pub git_blame_entries_width: Option<Pixels>,
  711}
  712
  713impl GutterDimensions {
  714    /// The full width of the space taken up by the gutter.
  715    pub fn full_width(&self) -> Pixels {
  716        self.margin + self.width
  717    }
  718
  719    /// The width of the space reserved for the fold indicators,
  720    /// use alongside 'justify_end' and `gutter_width` to
  721    /// right align content with the line numbers
  722    pub fn fold_area_width(&self) -> Pixels {
  723        self.margin + self.right_padding
  724    }
  725}
  726
  727#[derive(Debug)]
  728pub struct RemoteSelection {
  729    pub replica_id: ReplicaId,
  730    pub selection: Selection<Anchor>,
  731    pub cursor_shape: CursorShape,
  732    pub peer_id: PeerId,
  733    pub line_mode: bool,
  734    pub participant_index: Option<ParticipantIndex>,
  735    pub user_name: Option<SharedString>,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct SelectionHistoryEntry {
  740    selections: Arc<[Selection<Anchor>]>,
  741    select_next_state: Option<SelectNextState>,
  742    select_prev_state: Option<SelectNextState>,
  743    add_selections_state: Option<AddSelectionsState>,
  744}
  745
  746enum SelectionHistoryMode {
  747    Normal,
  748    Undoing,
  749    Redoing,
  750}
  751
  752#[derive(Clone, PartialEq, Eq, Hash)]
  753struct HoveredCursor {
  754    replica_id: u16,
  755    selection_id: usize,
  756}
  757
  758impl Default for SelectionHistoryMode {
  759    fn default() -> Self {
  760        Self::Normal
  761    }
  762}
  763
  764#[derive(Default)]
  765struct SelectionHistory {
  766    #[allow(clippy::type_complexity)]
  767    selections_by_transaction:
  768        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  769    mode: SelectionHistoryMode,
  770    undo_stack: VecDeque<SelectionHistoryEntry>,
  771    redo_stack: VecDeque<SelectionHistoryEntry>,
  772}
  773
  774impl SelectionHistory {
  775    fn insert_transaction(
  776        &mut self,
  777        transaction_id: TransactionId,
  778        selections: Arc<[Selection<Anchor>]>,
  779    ) {
  780        self.selections_by_transaction
  781            .insert(transaction_id, (selections, None));
  782    }
  783
  784    #[allow(clippy::type_complexity)]
  785    fn transaction(
  786        &self,
  787        transaction_id: TransactionId,
  788    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  789        self.selections_by_transaction.get(&transaction_id)
  790    }
  791
  792    #[allow(clippy::type_complexity)]
  793    fn transaction_mut(
  794        &mut self,
  795        transaction_id: TransactionId,
  796    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  797        self.selections_by_transaction.get_mut(&transaction_id)
  798    }
  799
  800    fn push(&mut self, entry: SelectionHistoryEntry) {
  801        if !entry.selections.is_empty() {
  802            match self.mode {
  803                SelectionHistoryMode::Normal => {
  804                    self.push_undo(entry);
  805                    self.redo_stack.clear();
  806                }
  807                SelectionHistoryMode::Undoing => self.push_redo(entry),
  808                SelectionHistoryMode::Redoing => self.push_undo(entry),
  809            }
  810        }
  811    }
  812
  813    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  814        if self
  815            .undo_stack
  816            .back()
  817            .map_or(true, |e| e.selections != entry.selections)
  818        {
  819            self.undo_stack.push_back(entry);
  820            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  821                self.undo_stack.pop_front();
  822            }
  823        }
  824    }
  825
  826    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  827        if self
  828            .redo_stack
  829            .back()
  830            .map_or(true, |e| e.selections != entry.selections)
  831        {
  832            self.redo_stack.push_back(entry);
  833            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  834                self.redo_stack.pop_front();
  835            }
  836        }
  837    }
  838}
  839
  840struct RowHighlight {
  841    index: usize,
  842    range: Range<Anchor>,
  843    color: Hsla,
  844    should_autoscroll: bool,
  845}
  846
  847#[derive(Clone, Debug)]
  848struct AddSelectionsState {
  849    above: bool,
  850    stack: Vec<usize>,
  851}
  852
  853#[derive(Clone)]
  854struct SelectNextState {
  855    query: AhoCorasick,
  856    wordwise: bool,
  857    done: bool,
  858}
  859
  860impl std::fmt::Debug for SelectNextState {
  861    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  862        f.debug_struct(std::any::type_name::<Self>())
  863            .field("wordwise", &self.wordwise)
  864            .field("done", &self.done)
  865            .finish()
  866    }
  867}
  868
  869#[derive(Debug)]
  870struct AutocloseRegion {
  871    selection_id: usize,
  872    range: Range<Anchor>,
  873    pair: BracketPair,
  874}
  875
  876#[derive(Debug)]
  877struct SnippetState {
  878    ranges: Vec<Vec<Range<Anchor>>>,
  879    active_index: usize,
  880}
  881
  882#[doc(hidden)]
  883pub struct RenameState {
  884    pub range: Range<Anchor>,
  885    pub old_name: Arc<str>,
  886    pub editor: View<Editor>,
  887    block_id: CustomBlockId,
  888}
  889
  890struct InvalidationStack<T>(Vec<T>);
  891
  892struct RegisteredInlineCompletionProvider {
  893    provider: Arc<dyn InlineCompletionProviderHandle>,
  894    _subscription: Subscription,
  895}
  896
  897enum ContextMenu {
  898    Completions(CompletionsMenu),
  899    CodeActions(CodeActionsMenu),
  900}
  901
  902impl ContextMenu {
  903    fn select_first(
  904        &mut self,
  905        provider: Option<&dyn CompletionProvider>,
  906        cx: &mut ViewContext<Editor>,
  907    ) -> bool {
  908        if self.visible() {
  909            match self {
  910                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_prev(
  920        &mut self,
  921        provider: Option<&dyn CompletionProvider>,
  922        cx: &mut ViewContext<Editor>,
  923    ) -> bool {
  924        if self.visible() {
  925            match self {
  926                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_next(
  936        &mut self,
  937        provider: Option<&dyn CompletionProvider>,
  938        cx: &mut ViewContext<Editor>,
  939    ) -> bool {
  940        if self.visible() {
  941            match self {
  942                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn select_last(
  952        &mut self,
  953        provider: Option<&dyn CompletionProvider>,
  954        cx: &mut ViewContext<Editor>,
  955    ) -> bool {
  956        if self.visible() {
  957            match self {
  958                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  959                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  960            }
  961            true
  962        } else {
  963            false
  964        }
  965    }
  966
  967    fn visible(&self) -> bool {
  968        match self {
  969            ContextMenu::Completions(menu) => menu.visible(),
  970            ContextMenu::CodeActions(menu) => menu.visible(),
  971        }
  972    }
  973
  974    fn render(
  975        &self,
  976        cursor_position: DisplayPoint,
  977        style: &EditorStyle,
  978        max_height: Pixels,
  979        workspace: Option<WeakView<Workspace>>,
  980        cx: &mut ViewContext<Editor>,
  981    ) -> (ContextMenuOrigin, AnyElement) {
  982        match self {
  983            ContextMenu::Completions(menu) => (
  984                ContextMenuOrigin::EditorPoint(cursor_position),
  985                menu.render(style, max_height, workspace, cx),
  986            ),
  987            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  988        }
  989    }
  990}
  991
  992enum ContextMenuOrigin {
  993    EditorPoint(DisplayPoint),
  994    GutterIndicator(DisplayRow),
  995}
  996
  997#[derive(Clone)]
  998struct CompletionsMenu {
  999    id: CompletionId,
 1000    sort_completions: bool,
 1001    initial_position: Anchor,
 1002    buffer: Model<Buffer>,
 1003    completions: Arc<RwLock<Box<[Completion]>>>,
 1004    match_candidates: Arc<[StringMatchCandidate]>,
 1005    matches: Arc<[StringMatch]>,
 1006    selected_item: usize,
 1007    scroll_handle: UniformListScrollHandle,
 1008    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
 1009}
 1010
 1011impl CompletionsMenu {
 1012    fn select_first(
 1013        &mut self,
 1014        provider: Option<&dyn CompletionProvider>,
 1015        cx: &mut ViewContext<Editor>,
 1016    ) {
 1017        self.selected_item = 0;
 1018        self.scroll_handle.scroll_to_item(self.selected_item);
 1019        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1020        cx.notify();
 1021    }
 1022
 1023    fn select_prev(
 1024        &mut self,
 1025        provider: Option<&dyn CompletionProvider>,
 1026        cx: &mut ViewContext<Editor>,
 1027    ) {
 1028        if self.selected_item > 0 {
 1029            self.selected_item -= 1;
 1030        } else {
 1031            self.selected_item = self.matches.len() - 1;
 1032        }
 1033        self.scroll_handle.scroll_to_item(self.selected_item);
 1034        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1035        cx.notify();
 1036    }
 1037
 1038    fn select_next(
 1039        &mut self,
 1040        provider: Option<&dyn CompletionProvider>,
 1041        cx: &mut ViewContext<Editor>,
 1042    ) {
 1043        if self.selected_item + 1 < self.matches.len() {
 1044            self.selected_item += 1;
 1045        } else {
 1046            self.selected_item = 0;
 1047        }
 1048        self.scroll_handle.scroll_to_item(self.selected_item);
 1049        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1050        cx.notify();
 1051    }
 1052
 1053    fn select_last(
 1054        &mut self,
 1055        provider: Option<&dyn CompletionProvider>,
 1056        cx: &mut ViewContext<Editor>,
 1057    ) {
 1058        self.selected_item = self.matches.len() - 1;
 1059        self.scroll_handle.scroll_to_item(self.selected_item);
 1060        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1061        cx.notify();
 1062    }
 1063
 1064    fn pre_resolve_completion_documentation(
 1065        buffer: Model<Buffer>,
 1066        completions: Arc<RwLock<Box<[Completion]>>>,
 1067        matches: Arc<[StringMatch]>,
 1068        editor: &Editor,
 1069        cx: &mut ViewContext<Editor>,
 1070    ) -> Task<()> {
 1071        let settings = EditorSettings::get_global(cx);
 1072        if !settings.show_completion_documentation {
 1073            return Task::ready(());
 1074        }
 1075
 1076        let Some(provider) = editor.completion_provider.as_ref() else {
 1077            return Task::ready(());
 1078        };
 1079
 1080        let resolve_task = provider.resolve_completions(
 1081            buffer,
 1082            matches.iter().map(|m| m.candidate_id).collect(),
 1083            completions.clone(),
 1084            cx,
 1085        );
 1086
 1087        cx.spawn(move |this, mut cx| async move {
 1088            if let Some(true) = resolve_task.await.log_err() {
 1089                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1090            }
 1091        })
 1092    }
 1093
 1094    fn attempt_resolve_selected_completion_documentation(
 1095        &mut self,
 1096        provider: Option<&dyn CompletionProvider>,
 1097        cx: &mut ViewContext<Editor>,
 1098    ) {
 1099        let settings = EditorSettings::get_global(cx);
 1100        if !settings.show_completion_documentation {
 1101            return;
 1102        }
 1103
 1104        let completion_index = self.matches[self.selected_item].candidate_id;
 1105        let Some(provider) = provider else {
 1106            return;
 1107        };
 1108
 1109        let resolve_task = provider.resolve_completions(
 1110            self.buffer.clone(),
 1111            vec![completion_index],
 1112            self.completions.clone(),
 1113            cx,
 1114        );
 1115
 1116        let delay_ms =
 1117            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1118        let delay = Duration::from_millis(delay_ms);
 1119
 1120        self.selected_completion_documentation_resolve_debounce
 1121            .lock()
 1122            .fire_new(delay, cx, |_, cx| {
 1123                cx.spawn(move |this, mut cx| async move {
 1124                    if let Some(true) = resolve_task.await.log_err() {
 1125                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1126                    }
 1127                })
 1128            });
 1129    }
 1130
 1131    fn visible(&self) -> bool {
 1132        !self.matches.is_empty()
 1133    }
 1134
 1135    fn render(
 1136        &self,
 1137        style: &EditorStyle,
 1138        max_height: Pixels,
 1139        workspace: Option<WeakView<Workspace>>,
 1140        cx: &mut ViewContext<Editor>,
 1141    ) -> AnyElement {
 1142        let settings = EditorSettings::get_global(cx);
 1143        let show_completion_documentation = settings.show_completion_documentation;
 1144
 1145        let widest_completion_ix = self
 1146            .matches
 1147            .iter()
 1148            .enumerate()
 1149            .max_by_key(|(_, mat)| {
 1150                let completions = self.completions.read();
 1151                let completion = &completions[mat.candidate_id];
 1152                let documentation = &completion.documentation;
 1153
 1154                let mut len = completion.label.text.chars().count();
 1155                if let Some(Documentation::SingleLine(text)) = documentation {
 1156                    if show_completion_documentation {
 1157                        len += text.chars().count();
 1158                    }
 1159                }
 1160
 1161                len
 1162            })
 1163            .map(|(ix, _)| ix);
 1164
 1165        let completions = self.completions.clone();
 1166        let matches = self.matches.clone();
 1167        let selected_item = self.selected_item;
 1168        let style = style.clone();
 1169
 1170        let multiline_docs = if show_completion_documentation {
 1171            let mat = &self.matches[selected_item];
 1172            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1173                Some(Documentation::MultiLinePlainText(text)) => {
 1174                    Some(div().child(SharedString::from(text.clone())))
 1175                }
 1176                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1177                    Some(div().child(render_parsed_markdown(
 1178                        "completions_markdown",
 1179                        parsed,
 1180                        &style,
 1181                        workspace,
 1182                        cx,
 1183                    )))
 1184                }
 1185                _ => None,
 1186            };
 1187            multiline_docs.map(|div| {
 1188                div.id("multiline_docs")
 1189                    .max_h(max_height)
 1190                    .flex_1()
 1191                    .px_1p5()
 1192                    .py_1()
 1193                    .min_w(px(260.))
 1194                    .max_w(px(640.))
 1195                    .w(px(500.))
 1196                    .overflow_y_scroll()
 1197                    .occlude()
 1198            })
 1199        } else {
 1200            None
 1201        };
 1202
 1203        let list = uniform_list(
 1204            cx.view().clone(),
 1205            "completions",
 1206            matches.len(),
 1207            move |_editor, range, cx| {
 1208                let start_ix = range.start;
 1209                let completions_guard = completions.read();
 1210
 1211                matches[range]
 1212                    .iter()
 1213                    .enumerate()
 1214                    .map(|(ix, mat)| {
 1215                        let item_ix = start_ix + ix;
 1216                        let candidate_id = mat.candidate_id;
 1217                        let completion = &completions_guard[candidate_id];
 1218
 1219                        let documentation = if show_completion_documentation {
 1220                            &completion.documentation
 1221                        } else {
 1222                            &None
 1223                        };
 1224
 1225                        let highlights = gpui::combine_highlights(
 1226                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1227                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1228                                |(range, mut highlight)| {
 1229                                    // Ignore font weight for syntax highlighting, as we'll use it
 1230                                    // for fuzzy matches.
 1231                                    highlight.font_weight = None;
 1232
 1233                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1234                                        highlight.strikethrough = Some(StrikethroughStyle {
 1235                                            thickness: 1.0.into(),
 1236                                            ..Default::default()
 1237                                        });
 1238                                        highlight.color = Some(cx.theme().colors().text_muted);
 1239                                    }
 1240
 1241                                    (range, highlight)
 1242                                },
 1243                            ),
 1244                        );
 1245                        let completion_label = StyledText::new(completion.label.text.clone())
 1246                            .with_highlights(&style.text, highlights);
 1247                        let documentation_label =
 1248                            if let Some(Documentation::SingleLine(text)) = documentation {
 1249                                if text.trim().is_empty() {
 1250                                    None
 1251                                } else {
 1252                                    Some(
 1253                                        Label::new(text.clone())
 1254                                            .ml_4()
 1255                                            .size(LabelSize::Small)
 1256                                            .color(Color::Muted),
 1257                                    )
 1258                                }
 1259                            } else {
 1260                                None
 1261                            };
 1262
 1263                        let color_swatch = completion
 1264                            .color()
 1265                            .map(|color| div().size_4().bg(color).rounded_sm());
 1266
 1267                        div().min_w(px(220.)).max_w(px(540.)).child(
 1268                            ListItem::new(mat.candidate_id)
 1269                                .inset(true)
 1270                                .selected(item_ix == selected_item)
 1271                                .on_click(cx.listener(move |editor, _event, cx| {
 1272                                    cx.stop_propagation();
 1273                                    if let Some(task) = editor.confirm_completion(
 1274                                        &ConfirmCompletion {
 1275                                            item_ix: Some(item_ix),
 1276                                        },
 1277                                        cx,
 1278                                    ) {
 1279                                        task.detach_and_log_err(cx)
 1280                                    }
 1281                                }))
 1282                                .start_slot::<Div>(color_swatch)
 1283                                .child(h_flex().overflow_hidden().child(completion_label))
 1284                                .end_slot::<Label>(documentation_label),
 1285                        )
 1286                    })
 1287                    .collect()
 1288            },
 1289        )
 1290        .occlude()
 1291        .max_h(max_height)
 1292        .track_scroll(self.scroll_handle.clone())
 1293        .with_width_from_item(widest_completion_ix)
 1294        .with_sizing_behavior(ListSizingBehavior::Infer);
 1295
 1296        Popover::new()
 1297            .child(list)
 1298            .when_some(multiline_docs, |popover, multiline_docs| {
 1299                popover.aside(multiline_docs)
 1300            })
 1301            .into_any_element()
 1302    }
 1303
 1304    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1305        let mut matches = if let Some(query) = query {
 1306            fuzzy::match_strings(
 1307                &self.match_candidates,
 1308                query,
 1309                query.chars().any(|c| c.is_uppercase()),
 1310                100,
 1311                &Default::default(),
 1312                executor,
 1313            )
 1314            .await
 1315        } else {
 1316            self.match_candidates
 1317                .iter()
 1318                .enumerate()
 1319                .map(|(candidate_id, candidate)| StringMatch {
 1320                    candidate_id,
 1321                    score: Default::default(),
 1322                    positions: Default::default(),
 1323                    string: candidate.string.clone(),
 1324                })
 1325                .collect()
 1326        };
 1327
 1328        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1329        if let Some(query) = query {
 1330            if let Some(query_start) = query.chars().next() {
 1331                matches.retain(|string_match| {
 1332                    split_words(&string_match.string).any(|word| {
 1333                        // Check that the first codepoint of the word as lowercase matches the first
 1334                        // codepoint of the query as lowercase
 1335                        word.chars()
 1336                            .flat_map(|codepoint| codepoint.to_lowercase())
 1337                            .zip(query_start.to_lowercase())
 1338                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1339                    })
 1340                });
 1341            }
 1342        }
 1343
 1344        let completions = self.completions.read();
 1345        if self.sort_completions {
 1346            matches.sort_unstable_by_key(|mat| {
 1347                // We do want to strike a balance here between what the language server tells us
 1348                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1349                // `Creat` and there is a local variable called `CreateComponent`).
 1350                // So what we do is: we bucket all matches into two buckets
 1351                // - Strong matches
 1352                // - Weak matches
 1353                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1354                // and the Weak matches are the rest.
 1355                //
 1356                // For the strong matches, we sort by the language-servers score first and for the weak
 1357                // matches, we prefer our fuzzy finder first.
 1358                //
 1359                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1360                // us into account when it's obviously a bad match.
 1361
 1362                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1363                enum MatchScore<'a> {
 1364                    Strong {
 1365                        sort_text: Option<&'a str>,
 1366                        score: Reverse<OrderedFloat<f64>>,
 1367                        sort_key: (usize, &'a str),
 1368                    },
 1369                    Weak {
 1370                        score: Reverse<OrderedFloat<f64>>,
 1371                        sort_text: Option<&'a str>,
 1372                        sort_key: (usize, &'a str),
 1373                    },
 1374                }
 1375
 1376                let completion = &completions[mat.candidate_id];
 1377                let sort_key = completion.sort_key();
 1378                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1379                let score = Reverse(OrderedFloat(mat.score));
 1380
 1381                if mat.score >= 0.2 {
 1382                    MatchScore::Strong {
 1383                        sort_text,
 1384                        score,
 1385                        sort_key,
 1386                    }
 1387                } else {
 1388                    MatchScore::Weak {
 1389                        score,
 1390                        sort_text,
 1391                        sort_key,
 1392                    }
 1393                }
 1394            });
 1395        }
 1396
 1397        for mat in &mut matches {
 1398            let completion = &completions[mat.candidate_id];
 1399            mat.string.clone_from(&completion.label.text);
 1400            for position in &mut mat.positions {
 1401                *position += completion.label.filter_range.start;
 1402            }
 1403        }
 1404        drop(completions);
 1405
 1406        self.matches = matches.into();
 1407        self.selected_item = 0;
 1408    }
 1409}
 1410
 1411struct AvailableCodeAction {
 1412    excerpt_id: ExcerptId,
 1413    action: CodeAction,
 1414    provider: Arc<dyn CodeActionProvider>,
 1415}
 1416
 1417#[derive(Clone)]
 1418struct CodeActionContents {
 1419    tasks: Option<Arc<ResolvedTasks>>,
 1420    actions: Option<Arc<[AvailableCodeAction]>>,
 1421}
 1422
 1423impl CodeActionContents {
 1424    fn len(&self) -> usize {
 1425        match (&self.tasks, &self.actions) {
 1426            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1427            (Some(tasks), None) => tasks.templates.len(),
 1428            (None, Some(actions)) => actions.len(),
 1429            (None, None) => 0,
 1430        }
 1431    }
 1432
 1433    fn is_empty(&self) -> bool {
 1434        match (&self.tasks, &self.actions) {
 1435            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1436            (Some(tasks), None) => tasks.templates.is_empty(),
 1437            (None, Some(actions)) => actions.is_empty(),
 1438            (None, None) => true,
 1439        }
 1440    }
 1441
 1442    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1443        self.tasks
 1444            .iter()
 1445            .flat_map(|tasks| {
 1446                tasks
 1447                    .templates
 1448                    .iter()
 1449                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1450            })
 1451            .chain(self.actions.iter().flat_map(|actions| {
 1452                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1453                    excerpt_id: available.excerpt_id,
 1454                    action: available.action.clone(),
 1455                    provider: available.provider.clone(),
 1456                })
 1457            }))
 1458    }
 1459    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1460        match (&self.tasks, &self.actions) {
 1461            (Some(tasks), Some(actions)) => {
 1462                if index < tasks.templates.len() {
 1463                    tasks
 1464                        .templates
 1465                        .get(index)
 1466                        .cloned()
 1467                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1468                } else {
 1469                    actions.get(index - tasks.templates.len()).map(|available| {
 1470                        CodeActionsItem::CodeAction {
 1471                            excerpt_id: available.excerpt_id,
 1472                            action: available.action.clone(),
 1473                            provider: available.provider.clone(),
 1474                        }
 1475                    })
 1476                }
 1477            }
 1478            (Some(tasks), None) => tasks
 1479                .templates
 1480                .get(index)
 1481                .cloned()
 1482                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1483            (None, Some(actions)) => {
 1484                actions
 1485                    .get(index)
 1486                    .map(|available| CodeActionsItem::CodeAction {
 1487                        excerpt_id: available.excerpt_id,
 1488                        action: available.action.clone(),
 1489                        provider: available.provider.clone(),
 1490                    })
 1491            }
 1492            (None, None) => None,
 1493        }
 1494    }
 1495}
 1496
 1497#[allow(clippy::large_enum_variant)]
 1498#[derive(Clone)]
 1499enum CodeActionsItem {
 1500    Task(TaskSourceKind, ResolvedTask),
 1501    CodeAction {
 1502        excerpt_id: ExcerptId,
 1503        action: CodeAction,
 1504        provider: Arc<dyn CodeActionProvider>,
 1505    },
 1506}
 1507
 1508impl CodeActionsItem {
 1509    fn as_task(&self) -> Option<&ResolvedTask> {
 1510        let Self::Task(_, task) = self else {
 1511            return None;
 1512        };
 1513        Some(task)
 1514    }
 1515    fn as_code_action(&self) -> Option<&CodeAction> {
 1516        let Self::CodeAction { action, .. } = self else {
 1517            return None;
 1518        };
 1519        Some(action)
 1520    }
 1521    fn label(&self) -> String {
 1522        match self {
 1523            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1524            Self::Task(_, task) => task.resolved_label.clone(),
 1525        }
 1526    }
 1527}
 1528
 1529struct CodeActionsMenu {
 1530    actions: CodeActionContents,
 1531    buffer: Model<Buffer>,
 1532    selected_item: usize,
 1533    scroll_handle: UniformListScrollHandle,
 1534    deployed_from_indicator: Option<DisplayRow>,
 1535}
 1536
 1537impl CodeActionsMenu {
 1538    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1539        self.selected_item = 0;
 1540        self.scroll_handle.scroll_to_item(self.selected_item);
 1541        cx.notify()
 1542    }
 1543
 1544    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1545        if self.selected_item > 0 {
 1546            self.selected_item -= 1;
 1547        } else {
 1548            self.selected_item = self.actions.len() - 1;
 1549        }
 1550        self.scroll_handle.scroll_to_item(self.selected_item);
 1551        cx.notify();
 1552    }
 1553
 1554    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1555        if self.selected_item + 1 < self.actions.len() {
 1556            self.selected_item += 1;
 1557        } else {
 1558            self.selected_item = 0;
 1559        }
 1560        self.scroll_handle.scroll_to_item(self.selected_item);
 1561        cx.notify();
 1562    }
 1563
 1564    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1565        self.selected_item = self.actions.len() - 1;
 1566        self.scroll_handle.scroll_to_item(self.selected_item);
 1567        cx.notify()
 1568    }
 1569
 1570    fn visible(&self) -> bool {
 1571        !self.actions.is_empty()
 1572    }
 1573
 1574    fn render(
 1575        &self,
 1576        cursor_position: DisplayPoint,
 1577        _style: &EditorStyle,
 1578        max_height: Pixels,
 1579        cx: &mut ViewContext<Editor>,
 1580    ) -> (ContextMenuOrigin, AnyElement) {
 1581        let actions = self.actions.clone();
 1582        let selected_item = self.selected_item;
 1583        let element = uniform_list(
 1584            cx.view().clone(),
 1585            "code_actions_menu",
 1586            self.actions.len(),
 1587            move |_this, range, cx| {
 1588                actions
 1589                    .iter()
 1590                    .skip(range.start)
 1591                    .take(range.end - range.start)
 1592                    .enumerate()
 1593                    .map(|(ix, action)| {
 1594                        let item_ix = range.start + ix;
 1595                        let selected = selected_item == item_ix;
 1596                        let colors = cx.theme().colors();
 1597                        div()
 1598                            .px_1()
 1599                            .rounded_md()
 1600                            .text_color(colors.text)
 1601                            .when(selected, |style| {
 1602                                style
 1603                                    .bg(colors.element_active)
 1604                                    .text_color(colors.text_accent)
 1605                            })
 1606                            .hover(|style| {
 1607                                style
 1608                                    .bg(colors.element_hover)
 1609                                    .text_color(colors.text_accent)
 1610                            })
 1611                            .whitespace_nowrap()
 1612                            .when_some(action.as_code_action(), |this, action| {
 1613                                this.on_mouse_down(
 1614                                    MouseButton::Left,
 1615                                    cx.listener(move |editor, _, cx| {
 1616                                        cx.stop_propagation();
 1617                                        if let Some(task) = editor.confirm_code_action(
 1618                                            &ConfirmCodeAction {
 1619                                                item_ix: Some(item_ix),
 1620                                            },
 1621                                            cx,
 1622                                        ) {
 1623                                            task.detach_and_log_err(cx)
 1624                                        }
 1625                                    }),
 1626                                )
 1627                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1628                                .child(SharedString::from(action.lsp_action.title.clone()))
 1629                            })
 1630                            .when_some(action.as_task(), |this, task| {
 1631                                this.on_mouse_down(
 1632                                    MouseButton::Left,
 1633                                    cx.listener(move |editor, _, cx| {
 1634                                        cx.stop_propagation();
 1635                                        if let Some(task) = editor.confirm_code_action(
 1636                                            &ConfirmCodeAction {
 1637                                                item_ix: Some(item_ix),
 1638                                            },
 1639                                            cx,
 1640                                        ) {
 1641                                            task.detach_and_log_err(cx)
 1642                                        }
 1643                                    }),
 1644                                )
 1645                                .child(SharedString::from(task.resolved_label.clone()))
 1646                            })
 1647                    })
 1648                    .collect()
 1649            },
 1650        )
 1651        .elevation_1(cx)
 1652        .p_1()
 1653        .max_h(max_height)
 1654        .occlude()
 1655        .track_scroll(self.scroll_handle.clone())
 1656        .with_width_from_item(
 1657            self.actions
 1658                .iter()
 1659                .enumerate()
 1660                .max_by_key(|(_, action)| match action {
 1661                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1662                    CodeActionsItem::CodeAction { action, .. } => {
 1663                        action.lsp_action.title.chars().count()
 1664                    }
 1665                })
 1666                .map(|(ix, _)| ix),
 1667        )
 1668        .with_sizing_behavior(ListSizingBehavior::Infer)
 1669        .into_any_element();
 1670
 1671        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1672            ContextMenuOrigin::GutterIndicator(row)
 1673        } else {
 1674            ContextMenuOrigin::EditorPoint(cursor_position)
 1675        };
 1676
 1677        (cursor_position, element)
 1678    }
 1679}
 1680
 1681#[derive(Debug)]
 1682struct ActiveDiagnosticGroup {
 1683    primary_range: Range<Anchor>,
 1684    primary_message: String,
 1685    group_id: usize,
 1686    blocks: HashMap<CustomBlockId, Diagnostic>,
 1687    is_valid: bool,
 1688}
 1689
 1690#[derive(Serialize, Deserialize, Clone, Debug)]
 1691pub struct ClipboardSelection {
 1692    pub len: usize,
 1693    pub is_entire_line: bool,
 1694    pub first_line_indent: u32,
 1695}
 1696
 1697#[derive(Debug)]
 1698pub(crate) struct NavigationData {
 1699    cursor_anchor: Anchor,
 1700    cursor_position: Point,
 1701    scroll_anchor: ScrollAnchor,
 1702    scroll_top_row: u32,
 1703}
 1704
 1705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1706pub enum GotoDefinitionKind {
 1707    Symbol,
 1708    Declaration,
 1709    Type,
 1710    Implementation,
 1711}
 1712
 1713#[derive(Debug, Clone)]
 1714enum InlayHintRefreshReason {
 1715    Toggle(bool),
 1716    SettingsChange(InlayHintSettings),
 1717    NewLinesShown,
 1718    BufferEdited(HashSet<Arc<Language>>),
 1719    RefreshRequested,
 1720    ExcerptsRemoved(Vec<ExcerptId>),
 1721}
 1722
 1723impl InlayHintRefreshReason {
 1724    fn description(&self) -> &'static str {
 1725        match self {
 1726            Self::Toggle(_) => "toggle",
 1727            Self::SettingsChange(_) => "settings change",
 1728            Self::NewLinesShown => "new lines shown",
 1729            Self::BufferEdited(_) => "buffer edited",
 1730            Self::RefreshRequested => "refresh requested",
 1731            Self::ExcerptsRemoved(_) => "excerpts removed",
 1732        }
 1733    }
 1734}
 1735
 1736pub(crate) struct FocusedBlock {
 1737    id: BlockId,
 1738    focus_handle: WeakFocusHandle,
 1739}
 1740
 1741impl Editor {
 1742    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1743        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1744        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1745        Self::new(
 1746            EditorMode::SingleLine { auto_width: false },
 1747            buffer,
 1748            None,
 1749            false,
 1750            cx,
 1751        )
 1752    }
 1753
 1754    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1755        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1756        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1757        Self::new(EditorMode::Full, buffer, None, false, cx)
 1758    }
 1759
 1760    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1761        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1762        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1763        Self::new(
 1764            EditorMode::SingleLine { auto_width: true },
 1765            buffer,
 1766            None,
 1767            false,
 1768            cx,
 1769        )
 1770    }
 1771
 1772    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1773        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1774        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1775        Self::new(
 1776            EditorMode::AutoHeight { max_lines },
 1777            buffer,
 1778            None,
 1779            false,
 1780            cx,
 1781        )
 1782    }
 1783
 1784    pub fn for_buffer(
 1785        buffer: Model<Buffer>,
 1786        project: Option<Model<Project>>,
 1787        cx: &mut ViewContext<Self>,
 1788    ) -> Self {
 1789        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1790        Self::new(EditorMode::Full, buffer, project, false, cx)
 1791    }
 1792
 1793    pub fn for_multibuffer(
 1794        buffer: Model<MultiBuffer>,
 1795        project: Option<Model<Project>>,
 1796        show_excerpt_controls: bool,
 1797        cx: &mut ViewContext<Self>,
 1798    ) -> Self {
 1799        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1800    }
 1801
 1802    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1803        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1804        let mut clone = Self::new(
 1805            self.mode,
 1806            self.buffer.clone(),
 1807            self.project.clone(),
 1808            show_excerpt_controls,
 1809            cx,
 1810        );
 1811        self.display_map.update(cx, |display_map, cx| {
 1812            let snapshot = display_map.snapshot(cx);
 1813            clone.display_map.update(cx, |display_map, cx| {
 1814                display_map.set_state(&snapshot, cx);
 1815            });
 1816        });
 1817        clone.selections.clone_state(&self.selections);
 1818        clone.scroll_manager.clone_state(&self.scroll_manager);
 1819        clone.searchable = self.searchable;
 1820        clone
 1821    }
 1822
 1823    pub fn new(
 1824        mode: EditorMode,
 1825        buffer: Model<MultiBuffer>,
 1826        project: Option<Model<Project>>,
 1827        show_excerpt_controls: bool,
 1828        cx: &mut ViewContext<Self>,
 1829    ) -> Self {
 1830        let style = cx.text_style();
 1831        let font_size = style.font_size.to_pixels(cx.rem_size());
 1832        let editor = cx.view().downgrade();
 1833        let fold_placeholder = FoldPlaceholder {
 1834            constrain_width: true,
 1835            render: Arc::new(move |fold_id, fold_range, cx| {
 1836                let editor = editor.clone();
 1837                div()
 1838                    .id(fold_id)
 1839                    .bg(cx.theme().colors().ghost_element_background)
 1840                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1841                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1842                    .rounded_sm()
 1843                    .size_full()
 1844                    .cursor_pointer()
 1845                    .child("")
 1846                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1847                    .on_click(move |_, cx| {
 1848                        editor
 1849                            .update(cx, |editor, cx| {
 1850                                editor.unfold_ranges(
 1851                                    [fold_range.start..fold_range.end],
 1852                                    true,
 1853                                    false,
 1854                                    cx,
 1855                                );
 1856                                cx.stop_propagation();
 1857                            })
 1858                            .ok();
 1859                    })
 1860                    .into_any()
 1861            }),
 1862            merge_adjacent: true,
 1863        };
 1864        let display_map = cx.new_model(|cx| {
 1865            DisplayMap::new(
 1866                buffer.clone(),
 1867                style.font(),
 1868                font_size,
 1869                None,
 1870                show_excerpt_controls,
 1871                FILE_HEADER_HEIGHT,
 1872                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1873                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1874                fold_placeholder,
 1875                cx,
 1876            )
 1877        });
 1878
 1879        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1880
 1881        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1882
 1883        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1884            .then(|| language_settings::SoftWrap::None);
 1885
 1886        let mut project_subscriptions = Vec::new();
 1887        if mode == EditorMode::Full {
 1888            if let Some(project) = project.as_ref() {
 1889                if buffer.read(cx).is_singleton() {
 1890                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1891                        cx.emit(EditorEvent::TitleChanged);
 1892                    }));
 1893                }
 1894                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1895                    if let project::Event::RefreshInlayHints = event {
 1896                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1897                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1898                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1899                            let focus_handle = editor.focus_handle(cx);
 1900                            if focus_handle.is_focused(cx) {
 1901                                let snapshot = buffer.read(cx).snapshot();
 1902                                for (range, snippet) in snippet_edits {
 1903                                    let editor_range =
 1904                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1905                                    editor
 1906                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1907                                        .ok();
 1908                                }
 1909                            }
 1910                        }
 1911                    }
 1912                }));
 1913                if let Some(task_inventory) = project
 1914                    .read(cx)
 1915                    .task_store()
 1916                    .read(cx)
 1917                    .task_inventory()
 1918                    .cloned()
 1919                {
 1920                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1921                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1922                    }));
 1923                }
 1924            }
 1925        }
 1926
 1927        let inlay_hint_settings = inlay_hint_settings(
 1928            selections.newest_anchor().head(),
 1929            &buffer.read(cx).snapshot(cx),
 1930            cx,
 1931        );
 1932        let focus_handle = cx.focus_handle();
 1933        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1934        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1935            .detach();
 1936        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1937            .detach();
 1938        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1939
 1940        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1941            Some(false)
 1942        } else {
 1943            None
 1944        };
 1945
 1946        let mut code_action_providers = Vec::new();
 1947        if let Some(project) = project.clone() {
 1948            code_action_providers.push(Arc::new(project) as Arc<_>);
 1949        }
 1950
 1951        let mut this = Self {
 1952            focus_handle,
 1953            show_cursor_when_unfocused: false,
 1954            last_focused_descendant: None,
 1955            buffer: buffer.clone(),
 1956            display_map: display_map.clone(),
 1957            selections,
 1958            scroll_manager: ScrollManager::new(cx),
 1959            columnar_selection_tail: None,
 1960            add_selections_state: None,
 1961            select_next_state: None,
 1962            select_prev_state: None,
 1963            selection_history: Default::default(),
 1964            autoclose_regions: Default::default(),
 1965            snippet_stack: Default::default(),
 1966            select_larger_syntax_node_stack: Vec::new(),
 1967            ime_transaction: Default::default(),
 1968            active_diagnostics: None,
 1969            soft_wrap_mode_override,
 1970            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1971            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1972            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1973            project,
 1974            blink_manager: blink_manager.clone(),
 1975            show_local_selections: true,
 1976            mode,
 1977            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1978            show_gutter: mode == EditorMode::Full,
 1979            show_line_numbers: None,
 1980            use_relative_line_numbers: None,
 1981            show_git_diff_gutter: None,
 1982            show_code_actions: None,
 1983            show_runnables: None,
 1984            show_wrap_guides: None,
 1985            show_indent_guides,
 1986            placeholder_text: None,
 1987            highlight_order: 0,
 1988            highlighted_rows: HashMap::default(),
 1989            background_highlights: Default::default(),
 1990            gutter_highlights: TreeMap::default(),
 1991            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1992            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1993            nav_history: None,
 1994            context_menu: RwLock::new(None),
 1995            mouse_context_menu: None,
 1996            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1997            completion_tasks: Default::default(),
 1998            signature_help_state: SignatureHelpState::default(),
 1999            auto_signature_help: None,
 2000            find_all_references_task_sources: Vec::new(),
 2001            next_completion_id: 0,
 2002            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2003            next_inlay_id: 0,
 2004            code_action_providers,
 2005            available_code_actions: Default::default(),
 2006            code_actions_task: Default::default(),
 2007            document_highlights_task: Default::default(),
 2008            linked_editing_range_task: Default::default(),
 2009            pending_rename: Default::default(),
 2010            searchable: true,
 2011            cursor_shape: EditorSettings::get_global(cx)
 2012                .cursor_shape
 2013                .unwrap_or_default(),
 2014            current_line_highlight: None,
 2015            autoindent_mode: Some(AutoindentMode::EachLine),
 2016            collapse_matches: false,
 2017            workspace: None,
 2018            input_enabled: true,
 2019            use_modal_editing: mode == EditorMode::Full,
 2020            read_only: false,
 2021            use_autoclose: true,
 2022            use_auto_surround: true,
 2023            auto_replace_emoji_shortcode: false,
 2024            leader_peer_id: None,
 2025            remote_id: None,
 2026            hover_state: Default::default(),
 2027            hovered_link_state: Default::default(),
 2028            inline_completion_provider: None,
 2029            active_inline_completion: None,
 2030            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2031            expanded_hunks: ExpandedHunks::default(),
 2032            gutter_hovered: false,
 2033            pixel_position_of_newest_cursor: None,
 2034            last_bounds: None,
 2035            expect_bounds_change: None,
 2036            gutter_dimensions: GutterDimensions::default(),
 2037            style: None,
 2038            show_cursor_names: false,
 2039            hovered_cursors: Default::default(),
 2040            next_editor_action_id: EditorActionId::default(),
 2041            editor_actions: Rc::default(),
 2042            show_inline_completions_override: None,
 2043            enable_inline_completions: true,
 2044            custom_context_menu: None,
 2045            show_git_blame_gutter: false,
 2046            show_git_blame_inline: false,
 2047            show_selection_menu: None,
 2048            show_git_blame_inline_delay_task: None,
 2049            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2050            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2051                .session
 2052                .restore_unsaved_buffers,
 2053            blame: None,
 2054            blame_subscription: None,
 2055            tasks: Default::default(),
 2056            _subscriptions: vec![
 2057                cx.observe(&buffer, Self::on_buffer_changed),
 2058                cx.subscribe(&buffer, Self::on_buffer_event),
 2059                cx.observe(&display_map, Self::on_display_map_changed),
 2060                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2061                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2062                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2063                cx.observe_window_activation(|editor, cx| {
 2064                    let active = cx.is_window_active();
 2065                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2066                        if active {
 2067                            blink_manager.enable(cx);
 2068                        } else {
 2069                            blink_manager.disable(cx);
 2070                        }
 2071                    });
 2072                }),
 2073            ],
 2074            tasks_update_task: None,
 2075            linked_edit_ranges: Default::default(),
 2076            previous_search_ranges: None,
 2077            breadcrumb_header: None,
 2078            focused_block: None,
 2079            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2080            addons: HashMap::default(),
 2081            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2082            text_style_refinement: None,
 2083        };
 2084        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2085        this._subscriptions.extend(project_subscriptions);
 2086
 2087        this.end_selection(cx);
 2088        this.scroll_manager.show_scrollbar(cx);
 2089
 2090        if mode == EditorMode::Full {
 2091            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2092            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2093
 2094            if this.git_blame_inline_enabled {
 2095                this.git_blame_inline_enabled = true;
 2096                this.start_git_blame_inline(false, cx);
 2097            }
 2098        }
 2099
 2100        this.report_editor_event("open", None, cx);
 2101        this
 2102    }
 2103
 2104    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2105        self.mouse_context_menu
 2106            .as_ref()
 2107            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2108    }
 2109
 2110    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2111        let mut key_context = KeyContext::new_with_defaults();
 2112        key_context.add("Editor");
 2113        let mode = match self.mode {
 2114            EditorMode::SingleLine { .. } => "single_line",
 2115            EditorMode::AutoHeight { .. } => "auto_height",
 2116            EditorMode::Full => "full",
 2117        };
 2118
 2119        if EditorSettings::jupyter_enabled(cx) {
 2120            key_context.add("jupyter");
 2121        }
 2122
 2123        key_context.set("mode", mode);
 2124        if self.pending_rename.is_some() {
 2125            key_context.add("renaming");
 2126        }
 2127        if self.context_menu_visible() {
 2128            match self.context_menu.read().as_ref() {
 2129                Some(ContextMenu::Completions(_)) => {
 2130                    key_context.add("menu");
 2131                    key_context.add("showing_completions")
 2132                }
 2133                Some(ContextMenu::CodeActions(_)) => {
 2134                    key_context.add("menu");
 2135                    key_context.add("showing_code_actions")
 2136                }
 2137                None => {}
 2138            }
 2139        }
 2140
 2141        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2142        if !self.focus_handle(cx).contains_focused(cx)
 2143            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2144        {
 2145            for addon in self.addons.values() {
 2146                addon.extend_key_context(&mut key_context, cx)
 2147            }
 2148        }
 2149
 2150        if let Some(extension) = self
 2151            .buffer
 2152            .read(cx)
 2153            .as_singleton()
 2154            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2155        {
 2156            key_context.set("extension", extension.to_string());
 2157        }
 2158
 2159        if self.has_active_inline_completion(cx) {
 2160            key_context.add("copilot_suggestion");
 2161            key_context.add("inline_completion");
 2162        }
 2163
 2164        key_context
 2165    }
 2166
 2167    pub fn new_file(
 2168        workspace: &mut Workspace,
 2169        _: &workspace::NewFile,
 2170        cx: &mut ViewContext<Workspace>,
 2171    ) {
 2172        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2173            "Failed to create buffer",
 2174            cx,
 2175            |e, _| match e.error_code() {
 2176                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2177                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2178                e.error_tag("required").unwrap_or("the latest version")
 2179            )),
 2180                _ => None,
 2181            },
 2182        );
 2183    }
 2184
 2185    pub fn new_in_workspace(
 2186        workspace: &mut Workspace,
 2187        cx: &mut ViewContext<Workspace>,
 2188    ) -> Task<Result<View<Editor>>> {
 2189        let project = workspace.project().clone();
 2190        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2191
 2192        cx.spawn(|workspace, mut cx| async move {
 2193            let buffer = create.await?;
 2194            workspace.update(&mut cx, |workspace, cx| {
 2195                let editor =
 2196                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2197                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2198                editor
 2199            })
 2200        })
 2201    }
 2202
 2203    fn new_file_vertical(
 2204        workspace: &mut Workspace,
 2205        _: &workspace::NewFileSplitVertical,
 2206        cx: &mut ViewContext<Workspace>,
 2207    ) {
 2208        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2209    }
 2210
 2211    fn new_file_horizontal(
 2212        workspace: &mut Workspace,
 2213        _: &workspace::NewFileSplitHorizontal,
 2214        cx: &mut ViewContext<Workspace>,
 2215    ) {
 2216        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2217    }
 2218
 2219    fn new_file_in_direction(
 2220        workspace: &mut Workspace,
 2221        direction: SplitDirection,
 2222        cx: &mut ViewContext<Workspace>,
 2223    ) {
 2224        let project = workspace.project().clone();
 2225        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2226
 2227        cx.spawn(|workspace, mut cx| async move {
 2228            let buffer = create.await?;
 2229            workspace.update(&mut cx, move |workspace, cx| {
 2230                workspace.split_item(
 2231                    direction,
 2232                    Box::new(
 2233                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2234                    ),
 2235                    cx,
 2236                )
 2237            })?;
 2238            anyhow::Ok(())
 2239        })
 2240        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2241            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2242                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2243                e.error_tag("required").unwrap_or("the latest version")
 2244            )),
 2245            _ => None,
 2246        });
 2247    }
 2248
 2249    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2250        self.leader_peer_id
 2251    }
 2252
 2253    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2254        &self.buffer
 2255    }
 2256
 2257    pub fn workspace(&self) -> Option<View<Workspace>> {
 2258        self.workspace.as_ref()?.0.upgrade()
 2259    }
 2260
 2261    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2262        self.buffer().read(cx).title(cx)
 2263    }
 2264
 2265    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2266        let git_blame_gutter_max_author_length = self
 2267            .render_git_blame_gutter(cx)
 2268            .then(|| {
 2269                if let Some(blame) = self.blame.as_ref() {
 2270                    let max_author_length =
 2271                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2272                    Some(max_author_length)
 2273                } else {
 2274                    None
 2275                }
 2276            })
 2277            .flatten();
 2278
 2279        EditorSnapshot {
 2280            mode: self.mode,
 2281            show_gutter: self.show_gutter,
 2282            show_line_numbers: self.show_line_numbers,
 2283            show_git_diff_gutter: self.show_git_diff_gutter,
 2284            show_code_actions: self.show_code_actions,
 2285            show_runnables: self.show_runnables,
 2286            git_blame_gutter_max_author_length,
 2287            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2288            scroll_anchor: self.scroll_manager.anchor(),
 2289            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2290            placeholder_text: self.placeholder_text.clone(),
 2291            is_focused: self.focus_handle.is_focused(cx),
 2292            current_line_highlight: self
 2293                .current_line_highlight
 2294                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2295            gutter_hovered: self.gutter_hovered,
 2296        }
 2297    }
 2298
 2299    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2300        self.buffer.read(cx).language_at(point, cx)
 2301    }
 2302
 2303    pub fn file_at<T: ToOffset>(
 2304        &self,
 2305        point: T,
 2306        cx: &AppContext,
 2307    ) -> Option<Arc<dyn language::File>> {
 2308        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2309    }
 2310
 2311    pub fn active_excerpt(
 2312        &self,
 2313        cx: &AppContext,
 2314    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2315        self.buffer
 2316            .read(cx)
 2317            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2318    }
 2319
 2320    pub fn mode(&self) -> EditorMode {
 2321        self.mode
 2322    }
 2323
 2324    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2325        self.collaboration_hub.as_deref()
 2326    }
 2327
 2328    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2329        self.collaboration_hub = Some(hub);
 2330    }
 2331
 2332    pub fn set_custom_context_menu(
 2333        &mut self,
 2334        f: impl 'static
 2335            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2336    ) {
 2337        self.custom_context_menu = Some(Box::new(f))
 2338    }
 2339
 2340    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2341        self.completion_provider = provider;
 2342    }
 2343
 2344    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2345        self.semantics_provider.clone()
 2346    }
 2347
 2348    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2349        self.semantics_provider = provider;
 2350    }
 2351
 2352    pub fn set_inline_completion_provider<T>(
 2353        &mut self,
 2354        provider: Option<Model<T>>,
 2355        cx: &mut ViewContext<Self>,
 2356    ) where
 2357        T: InlineCompletionProvider,
 2358    {
 2359        self.inline_completion_provider =
 2360            provider.map(|provider| RegisteredInlineCompletionProvider {
 2361                _subscription: cx.observe(&provider, |this, _, cx| {
 2362                    if this.focus_handle.is_focused(cx) {
 2363                        this.update_visible_inline_completion(cx);
 2364                    }
 2365                }),
 2366                provider: Arc::new(provider),
 2367            });
 2368        self.refresh_inline_completion(false, false, cx);
 2369    }
 2370
 2371    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2372        self.placeholder_text.as_deref()
 2373    }
 2374
 2375    pub fn set_placeholder_text(
 2376        &mut self,
 2377        placeholder_text: impl Into<Arc<str>>,
 2378        cx: &mut ViewContext<Self>,
 2379    ) {
 2380        let placeholder_text = Some(placeholder_text.into());
 2381        if self.placeholder_text != placeholder_text {
 2382            self.placeholder_text = placeholder_text;
 2383            cx.notify();
 2384        }
 2385    }
 2386
 2387    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2388        self.cursor_shape = cursor_shape;
 2389
 2390        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2391        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2392
 2393        cx.notify();
 2394    }
 2395
 2396    pub fn set_current_line_highlight(
 2397        &mut self,
 2398        current_line_highlight: Option<CurrentLineHighlight>,
 2399    ) {
 2400        self.current_line_highlight = current_line_highlight;
 2401    }
 2402
 2403    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2404        self.collapse_matches = collapse_matches;
 2405    }
 2406
 2407    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2408        if self.collapse_matches {
 2409            return range.start..range.start;
 2410        }
 2411        range.clone()
 2412    }
 2413
 2414    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2415        if self.display_map.read(cx).clip_at_line_ends != clip {
 2416            self.display_map
 2417                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2418        }
 2419    }
 2420
 2421    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2422        self.input_enabled = input_enabled;
 2423    }
 2424
 2425    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2426        self.enable_inline_completions = enabled;
 2427    }
 2428
 2429    pub fn set_autoindent(&mut self, autoindent: bool) {
 2430        if autoindent {
 2431            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2432        } else {
 2433            self.autoindent_mode = None;
 2434        }
 2435    }
 2436
 2437    pub fn read_only(&self, cx: &AppContext) -> bool {
 2438        self.read_only || self.buffer.read(cx).read_only()
 2439    }
 2440
 2441    pub fn set_read_only(&mut self, read_only: bool) {
 2442        self.read_only = read_only;
 2443    }
 2444
 2445    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2446        self.use_autoclose = autoclose;
 2447    }
 2448
 2449    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2450        self.use_auto_surround = auto_surround;
 2451    }
 2452
 2453    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2454        self.auto_replace_emoji_shortcode = auto_replace;
 2455    }
 2456
 2457    pub fn toggle_inline_completions(
 2458        &mut self,
 2459        _: &ToggleInlineCompletions,
 2460        cx: &mut ViewContext<Self>,
 2461    ) {
 2462        if self.show_inline_completions_override.is_some() {
 2463            self.set_show_inline_completions(None, cx);
 2464        } else {
 2465            let cursor = self.selections.newest_anchor().head();
 2466            if let Some((buffer, cursor_buffer_position)) =
 2467                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2468            {
 2469                let show_inline_completions =
 2470                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2471                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2472            }
 2473        }
 2474    }
 2475
 2476    pub fn set_show_inline_completions(
 2477        &mut self,
 2478        show_inline_completions: Option<bool>,
 2479        cx: &mut ViewContext<Self>,
 2480    ) {
 2481        self.show_inline_completions_override = show_inline_completions;
 2482        self.refresh_inline_completion(false, true, cx);
 2483    }
 2484
 2485    fn should_show_inline_completions(
 2486        &self,
 2487        buffer: &Model<Buffer>,
 2488        buffer_position: language::Anchor,
 2489        cx: &AppContext,
 2490    ) -> bool {
 2491        if let Some(provider) = self.inline_completion_provider() {
 2492            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2493                show_inline_completions
 2494            } else {
 2495                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2496            }
 2497        } else {
 2498            false
 2499        }
 2500    }
 2501
 2502    pub fn set_use_modal_editing(&mut self, to: bool) {
 2503        self.use_modal_editing = to;
 2504    }
 2505
 2506    pub fn use_modal_editing(&self) -> bool {
 2507        self.use_modal_editing
 2508    }
 2509
 2510    fn selections_did_change(
 2511        &mut self,
 2512        local: bool,
 2513        old_cursor_position: &Anchor,
 2514        show_completions: bool,
 2515        cx: &mut ViewContext<Self>,
 2516    ) {
 2517        cx.invalidate_character_coordinates();
 2518
 2519        // Copy selections to primary selection buffer
 2520        #[cfg(target_os = "linux")]
 2521        if local {
 2522            let selections = self.selections.all::<usize>(cx);
 2523            let buffer_handle = self.buffer.read(cx).read(cx);
 2524
 2525            let mut text = String::new();
 2526            for (index, selection) in selections.iter().enumerate() {
 2527                let text_for_selection = buffer_handle
 2528                    .text_for_range(selection.start..selection.end)
 2529                    .collect::<String>();
 2530
 2531                text.push_str(&text_for_selection);
 2532                if index != selections.len() - 1 {
 2533                    text.push('\n');
 2534                }
 2535            }
 2536
 2537            if !text.is_empty() {
 2538                cx.write_to_primary(ClipboardItem::new_string(text));
 2539            }
 2540        }
 2541
 2542        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2543            self.buffer.update(cx, |buffer, cx| {
 2544                buffer.set_active_selections(
 2545                    &self.selections.disjoint_anchors(),
 2546                    self.selections.line_mode,
 2547                    self.cursor_shape,
 2548                    cx,
 2549                )
 2550            });
 2551        }
 2552        let display_map = self
 2553            .display_map
 2554            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2555        let buffer = &display_map.buffer_snapshot;
 2556        self.add_selections_state = None;
 2557        self.select_next_state = None;
 2558        self.select_prev_state = None;
 2559        self.select_larger_syntax_node_stack.clear();
 2560        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2561        self.snippet_stack
 2562            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2563        self.take_rename(false, cx);
 2564
 2565        let new_cursor_position = self.selections.newest_anchor().head();
 2566
 2567        self.push_to_nav_history(
 2568            *old_cursor_position,
 2569            Some(new_cursor_position.to_point(buffer)),
 2570            cx,
 2571        );
 2572
 2573        if local {
 2574            let new_cursor_position = self.selections.newest_anchor().head();
 2575            let mut context_menu = self.context_menu.write();
 2576            let completion_menu = match context_menu.as_ref() {
 2577                Some(ContextMenu::Completions(menu)) => Some(menu),
 2578
 2579                _ => {
 2580                    *context_menu = None;
 2581                    None
 2582                }
 2583            };
 2584
 2585            if let Some(completion_menu) = completion_menu {
 2586                let cursor_position = new_cursor_position.to_offset(buffer);
 2587                let (word_range, kind) =
 2588                    buffer.surrounding_word(completion_menu.initial_position, true);
 2589                if kind == Some(CharKind::Word)
 2590                    && word_range.to_inclusive().contains(&cursor_position)
 2591                {
 2592                    let mut completion_menu = completion_menu.clone();
 2593                    drop(context_menu);
 2594
 2595                    let query = Self::completion_query(buffer, cursor_position);
 2596                    cx.spawn(move |this, mut cx| async move {
 2597                        completion_menu
 2598                            .filter(query.as_deref(), cx.background_executor().clone())
 2599                            .await;
 2600
 2601                        this.update(&mut cx, |this, cx| {
 2602                            let mut context_menu = this.context_menu.write();
 2603                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2604                                return;
 2605                            };
 2606
 2607                            if menu.id > completion_menu.id {
 2608                                return;
 2609                            }
 2610
 2611                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2612                            drop(context_menu);
 2613                            cx.notify();
 2614                        })
 2615                    })
 2616                    .detach();
 2617
 2618                    if show_completions {
 2619                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2620                    }
 2621                } else {
 2622                    drop(context_menu);
 2623                    self.hide_context_menu(cx);
 2624                }
 2625            } else {
 2626                drop(context_menu);
 2627            }
 2628
 2629            hide_hover(self, cx);
 2630
 2631            if old_cursor_position.to_display_point(&display_map).row()
 2632                != new_cursor_position.to_display_point(&display_map).row()
 2633            {
 2634                self.available_code_actions.take();
 2635            }
 2636            self.refresh_code_actions(cx);
 2637            self.refresh_document_highlights(cx);
 2638            refresh_matching_bracket_highlights(self, cx);
 2639            self.discard_inline_completion(false, cx);
 2640            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2641            if self.git_blame_inline_enabled {
 2642                self.start_inline_blame_timer(cx);
 2643            }
 2644        }
 2645
 2646        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2647        cx.emit(EditorEvent::SelectionsChanged { local });
 2648
 2649        if self.selections.disjoint_anchors().len() == 1 {
 2650            cx.emit(SearchEvent::ActiveMatchChanged)
 2651        }
 2652        cx.notify();
 2653    }
 2654
 2655    pub fn change_selections<R>(
 2656        &mut self,
 2657        autoscroll: Option<Autoscroll>,
 2658        cx: &mut ViewContext<Self>,
 2659        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2660    ) -> R {
 2661        self.change_selections_inner(autoscroll, true, cx, change)
 2662    }
 2663
 2664    pub fn change_selections_inner<R>(
 2665        &mut self,
 2666        autoscroll: Option<Autoscroll>,
 2667        request_completions: bool,
 2668        cx: &mut ViewContext<Self>,
 2669        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2670    ) -> R {
 2671        let old_cursor_position = self.selections.newest_anchor().head();
 2672        self.push_to_selection_history();
 2673
 2674        let (changed, result) = self.selections.change_with(cx, change);
 2675
 2676        if changed {
 2677            if let Some(autoscroll) = autoscroll {
 2678                self.request_autoscroll(autoscroll, cx);
 2679            }
 2680            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2681
 2682            if self.should_open_signature_help_automatically(
 2683                &old_cursor_position,
 2684                self.signature_help_state.backspace_pressed(),
 2685                cx,
 2686            ) {
 2687                self.show_signature_help(&ShowSignatureHelp, cx);
 2688            }
 2689            self.signature_help_state.set_backspace_pressed(false);
 2690        }
 2691
 2692        result
 2693    }
 2694
 2695    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2696    where
 2697        I: IntoIterator<Item = (Range<S>, T)>,
 2698        S: ToOffset,
 2699        T: Into<Arc<str>>,
 2700    {
 2701        if self.read_only(cx) {
 2702            return;
 2703        }
 2704
 2705        self.buffer
 2706            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2707    }
 2708
 2709    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2710    where
 2711        I: IntoIterator<Item = (Range<S>, T)>,
 2712        S: ToOffset,
 2713        T: Into<Arc<str>>,
 2714    {
 2715        if self.read_only(cx) {
 2716            return;
 2717        }
 2718
 2719        self.buffer.update(cx, |buffer, cx| {
 2720            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2721        });
 2722    }
 2723
 2724    pub fn edit_with_block_indent<I, S, T>(
 2725        &mut self,
 2726        edits: I,
 2727        original_indent_columns: Vec<u32>,
 2728        cx: &mut ViewContext<Self>,
 2729    ) where
 2730        I: IntoIterator<Item = (Range<S>, T)>,
 2731        S: ToOffset,
 2732        T: Into<Arc<str>>,
 2733    {
 2734        if self.read_only(cx) {
 2735            return;
 2736        }
 2737
 2738        self.buffer.update(cx, |buffer, cx| {
 2739            buffer.edit(
 2740                edits,
 2741                Some(AutoindentMode::Block {
 2742                    original_indent_columns,
 2743                }),
 2744                cx,
 2745            )
 2746        });
 2747    }
 2748
 2749    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2750        self.hide_context_menu(cx);
 2751
 2752        match phase {
 2753            SelectPhase::Begin {
 2754                position,
 2755                add,
 2756                click_count,
 2757            } => self.begin_selection(position, add, click_count, cx),
 2758            SelectPhase::BeginColumnar {
 2759                position,
 2760                goal_column,
 2761                reset,
 2762            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2763            SelectPhase::Extend {
 2764                position,
 2765                click_count,
 2766            } => self.extend_selection(position, click_count, cx),
 2767            SelectPhase::Update {
 2768                position,
 2769                goal_column,
 2770                scroll_delta,
 2771            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2772            SelectPhase::End => self.end_selection(cx),
 2773        }
 2774    }
 2775
 2776    fn extend_selection(
 2777        &mut self,
 2778        position: DisplayPoint,
 2779        click_count: usize,
 2780        cx: &mut ViewContext<Self>,
 2781    ) {
 2782        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2783        let tail = self.selections.newest::<usize>(cx).tail();
 2784        self.begin_selection(position, false, click_count, cx);
 2785
 2786        let position = position.to_offset(&display_map, Bias::Left);
 2787        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2788
 2789        let mut pending_selection = self
 2790            .selections
 2791            .pending_anchor()
 2792            .expect("extend_selection not called with pending selection");
 2793        if position >= tail {
 2794            pending_selection.start = tail_anchor;
 2795        } else {
 2796            pending_selection.end = tail_anchor;
 2797            pending_selection.reversed = true;
 2798        }
 2799
 2800        let mut pending_mode = self.selections.pending_mode().unwrap();
 2801        match &mut pending_mode {
 2802            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2803            _ => {}
 2804        }
 2805
 2806        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2807            s.set_pending(pending_selection, pending_mode)
 2808        });
 2809    }
 2810
 2811    fn begin_selection(
 2812        &mut self,
 2813        position: DisplayPoint,
 2814        add: bool,
 2815        click_count: usize,
 2816        cx: &mut ViewContext<Self>,
 2817    ) {
 2818        if !self.focus_handle.is_focused(cx) {
 2819            self.last_focused_descendant = None;
 2820            cx.focus(&self.focus_handle);
 2821        }
 2822
 2823        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2824        let buffer = &display_map.buffer_snapshot;
 2825        let newest_selection = self.selections.newest_anchor().clone();
 2826        let position = display_map.clip_point(position, Bias::Left);
 2827
 2828        let start;
 2829        let end;
 2830        let mode;
 2831        let auto_scroll;
 2832        match click_count {
 2833            1 => {
 2834                start = buffer.anchor_before(position.to_point(&display_map));
 2835                end = start;
 2836                mode = SelectMode::Character;
 2837                auto_scroll = true;
 2838            }
 2839            2 => {
 2840                let range = movement::surrounding_word(&display_map, position);
 2841                start = buffer.anchor_before(range.start.to_point(&display_map));
 2842                end = buffer.anchor_before(range.end.to_point(&display_map));
 2843                mode = SelectMode::Word(start..end);
 2844                auto_scroll = true;
 2845            }
 2846            3 => {
 2847                let position = display_map
 2848                    .clip_point(position, Bias::Left)
 2849                    .to_point(&display_map);
 2850                let line_start = display_map.prev_line_boundary(position).0;
 2851                let next_line_start = buffer.clip_point(
 2852                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2853                    Bias::Left,
 2854                );
 2855                start = buffer.anchor_before(line_start);
 2856                end = buffer.anchor_before(next_line_start);
 2857                mode = SelectMode::Line(start..end);
 2858                auto_scroll = true;
 2859            }
 2860            _ => {
 2861                start = buffer.anchor_before(0);
 2862                end = buffer.anchor_before(buffer.len());
 2863                mode = SelectMode::All;
 2864                auto_scroll = false;
 2865            }
 2866        }
 2867
 2868        let point_to_delete: Option<usize> = {
 2869            let selected_points: Vec<Selection<Point>> =
 2870                self.selections.disjoint_in_range(start..end, cx);
 2871
 2872            if !add || click_count > 1 {
 2873                None
 2874            } else if !selected_points.is_empty() {
 2875                Some(selected_points[0].id)
 2876            } else {
 2877                let clicked_point_already_selected =
 2878                    self.selections.disjoint.iter().find(|selection| {
 2879                        selection.start.to_point(buffer) == start.to_point(buffer)
 2880                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2881                    });
 2882
 2883                clicked_point_already_selected.map(|selection| selection.id)
 2884            }
 2885        };
 2886
 2887        let selections_count = self.selections.count();
 2888
 2889        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2890            if let Some(point_to_delete) = point_to_delete {
 2891                s.delete(point_to_delete);
 2892
 2893                if selections_count == 1 {
 2894                    s.set_pending_anchor_range(start..end, mode);
 2895                }
 2896            } else {
 2897                if !add {
 2898                    s.clear_disjoint();
 2899                } else if click_count > 1 {
 2900                    s.delete(newest_selection.id)
 2901                }
 2902
 2903                s.set_pending_anchor_range(start..end, mode);
 2904            }
 2905        });
 2906    }
 2907
 2908    fn begin_columnar_selection(
 2909        &mut self,
 2910        position: DisplayPoint,
 2911        goal_column: u32,
 2912        reset: bool,
 2913        cx: &mut ViewContext<Self>,
 2914    ) {
 2915        if !self.focus_handle.is_focused(cx) {
 2916            self.last_focused_descendant = None;
 2917            cx.focus(&self.focus_handle);
 2918        }
 2919
 2920        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2921
 2922        if reset {
 2923            let pointer_position = display_map
 2924                .buffer_snapshot
 2925                .anchor_before(position.to_point(&display_map));
 2926
 2927            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2928                s.clear_disjoint();
 2929                s.set_pending_anchor_range(
 2930                    pointer_position..pointer_position,
 2931                    SelectMode::Character,
 2932                );
 2933            });
 2934        }
 2935
 2936        let tail = self.selections.newest::<Point>(cx).tail();
 2937        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2938
 2939        if !reset {
 2940            self.select_columns(
 2941                tail.to_display_point(&display_map),
 2942                position,
 2943                goal_column,
 2944                &display_map,
 2945                cx,
 2946            );
 2947        }
 2948    }
 2949
 2950    fn update_selection(
 2951        &mut self,
 2952        position: DisplayPoint,
 2953        goal_column: u32,
 2954        scroll_delta: gpui::Point<f32>,
 2955        cx: &mut ViewContext<Self>,
 2956    ) {
 2957        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2958
 2959        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2960            let tail = tail.to_display_point(&display_map);
 2961            self.select_columns(tail, position, goal_column, &display_map, cx);
 2962        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2963            let buffer = self.buffer.read(cx).snapshot(cx);
 2964            let head;
 2965            let tail;
 2966            let mode = self.selections.pending_mode().unwrap();
 2967            match &mode {
 2968                SelectMode::Character => {
 2969                    head = position.to_point(&display_map);
 2970                    tail = pending.tail().to_point(&buffer);
 2971                }
 2972                SelectMode::Word(original_range) => {
 2973                    let original_display_range = original_range.start.to_display_point(&display_map)
 2974                        ..original_range.end.to_display_point(&display_map);
 2975                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2976                        ..original_display_range.end.to_point(&display_map);
 2977                    if movement::is_inside_word(&display_map, position)
 2978                        || original_display_range.contains(&position)
 2979                    {
 2980                        let word_range = movement::surrounding_word(&display_map, position);
 2981                        if word_range.start < original_display_range.start {
 2982                            head = word_range.start.to_point(&display_map);
 2983                        } else {
 2984                            head = word_range.end.to_point(&display_map);
 2985                        }
 2986                    } else {
 2987                        head = position.to_point(&display_map);
 2988                    }
 2989
 2990                    if head <= original_buffer_range.start {
 2991                        tail = original_buffer_range.end;
 2992                    } else {
 2993                        tail = original_buffer_range.start;
 2994                    }
 2995                }
 2996                SelectMode::Line(original_range) => {
 2997                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2998
 2999                    let position = display_map
 3000                        .clip_point(position, Bias::Left)
 3001                        .to_point(&display_map);
 3002                    let line_start = display_map.prev_line_boundary(position).0;
 3003                    let next_line_start = buffer.clip_point(
 3004                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3005                        Bias::Left,
 3006                    );
 3007
 3008                    if line_start < original_range.start {
 3009                        head = line_start
 3010                    } else {
 3011                        head = next_line_start
 3012                    }
 3013
 3014                    if head <= original_range.start {
 3015                        tail = original_range.end;
 3016                    } else {
 3017                        tail = original_range.start;
 3018                    }
 3019                }
 3020                SelectMode::All => {
 3021                    return;
 3022                }
 3023            };
 3024
 3025            if head < tail {
 3026                pending.start = buffer.anchor_before(head);
 3027                pending.end = buffer.anchor_before(tail);
 3028                pending.reversed = true;
 3029            } else {
 3030                pending.start = buffer.anchor_before(tail);
 3031                pending.end = buffer.anchor_before(head);
 3032                pending.reversed = false;
 3033            }
 3034
 3035            self.change_selections(None, cx, |s| {
 3036                s.set_pending(pending, mode);
 3037            });
 3038        } else {
 3039            log::error!("update_selection dispatched with no pending selection");
 3040            return;
 3041        }
 3042
 3043        self.apply_scroll_delta(scroll_delta, cx);
 3044        cx.notify();
 3045    }
 3046
 3047    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3048        self.columnar_selection_tail.take();
 3049        if self.selections.pending_anchor().is_some() {
 3050            let selections = self.selections.all::<usize>(cx);
 3051            self.change_selections(None, cx, |s| {
 3052                s.select(selections);
 3053                s.clear_pending();
 3054            });
 3055        }
 3056    }
 3057
 3058    fn select_columns(
 3059        &mut self,
 3060        tail: DisplayPoint,
 3061        head: DisplayPoint,
 3062        goal_column: u32,
 3063        display_map: &DisplaySnapshot,
 3064        cx: &mut ViewContext<Self>,
 3065    ) {
 3066        let start_row = cmp::min(tail.row(), head.row());
 3067        let end_row = cmp::max(tail.row(), head.row());
 3068        let start_column = cmp::min(tail.column(), goal_column);
 3069        let end_column = cmp::max(tail.column(), goal_column);
 3070        let reversed = start_column < tail.column();
 3071
 3072        let selection_ranges = (start_row.0..=end_row.0)
 3073            .map(DisplayRow)
 3074            .filter_map(|row| {
 3075                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3076                    let start = display_map
 3077                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3078                        .to_point(display_map);
 3079                    let end = display_map
 3080                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3081                        .to_point(display_map);
 3082                    if reversed {
 3083                        Some(end..start)
 3084                    } else {
 3085                        Some(start..end)
 3086                    }
 3087                } else {
 3088                    None
 3089                }
 3090            })
 3091            .collect::<Vec<_>>();
 3092
 3093        self.change_selections(None, cx, |s| {
 3094            s.select_ranges(selection_ranges);
 3095        });
 3096        cx.notify();
 3097    }
 3098
 3099    pub fn has_pending_nonempty_selection(&self) -> bool {
 3100        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3101            Some(Selection { start, end, .. }) => start != end,
 3102            None => false,
 3103        };
 3104
 3105        pending_nonempty_selection
 3106            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3107    }
 3108
 3109    pub fn has_pending_selection(&self) -> bool {
 3110        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3111    }
 3112
 3113    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3114        if self.clear_expanded_diff_hunks(cx) {
 3115            cx.notify();
 3116            return;
 3117        }
 3118        if self.dismiss_menus_and_popups(true, cx) {
 3119            return;
 3120        }
 3121
 3122        if self.mode == EditorMode::Full
 3123            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3124        {
 3125            return;
 3126        }
 3127
 3128        cx.propagate();
 3129    }
 3130
 3131    pub fn dismiss_menus_and_popups(
 3132        &mut self,
 3133        should_report_inline_completion_event: bool,
 3134        cx: &mut ViewContext<Self>,
 3135    ) -> bool {
 3136        if self.take_rename(false, cx).is_some() {
 3137            return true;
 3138        }
 3139
 3140        if hide_hover(self, cx) {
 3141            return true;
 3142        }
 3143
 3144        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3145            return true;
 3146        }
 3147
 3148        if self.hide_context_menu(cx).is_some() {
 3149            return true;
 3150        }
 3151
 3152        if self.mouse_context_menu.take().is_some() {
 3153            return true;
 3154        }
 3155
 3156        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3157            return true;
 3158        }
 3159
 3160        if self.snippet_stack.pop().is_some() {
 3161            return true;
 3162        }
 3163
 3164        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3165            self.dismiss_diagnostics(cx);
 3166            return true;
 3167        }
 3168
 3169        false
 3170    }
 3171
 3172    fn linked_editing_ranges_for(
 3173        &self,
 3174        selection: Range<text::Anchor>,
 3175        cx: &AppContext,
 3176    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3177        if self.linked_edit_ranges.is_empty() {
 3178            return None;
 3179        }
 3180        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3181            selection.end.buffer_id.and_then(|end_buffer_id| {
 3182                if selection.start.buffer_id != Some(end_buffer_id) {
 3183                    return None;
 3184                }
 3185                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3186                let snapshot = buffer.read(cx).snapshot();
 3187                self.linked_edit_ranges
 3188                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3189                    .map(|ranges| (ranges, snapshot, buffer))
 3190            })?;
 3191        use text::ToOffset as TO;
 3192        // find offset from the start of current range to current cursor position
 3193        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3194
 3195        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3196        let start_difference = start_offset - start_byte_offset;
 3197        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3198        let end_difference = end_offset - start_byte_offset;
 3199        // Current range has associated linked ranges.
 3200        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3201        for range in linked_ranges.iter() {
 3202            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3203            let end_offset = start_offset + end_difference;
 3204            let start_offset = start_offset + start_difference;
 3205            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3206                continue;
 3207            }
 3208            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3209                if s.start.buffer_id != selection.start.buffer_id
 3210                    || s.end.buffer_id != selection.end.buffer_id
 3211                {
 3212                    return false;
 3213                }
 3214                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3215                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3216            }) {
 3217                continue;
 3218            }
 3219            let start = buffer_snapshot.anchor_after(start_offset);
 3220            let end = buffer_snapshot.anchor_after(end_offset);
 3221            linked_edits
 3222                .entry(buffer.clone())
 3223                .or_default()
 3224                .push(start..end);
 3225        }
 3226        Some(linked_edits)
 3227    }
 3228
 3229    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3230        let text: Arc<str> = text.into();
 3231
 3232        if self.read_only(cx) {
 3233            return;
 3234        }
 3235
 3236        let selections = self.selections.all_adjusted(cx);
 3237        let mut bracket_inserted = false;
 3238        let mut edits = Vec::new();
 3239        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3240        let mut new_selections = Vec::with_capacity(selections.len());
 3241        let mut new_autoclose_regions = Vec::new();
 3242        let snapshot = self.buffer.read(cx).read(cx);
 3243
 3244        for (selection, autoclose_region) in
 3245            self.selections_with_autoclose_regions(selections, &snapshot)
 3246        {
 3247            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3248                // Determine if the inserted text matches the opening or closing
 3249                // bracket of any of this language's bracket pairs.
 3250                let mut bracket_pair = None;
 3251                let mut is_bracket_pair_start = false;
 3252                let mut is_bracket_pair_end = false;
 3253                if !text.is_empty() {
 3254                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3255                    //  and they are removing the character that triggered IME popup.
 3256                    for (pair, enabled) in scope.brackets() {
 3257                        if !pair.close && !pair.surround {
 3258                            continue;
 3259                        }
 3260
 3261                        if enabled && pair.start.ends_with(text.as_ref()) {
 3262                            let prefix_len = pair.start.len() - text.len();
 3263                            let preceding_text_matches_prefix = prefix_len == 0
 3264                                || (selection.start.column >= (prefix_len as u32)
 3265                                    && snapshot.contains_str_at(
 3266                                        Point::new(
 3267                                            selection.start.row,
 3268                                            selection.start.column - (prefix_len as u32),
 3269                                        ),
 3270                                        &pair.start[..prefix_len],
 3271                                    ));
 3272                            if preceding_text_matches_prefix {
 3273                                bracket_pair = Some(pair.clone());
 3274                                is_bracket_pair_start = true;
 3275                                break;
 3276                            }
 3277                        }
 3278                        if pair.end.as_str() == text.as_ref() {
 3279                            bracket_pair = Some(pair.clone());
 3280                            is_bracket_pair_end = true;
 3281                            break;
 3282                        }
 3283                    }
 3284                }
 3285
 3286                if let Some(bracket_pair) = bracket_pair {
 3287                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3288                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3289                    let auto_surround =
 3290                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3291                    if selection.is_empty() {
 3292                        if is_bracket_pair_start {
 3293                            // If the inserted text is a suffix of an opening bracket and the
 3294                            // selection is preceded by the rest of the opening bracket, then
 3295                            // insert the closing bracket.
 3296                            let following_text_allows_autoclose = snapshot
 3297                                .chars_at(selection.start)
 3298                                .next()
 3299                                .map_or(true, |c| scope.should_autoclose_before(c));
 3300
 3301                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3302                                && bracket_pair.start.len() == 1
 3303                            {
 3304                                let target = bracket_pair.start.chars().next().unwrap();
 3305                                let current_line_count = snapshot
 3306                                    .reversed_chars_at(selection.start)
 3307                                    .take_while(|&c| c != '\n')
 3308                                    .filter(|&c| c == target)
 3309                                    .count();
 3310                                current_line_count % 2 == 1
 3311                            } else {
 3312                                false
 3313                            };
 3314
 3315                            if autoclose
 3316                                && bracket_pair.close
 3317                                && following_text_allows_autoclose
 3318                                && !is_closing_quote
 3319                            {
 3320                                let anchor = snapshot.anchor_before(selection.end);
 3321                                new_selections.push((selection.map(|_| anchor), text.len()));
 3322                                new_autoclose_regions.push((
 3323                                    anchor,
 3324                                    text.len(),
 3325                                    selection.id,
 3326                                    bracket_pair.clone(),
 3327                                ));
 3328                                edits.push((
 3329                                    selection.range(),
 3330                                    format!("{}{}", text, bracket_pair.end).into(),
 3331                                ));
 3332                                bracket_inserted = true;
 3333                                continue;
 3334                            }
 3335                        }
 3336
 3337                        if let Some(region) = autoclose_region {
 3338                            // If the selection is followed by an auto-inserted closing bracket,
 3339                            // then don't insert that closing bracket again; just move the selection
 3340                            // past the closing bracket.
 3341                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3342                                && text.as_ref() == region.pair.end.as_str();
 3343                            if should_skip {
 3344                                let anchor = snapshot.anchor_after(selection.end);
 3345                                new_selections
 3346                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3347                                continue;
 3348                            }
 3349                        }
 3350
 3351                        let always_treat_brackets_as_autoclosed = snapshot
 3352                            .settings_at(selection.start, cx)
 3353                            .always_treat_brackets_as_autoclosed;
 3354                        if always_treat_brackets_as_autoclosed
 3355                            && is_bracket_pair_end
 3356                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3357                        {
 3358                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3359                            // and the inserted text is a closing bracket and the selection is followed
 3360                            // by the closing bracket then move the selection past the closing bracket.
 3361                            let anchor = snapshot.anchor_after(selection.end);
 3362                            new_selections.push((selection.map(|_| anchor), text.len()));
 3363                            continue;
 3364                        }
 3365                    }
 3366                    // If an opening bracket is 1 character long and is typed while
 3367                    // text is selected, then surround that text with the bracket pair.
 3368                    else if auto_surround
 3369                        && bracket_pair.surround
 3370                        && is_bracket_pair_start
 3371                        && bracket_pair.start.chars().count() == 1
 3372                    {
 3373                        edits.push((selection.start..selection.start, text.clone()));
 3374                        edits.push((
 3375                            selection.end..selection.end,
 3376                            bracket_pair.end.as_str().into(),
 3377                        ));
 3378                        bracket_inserted = true;
 3379                        new_selections.push((
 3380                            Selection {
 3381                                id: selection.id,
 3382                                start: snapshot.anchor_after(selection.start),
 3383                                end: snapshot.anchor_before(selection.end),
 3384                                reversed: selection.reversed,
 3385                                goal: selection.goal,
 3386                            },
 3387                            0,
 3388                        ));
 3389                        continue;
 3390                    }
 3391                }
 3392            }
 3393
 3394            if self.auto_replace_emoji_shortcode
 3395                && selection.is_empty()
 3396                && text.as_ref().ends_with(':')
 3397            {
 3398                if let Some(possible_emoji_short_code) =
 3399                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3400                {
 3401                    if !possible_emoji_short_code.is_empty() {
 3402                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3403                            let emoji_shortcode_start = Point::new(
 3404                                selection.start.row,
 3405                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3406                            );
 3407
 3408                            // Remove shortcode from buffer
 3409                            edits.push((
 3410                                emoji_shortcode_start..selection.start,
 3411                                "".to_string().into(),
 3412                            ));
 3413                            new_selections.push((
 3414                                Selection {
 3415                                    id: selection.id,
 3416                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3417                                    end: snapshot.anchor_before(selection.start),
 3418                                    reversed: selection.reversed,
 3419                                    goal: selection.goal,
 3420                                },
 3421                                0,
 3422                            ));
 3423
 3424                            // Insert emoji
 3425                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3426                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3427                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3428
 3429                            continue;
 3430                        }
 3431                    }
 3432                }
 3433            }
 3434
 3435            // If not handling any auto-close operation, then just replace the selected
 3436            // text with the given input and move the selection to the end of the
 3437            // newly inserted text.
 3438            let anchor = snapshot.anchor_after(selection.end);
 3439            if !self.linked_edit_ranges.is_empty() {
 3440                let start_anchor = snapshot.anchor_before(selection.start);
 3441
 3442                let is_word_char = text.chars().next().map_or(true, |char| {
 3443                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3444                    classifier.is_word(char)
 3445                });
 3446
 3447                if is_word_char {
 3448                    if let Some(ranges) = self
 3449                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3450                    {
 3451                        for (buffer, edits) in ranges {
 3452                            linked_edits
 3453                                .entry(buffer.clone())
 3454                                .or_default()
 3455                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3456                        }
 3457                    }
 3458                }
 3459            }
 3460
 3461            new_selections.push((selection.map(|_| anchor), 0));
 3462            edits.push((selection.start..selection.end, text.clone()));
 3463        }
 3464
 3465        drop(snapshot);
 3466
 3467        self.transact(cx, |this, cx| {
 3468            this.buffer.update(cx, |buffer, cx| {
 3469                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3470            });
 3471            for (buffer, edits) in linked_edits {
 3472                buffer.update(cx, |buffer, cx| {
 3473                    let snapshot = buffer.snapshot();
 3474                    let edits = edits
 3475                        .into_iter()
 3476                        .map(|(range, text)| {
 3477                            use text::ToPoint as TP;
 3478                            let end_point = TP::to_point(&range.end, &snapshot);
 3479                            let start_point = TP::to_point(&range.start, &snapshot);
 3480                            (start_point..end_point, text)
 3481                        })
 3482                        .sorted_by_key(|(range, _)| range.start)
 3483                        .collect::<Vec<_>>();
 3484                    buffer.edit(edits, None, cx);
 3485                })
 3486            }
 3487            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3488            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3489            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3490            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3491                .zip(new_selection_deltas)
 3492                .map(|(selection, delta)| Selection {
 3493                    id: selection.id,
 3494                    start: selection.start + delta,
 3495                    end: selection.end + delta,
 3496                    reversed: selection.reversed,
 3497                    goal: SelectionGoal::None,
 3498                })
 3499                .collect::<Vec<_>>();
 3500
 3501            let mut i = 0;
 3502            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3503                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3504                let start = map.buffer_snapshot.anchor_before(position);
 3505                let end = map.buffer_snapshot.anchor_after(position);
 3506                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3507                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3508                        Ordering::Less => i += 1,
 3509                        Ordering::Greater => break,
 3510                        Ordering::Equal => {
 3511                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3512                                Ordering::Less => i += 1,
 3513                                Ordering::Equal => break,
 3514                                Ordering::Greater => break,
 3515                            }
 3516                        }
 3517                    }
 3518                }
 3519                this.autoclose_regions.insert(
 3520                    i,
 3521                    AutocloseRegion {
 3522                        selection_id,
 3523                        range: start..end,
 3524                        pair,
 3525                    },
 3526                );
 3527            }
 3528
 3529            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3530            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3531                s.select(new_selections)
 3532            });
 3533
 3534            if !bracket_inserted {
 3535                if let Some(on_type_format_task) =
 3536                    this.trigger_on_type_formatting(text.to_string(), cx)
 3537                {
 3538                    on_type_format_task.detach_and_log_err(cx);
 3539                }
 3540            }
 3541
 3542            let editor_settings = EditorSettings::get_global(cx);
 3543            if bracket_inserted
 3544                && (editor_settings.auto_signature_help
 3545                    || editor_settings.show_signature_help_after_edits)
 3546            {
 3547                this.show_signature_help(&ShowSignatureHelp, cx);
 3548            }
 3549
 3550            let trigger_in_words = !had_active_inline_completion;
 3551            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3552            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3553            this.refresh_inline_completion(true, false, cx);
 3554        });
 3555    }
 3556
 3557    fn find_possible_emoji_shortcode_at_position(
 3558        snapshot: &MultiBufferSnapshot,
 3559        position: Point,
 3560    ) -> Option<String> {
 3561        let mut chars = Vec::new();
 3562        let mut found_colon = false;
 3563        for char in snapshot.reversed_chars_at(position).take(100) {
 3564            // Found a possible emoji shortcode in the middle of the buffer
 3565            if found_colon {
 3566                if char.is_whitespace() {
 3567                    chars.reverse();
 3568                    return Some(chars.iter().collect());
 3569                }
 3570                // If the previous character is not a whitespace, we are in the middle of a word
 3571                // and we only want to complete the shortcode if the word is made up of other emojis
 3572                let mut containing_word = String::new();
 3573                for ch in snapshot
 3574                    .reversed_chars_at(position)
 3575                    .skip(chars.len() + 1)
 3576                    .take(100)
 3577                {
 3578                    if ch.is_whitespace() {
 3579                        break;
 3580                    }
 3581                    containing_word.push(ch);
 3582                }
 3583                let containing_word = containing_word.chars().rev().collect::<String>();
 3584                if util::word_consists_of_emojis(containing_word.as_str()) {
 3585                    chars.reverse();
 3586                    return Some(chars.iter().collect());
 3587                }
 3588            }
 3589
 3590            if char.is_whitespace() || !char.is_ascii() {
 3591                return None;
 3592            }
 3593            if char == ':' {
 3594                found_colon = true;
 3595            } else {
 3596                chars.push(char);
 3597            }
 3598        }
 3599        // Found a possible emoji shortcode at the beginning of the buffer
 3600        chars.reverse();
 3601        Some(chars.iter().collect())
 3602    }
 3603
 3604    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3605        self.transact(cx, |this, cx| {
 3606            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3607                let selections = this.selections.all::<usize>(cx);
 3608                let multi_buffer = this.buffer.read(cx);
 3609                let buffer = multi_buffer.snapshot(cx);
 3610                selections
 3611                    .iter()
 3612                    .map(|selection| {
 3613                        let start_point = selection.start.to_point(&buffer);
 3614                        let mut indent =
 3615                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3616                        indent.len = cmp::min(indent.len, start_point.column);
 3617                        let start = selection.start;
 3618                        let end = selection.end;
 3619                        let selection_is_empty = start == end;
 3620                        let language_scope = buffer.language_scope_at(start);
 3621                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3622                            &language_scope
 3623                        {
 3624                            let leading_whitespace_len = buffer
 3625                                .reversed_chars_at(start)
 3626                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3627                                .map(|c| c.len_utf8())
 3628                                .sum::<usize>();
 3629
 3630                            let trailing_whitespace_len = buffer
 3631                                .chars_at(end)
 3632                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3633                                .map(|c| c.len_utf8())
 3634                                .sum::<usize>();
 3635
 3636                            let insert_extra_newline =
 3637                                language.brackets().any(|(pair, enabled)| {
 3638                                    let pair_start = pair.start.trim_end();
 3639                                    let pair_end = pair.end.trim_start();
 3640
 3641                                    enabled
 3642                                        && pair.newline
 3643                                        && buffer.contains_str_at(
 3644                                            end + trailing_whitespace_len,
 3645                                            pair_end,
 3646                                        )
 3647                                        && buffer.contains_str_at(
 3648                                            (start - leading_whitespace_len)
 3649                                                .saturating_sub(pair_start.len()),
 3650                                            pair_start,
 3651                                        )
 3652                                });
 3653
 3654                            // Comment extension on newline is allowed only for cursor selections
 3655                            let comment_delimiter = maybe!({
 3656                                if !selection_is_empty {
 3657                                    return None;
 3658                                }
 3659
 3660                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3661                                    return None;
 3662                                }
 3663
 3664                                let delimiters = language.line_comment_prefixes();
 3665                                let max_len_of_delimiter =
 3666                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3667                                let (snapshot, range) =
 3668                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3669
 3670                                let mut index_of_first_non_whitespace = 0;
 3671                                let comment_candidate = snapshot
 3672                                    .chars_for_range(range)
 3673                                    .skip_while(|c| {
 3674                                        let should_skip = c.is_whitespace();
 3675                                        if should_skip {
 3676                                            index_of_first_non_whitespace += 1;
 3677                                        }
 3678                                        should_skip
 3679                                    })
 3680                                    .take(max_len_of_delimiter)
 3681                                    .collect::<String>();
 3682                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3683                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3684                                })?;
 3685                                let cursor_is_placed_after_comment_marker =
 3686                                    index_of_first_non_whitespace + comment_prefix.len()
 3687                                        <= start_point.column as usize;
 3688                                if cursor_is_placed_after_comment_marker {
 3689                                    Some(comment_prefix.clone())
 3690                                } else {
 3691                                    None
 3692                                }
 3693                            });
 3694                            (comment_delimiter, insert_extra_newline)
 3695                        } else {
 3696                            (None, false)
 3697                        };
 3698
 3699                        let capacity_for_delimiter = comment_delimiter
 3700                            .as_deref()
 3701                            .map(str::len)
 3702                            .unwrap_or_default();
 3703                        let mut new_text =
 3704                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3705                        new_text.push('\n');
 3706                        new_text.extend(indent.chars());
 3707                        if let Some(delimiter) = &comment_delimiter {
 3708                            new_text.push_str(delimiter);
 3709                        }
 3710                        if insert_extra_newline {
 3711                            new_text = new_text.repeat(2);
 3712                        }
 3713
 3714                        let anchor = buffer.anchor_after(end);
 3715                        let new_selection = selection.map(|_| anchor);
 3716                        (
 3717                            (start..end, new_text),
 3718                            (insert_extra_newline, new_selection),
 3719                        )
 3720                    })
 3721                    .unzip()
 3722            };
 3723
 3724            this.edit_with_autoindent(edits, cx);
 3725            let buffer = this.buffer.read(cx).snapshot(cx);
 3726            let new_selections = selection_fixup_info
 3727                .into_iter()
 3728                .map(|(extra_newline_inserted, new_selection)| {
 3729                    let mut cursor = new_selection.end.to_point(&buffer);
 3730                    if extra_newline_inserted {
 3731                        cursor.row -= 1;
 3732                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3733                    }
 3734                    new_selection.map(|_| cursor)
 3735                })
 3736                .collect();
 3737
 3738            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3739            this.refresh_inline_completion(true, false, cx);
 3740        });
 3741    }
 3742
 3743    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3744        let buffer = self.buffer.read(cx);
 3745        let snapshot = buffer.snapshot(cx);
 3746
 3747        let mut edits = Vec::new();
 3748        let mut rows = Vec::new();
 3749
 3750        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3751            let cursor = selection.head();
 3752            let row = cursor.row;
 3753
 3754            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3755
 3756            let newline = "\n".to_string();
 3757            edits.push((start_of_line..start_of_line, newline));
 3758
 3759            rows.push(row + rows_inserted as u32);
 3760        }
 3761
 3762        self.transact(cx, |editor, cx| {
 3763            editor.edit(edits, cx);
 3764
 3765            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3766                let mut index = 0;
 3767                s.move_cursors_with(|map, _, _| {
 3768                    let row = rows[index];
 3769                    index += 1;
 3770
 3771                    let point = Point::new(row, 0);
 3772                    let boundary = map.next_line_boundary(point).1;
 3773                    let clipped = map.clip_point(boundary, Bias::Left);
 3774
 3775                    (clipped, SelectionGoal::None)
 3776                });
 3777            });
 3778
 3779            let mut indent_edits = Vec::new();
 3780            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3781            for row in rows {
 3782                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3783                for (row, indent) in indents {
 3784                    if indent.len == 0 {
 3785                        continue;
 3786                    }
 3787
 3788                    let text = match indent.kind {
 3789                        IndentKind::Space => " ".repeat(indent.len as usize),
 3790                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3791                    };
 3792                    let point = Point::new(row.0, 0);
 3793                    indent_edits.push((point..point, text));
 3794                }
 3795            }
 3796            editor.edit(indent_edits, cx);
 3797        });
 3798    }
 3799
 3800    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3801        let buffer = self.buffer.read(cx);
 3802        let snapshot = buffer.snapshot(cx);
 3803
 3804        let mut edits = Vec::new();
 3805        let mut rows = Vec::new();
 3806        let mut rows_inserted = 0;
 3807
 3808        for selection in self.selections.all_adjusted(cx) {
 3809            let cursor = selection.head();
 3810            let row = cursor.row;
 3811
 3812            let point = Point::new(row + 1, 0);
 3813            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3814
 3815            let newline = "\n".to_string();
 3816            edits.push((start_of_line..start_of_line, newline));
 3817
 3818            rows_inserted += 1;
 3819            rows.push(row + rows_inserted);
 3820        }
 3821
 3822        self.transact(cx, |editor, cx| {
 3823            editor.edit(edits, cx);
 3824
 3825            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3826                let mut index = 0;
 3827                s.move_cursors_with(|map, _, _| {
 3828                    let row = rows[index];
 3829                    index += 1;
 3830
 3831                    let point = Point::new(row, 0);
 3832                    let boundary = map.next_line_boundary(point).1;
 3833                    let clipped = map.clip_point(boundary, Bias::Left);
 3834
 3835                    (clipped, SelectionGoal::None)
 3836                });
 3837            });
 3838
 3839            let mut indent_edits = Vec::new();
 3840            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3841            for row in rows {
 3842                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3843                for (row, indent) in indents {
 3844                    if indent.len == 0 {
 3845                        continue;
 3846                    }
 3847
 3848                    let text = match indent.kind {
 3849                        IndentKind::Space => " ".repeat(indent.len as usize),
 3850                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3851                    };
 3852                    let point = Point::new(row.0, 0);
 3853                    indent_edits.push((point..point, text));
 3854                }
 3855            }
 3856            editor.edit(indent_edits, cx);
 3857        });
 3858    }
 3859
 3860    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3861        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3862            original_indent_columns: Vec::new(),
 3863        });
 3864        self.insert_with_autoindent_mode(text, autoindent, cx);
 3865    }
 3866
 3867    fn insert_with_autoindent_mode(
 3868        &mut self,
 3869        text: &str,
 3870        autoindent_mode: Option<AutoindentMode>,
 3871        cx: &mut ViewContext<Self>,
 3872    ) {
 3873        if self.read_only(cx) {
 3874            return;
 3875        }
 3876
 3877        let text: Arc<str> = text.into();
 3878        self.transact(cx, |this, cx| {
 3879            let old_selections = this.selections.all_adjusted(cx);
 3880            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3881                let anchors = {
 3882                    let snapshot = buffer.read(cx);
 3883                    old_selections
 3884                        .iter()
 3885                        .map(|s| {
 3886                            let anchor = snapshot.anchor_after(s.head());
 3887                            s.map(|_| anchor)
 3888                        })
 3889                        .collect::<Vec<_>>()
 3890                };
 3891                buffer.edit(
 3892                    old_selections
 3893                        .iter()
 3894                        .map(|s| (s.start..s.end, text.clone())),
 3895                    autoindent_mode,
 3896                    cx,
 3897                );
 3898                anchors
 3899            });
 3900
 3901            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3902                s.select_anchors(selection_anchors);
 3903            })
 3904        });
 3905    }
 3906
 3907    fn trigger_completion_on_input(
 3908        &mut self,
 3909        text: &str,
 3910        trigger_in_words: bool,
 3911        cx: &mut ViewContext<Self>,
 3912    ) {
 3913        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3914            self.show_completions(
 3915                &ShowCompletions {
 3916                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3917                },
 3918                cx,
 3919            );
 3920        } else {
 3921            self.hide_context_menu(cx);
 3922        }
 3923    }
 3924
 3925    fn is_completion_trigger(
 3926        &self,
 3927        text: &str,
 3928        trigger_in_words: bool,
 3929        cx: &mut ViewContext<Self>,
 3930    ) -> bool {
 3931        let position = self.selections.newest_anchor().head();
 3932        let multibuffer = self.buffer.read(cx);
 3933        let Some(buffer) = position
 3934            .buffer_id
 3935            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3936        else {
 3937            return false;
 3938        };
 3939
 3940        if let Some(completion_provider) = &self.completion_provider {
 3941            completion_provider.is_completion_trigger(
 3942                &buffer,
 3943                position.text_anchor,
 3944                text,
 3945                trigger_in_words,
 3946                cx,
 3947            )
 3948        } else {
 3949            false
 3950        }
 3951    }
 3952
 3953    /// If any empty selections is touching the start of its innermost containing autoclose
 3954    /// region, expand it to select the brackets.
 3955    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3956        let selections = self.selections.all::<usize>(cx);
 3957        let buffer = self.buffer.read(cx).read(cx);
 3958        let new_selections = self
 3959            .selections_with_autoclose_regions(selections, &buffer)
 3960            .map(|(mut selection, region)| {
 3961                if !selection.is_empty() {
 3962                    return selection;
 3963                }
 3964
 3965                if let Some(region) = region {
 3966                    let mut range = region.range.to_offset(&buffer);
 3967                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3968                        range.start -= region.pair.start.len();
 3969                        if buffer.contains_str_at(range.start, &region.pair.start)
 3970                            && buffer.contains_str_at(range.end, &region.pair.end)
 3971                        {
 3972                            range.end += region.pair.end.len();
 3973                            selection.start = range.start;
 3974                            selection.end = range.end;
 3975
 3976                            return selection;
 3977                        }
 3978                    }
 3979                }
 3980
 3981                let always_treat_brackets_as_autoclosed = buffer
 3982                    .settings_at(selection.start, cx)
 3983                    .always_treat_brackets_as_autoclosed;
 3984
 3985                if !always_treat_brackets_as_autoclosed {
 3986                    return selection;
 3987                }
 3988
 3989                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3990                    for (pair, enabled) in scope.brackets() {
 3991                        if !enabled || !pair.close {
 3992                            continue;
 3993                        }
 3994
 3995                        if buffer.contains_str_at(selection.start, &pair.end) {
 3996                            let pair_start_len = pair.start.len();
 3997                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3998                            {
 3999                                selection.start -= pair_start_len;
 4000                                selection.end += pair.end.len();
 4001
 4002                                return selection;
 4003                            }
 4004                        }
 4005                    }
 4006                }
 4007
 4008                selection
 4009            })
 4010            .collect();
 4011
 4012        drop(buffer);
 4013        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4014    }
 4015
 4016    /// Iterate the given selections, and for each one, find the smallest surrounding
 4017    /// autoclose region. This uses the ordering of the selections and the autoclose
 4018    /// regions to avoid repeated comparisons.
 4019    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4020        &'a self,
 4021        selections: impl IntoIterator<Item = Selection<D>>,
 4022        buffer: &'a MultiBufferSnapshot,
 4023    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4024        let mut i = 0;
 4025        let mut regions = self.autoclose_regions.as_slice();
 4026        selections.into_iter().map(move |selection| {
 4027            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4028
 4029            let mut enclosing = None;
 4030            while let Some(pair_state) = regions.get(i) {
 4031                if pair_state.range.end.to_offset(buffer) < range.start {
 4032                    regions = &regions[i + 1..];
 4033                    i = 0;
 4034                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4035                    break;
 4036                } else {
 4037                    if pair_state.selection_id == selection.id {
 4038                        enclosing = Some(pair_state);
 4039                    }
 4040                    i += 1;
 4041                }
 4042            }
 4043
 4044            (selection, enclosing)
 4045        })
 4046    }
 4047
 4048    /// Remove any autoclose regions that no longer contain their selection.
 4049    fn invalidate_autoclose_regions(
 4050        &mut self,
 4051        mut selections: &[Selection<Anchor>],
 4052        buffer: &MultiBufferSnapshot,
 4053    ) {
 4054        self.autoclose_regions.retain(|state| {
 4055            let mut i = 0;
 4056            while let Some(selection) = selections.get(i) {
 4057                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4058                    selections = &selections[1..];
 4059                    continue;
 4060                }
 4061                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4062                    break;
 4063                }
 4064                if selection.id == state.selection_id {
 4065                    return true;
 4066                } else {
 4067                    i += 1;
 4068                }
 4069            }
 4070            false
 4071        });
 4072    }
 4073
 4074    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4075        let offset = position.to_offset(buffer);
 4076        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4077        if offset > word_range.start && kind == Some(CharKind::Word) {
 4078            Some(
 4079                buffer
 4080                    .text_for_range(word_range.start..offset)
 4081                    .collect::<String>(),
 4082            )
 4083        } else {
 4084            None
 4085        }
 4086    }
 4087
 4088    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4089        self.refresh_inlay_hints(
 4090            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4091            cx,
 4092        );
 4093    }
 4094
 4095    pub fn inlay_hints_enabled(&self) -> bool {
 4096        self.inlay_hint_cache.enabled
 4097    }
 4098
 4099    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4100        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4101            return;
 4102        }
 4103
 4104        let reason_description = reason.description();
 4105        let ignore_debounce = matches!(
 4106            reason,
 4107            InlayHintRefreshReason::SettingsChange(_)
 4108                | InlayHintRefreshReason::Toggle(_)
 4109                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4110        );
 4111        let (invalidate_cache, required_languages) = match reason {
 4112            InlayHintRefreshReason::Toggle(enabled) => {
 4113                self.inlay_hint_cache.enabled = enabled;
 4114                if enabled {
 4115                    (InvalidationStrategy::RefreshRequested, None)
 4116                } else {
 4117                    self.inlay_hint_cache.clear();
 4118                    self.splice_inlays(
 4119                        self.visible_inlay_hints(cx)
 4120                            .iter()
 4121                            .map(|inlay| inlay.id)
 4122                            .collect(),
 4123                        Vec::new(),
 4124                        cx,
 4125                    );
 4126                    return;
 4127                }
 4128            }
 4129            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4130                match self.inlay_hint_cache.update_settings(
 4131                    &self.buffer,
 4132                    new_settings,
 4133                    self.visible_inlay_hints(cx),
 4134                    cx,
 4135                ) {
 4136                    ControlFlow::Break(Some(InlaySplice {
 4137                        to_remove,
 4138                        to_insert,
 4139                    })) => {
 4140                        self.splice_inlays(to_remove, to_insert, cx);
 4141                        return;
 4142                    }
 4143                    ControlFlow::Break(None) => return,
 4144                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4145                }
 4146            }
 4147            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4148                if let Some(InlaySplice {
 4149                    to_remove,
 4150                    to_insert,
 4151                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4152                {
 4153                    self.splice_inlays(to_remove, to_insert, cx);
 4154                }
 4155                return;
 4156            }
 4157            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4158            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4159                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4160            }
 4161            InlayHintRefreshReason::RefreshRequested => {
 4162                (InvalidationStrategy::RefreshRequested, None)
 4163            }
 4164        };
 4165
 4166        if let Some(InlaySplice {
 4167            to_remove,
 4168            to_insert,
 4169        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4170            reason_description,
 4171            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4172            invalidate_cache,
 4173            ignore_debounce,
 4174            cx,
 4175        ) {
 4176            self.splice_inlays(to_remove, to_insert, cx);
 4177        }
 4178    }
 4179
 4180    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4181        self.display_map
 4182            .read(cx)
 4183            .current_inlays()
 4184            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4185            .cloned()
 4186            .collect()
 4187    }
 4188
 4189    pub fn excerpts_for_inlay_hints_query(
 4190        &self,
 4191        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4192        cx: &mut ViewContext<Editor>,
 4193    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4194        let Some(project) = self.project.as_ref() else {
 4195            return HashMap::default();
 4196        };
 4197        let project = project.read(cx);
 4198        let multi_buffer = self.buffer().read(cx);
 4199        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4200        let multi_buffer_visible_start = self
 4201            .scroll_manager
 4202            .anchor()
 4203            .anchor
 4204            .to_point(&multi_buffer_snapshot);
 4205        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4206            multi_buffer_visible_start
 4207                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4208            Bias::Left,
 4209        );
 4210        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4211        multi_buffer
 4212            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4213            .into_iter()
 4214            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4215            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4216                let buffer = buffer_handle.read(cx);
 4217                let buffer_file = project::File::from_dyn(buffer.file())?;
 4218                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4219                let worktree_entry = buffer_worktree
 4220                    .read(cx)
 4221                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4222                if worktree_entry.is_ignored {
 4223                    return None;
 4224                }
 4225
 4226                let language = buffer.language()?;
 4227                if let Some(restrict_to_languages) = restrict_to_languages {
 4228                    if !restrict_to_languages.contains(language) {
 4229                        return None;
 4230                    }
 4231                }
 4232                Some((
 4233                    excerpt_id,
 4234                    (
 4235                        buffer_handle,
 4236                        buffer.version().clone(),
 4237                        excerpt_visible_range,
 4238                    ),
 4239                ))
 4240            })
 4241            .collect()
 4242    }
 4243
 4244    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4245        TextLayoutDetails {
 4246            text_system: cx.text_system().clone(),
 4247            editor_style: self.style.clone().unwrap(),
 4248            rem_size: cx.rem_size(),
 4249            scroll_anchor: self.scroll_manager.anchor(),
 4250            visible_rows: self.visible_line_count(),
 4251            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4252        }
 4253    }
 4254
 4255    fn splice_inlays(
 4256        &self,
 4257        to_remove: Vec<InlayId>,
 4258        to_insert: Vec<Inlay>,
 4259        cx: &mut ViewContext<Self>,
 4260    ) {
 4261        self.display_map.update(cx, |display_map, cx| {
 4262            display_map.splice_inlays(to_remove, to_insert, cx);
 4263        });
 4264        cx.notify();
 4265    }
 4266
 4267    fn trigger_on_type_formatting(
 4268        &self,
 4269        input: String,
 4270        cx: &mut ViewContext<Self>,
 4271    ) -> Option<Task<Result<()>>> {
 4272        if input.len() != 1 {
 4273            return None;
 4274        }
 4275
 4276        let project = self.project.as_ref()?;
 4277        let position = self.selections.newest_anchor().head();
 4278        let (buffer, buffer_position) = self
 4279            .buffer
 4280            .read(cx)
 4281            .text_anchor_for_position(position, cx)?;
 4282
 4283        let settings = language_settings::language_settings(
 4284            buffer
 4285                .read(cx)
 4286                .language_at(buffer_position)
 4287                .map(|l| l.name()),
 4288            buffer.read(cx).file(),
 4289            cx,
 4290        );
 4291        if !settings.use_on_type_format {
 4292            return None;
 4293        }
 4294
 4295        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4296        // hence we do LSP request & edit on host side only — add formats to host's history.
 4297        let push_to_lsp_host_history = true;
 4298        // If this is not the host, append its history with new edits.
 4299        let push_to_client_history = project.read(cx).is_via_collab();
 4300
 4301        let on_type_formatting = project.update(cx, |project, cx| {
 4302            project.on_type_format(
 4303                buffer.clone(),
 4304                buffer_position,
 4305                input,
 4306                push_to_lsp_host_history,
 4307                cx,
 4308            )
 4309        });
 4310        Some(cx.spawn(|editor, mut cx| async move {
 4311            if let Some(transaction) = on_type_formatting.await? {
 4312                if push_to_client_history {
 4313                    buffer
 4314                        .update(&mut cx, |buffer, _| {
 4315                            buffer.push_transaction(transaction, Instant::now());
 4316                        })
 4317                        .ok();
 4318                }
 4319                editor.update(&mut cx, |editor, cx| {
 4320                    editor.refresh_document_highlights(cx);
 4321                })?;
 4322            }
 4323            Ok(())
 4324        }))
 4325    }
 4326
 4327    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4328        if self.pending_rename.is_some() {
 4329            return;
 4330        }
 4331
 4332        let Some(provider) = self.completion_provider.as_ref() else {
 4333            return;
 4334        };
 4335
 4336        let position = self.selections.newest_anchor().head();
 4337        let (buffer, buffer_position) =
 4338            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4339                output
 4340            } else {
 4341                return;
 4342            };
 4343
 4344        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4345        let is_followup_invoke = {
 4346            let context_menu_state = self.context_menu.read();
 4347            matches!(
 4348                context_menu_state.deref(),
 4349                Some(ContextMenu::Completions(_))
 4350            )
 4351        };
 4352        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4353            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4354            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4355                CompletionTriggerKind::TRIGGER_CHARACTER
 4356            }
 4357
 4358            _ => CompletionTriggerKind::INVOKED,
 4359        };
 4360        let completion_context = CompletionContext {
 4361            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4362                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4363                    Some(String::from(trigger))
 4364                } else {
 4365                    None
 4366                }
 4367            }),
 4368            trigger_kind,
 4369        };
 4370        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4371        let sort_completions = provider.sort_completions();
 4372
 4373        let id = post_inc(&mut self.next_completion_id);
 4374        let task = cx.spawn(|this, mut cx| {
 4375            async move {
 4376                this.update(&mut cx, |this, _| {
 4377                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4378                })?;
 4379                let completions = completions.await.log_err();
 4380                let menu = if let Some(completions) = completions {
 4381                    let mut menu = CompletionsMenu {
 4382                        id,
 4383                        sort_completions,
 4384                        initial_position: position,
 4385                        match_candidates: completions
 4386                            .iter()
 4387                            .enumerate()
 4388                            .map(|(id, completion)| {
 4389                                StringMatchCandidate::new(
 4390                                    id,
 4391                                    completion.label.text[completion.label.filter_range.clone()]
 4392                                        .into(),
 4393                                )
 4394                            })
 4395                            .collect(),
 4396                        buffer: buffer.clone(),
 4397                        completions: Arc::new(RwLock::new(completions.into())),
 4398                        matches: Vec::new().into(),
 4399                        selected_item: 0,
 4400                        scroll_handle: UniformListScrollHandle::new(),
 4401                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4402                            DebouncedDelay::new(),
 4403                        )),
 4404                    };
 4405                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4406                        .await;
 4407
 4408                    if menu.matches.is_empty() {
 4409                        None
 4410                    } else {
 4411                        this.update(&mut cx, |editor, cx| {
 4412                            let completions = menu.completions.clone();
 4413                            let matches = menu.matches.clone();
 4414
 4415                            let delay_ms = EditorSettings::get_global(cx)
 4416                                .completion_documentation_secondary_query_debounce;
 4417                            let delay = Duration::from_millis(delay_ms);
 4418                            editor
 4419                                .completion_documentation_pre_resolve_debounce
 4420                                .fire_new(delay, cx, |editor, cx| {
 4421                                    CompletionsMenu::pre_resolve_completion_documentation(
 4422                                        buffer,
 4423                                        completions,
 4424                                        matches,
 4425                                        editor,
 4426                                        cx,
 4427                                    )
 4428                                });
 4429                        })
 4430                        .ok();
 4431                        Some(menu)
 4432                    }
 4433                } else {
 4434                    None
 4435                };
 4436
 4437                this.update(&mut cx, |this, cx| {
 4438                    let mut context_menu = this.context_menu.write();
 4439                    match context_menu.as_ref() {
 4440                        None => {}
 4441
 4442                        Some(ContextMenu::Completions(prev_menu)) => {
 4443                            if prev_menu.id > id {
 4444                                return;
 4445                            }
 4446                        }
 4447
 4448                        _ => return,
 4449                    }
 4450
 4451                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4452                        let menu = menu.unwrap();
 4453                        *context_menu = Some(ContextMenu::Completions(menu));
 4454                        drop(context_menu);
 4455                        this.discard_inline_completion(false, cx);
 4456                        cx.notify();
 4457                    } else if this.completion_tasks.len() <= 1 {
 4458                        // If there are no more completion tasks and the last menu was
 4459                        // empty, we should hide it. If it was already hidden, we should
 4460                        // also show the copilot completion when available.
 4461                        drop(context_menu);
 4462                        if this.hide_context_menu(cx).is_none() {
 4463                            this.update_visible_inline_completion(cx);
 4464                        }
 4465                    }
 4466                })?;
 4467
 4468                Ok::<_, anyhow::Error>(())
 4469            }
 4470            .log_err()
 4471        });
 4472
 4473        self.completion_tasks.push((id, task));
 4474    }
 4475
 4476    pub fn confirm_completion(
 4477        &mut self,
 4478        action: &ConfirmCompletion,
 4479        cx: &mut ViewContext<Self>,
 4480    ) -> Option<Task<Result<()>>> {
 4481        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4482    }
 4483
 4484    pub fn compose_completion(
 4485        &mut self,
 4486        action: &ComposeCompletion,
 4487        cx: &mut ViewContext<Self>,
 4488    ) -> Option<Task<Result<()>>> {
 4489        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4490    }
 4491
 4492    fn do_completion(
 4493        &mut self,
 4494        item_ix: Option<usize>,
 4495        intent: CompletionIntent,
 4496        cx: &mut ViewContext<Editor>,
 4497    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4498        use language::ToOffset as _;
 4499
 4500        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4501            menu
 4502        } else {
 4503            return None;
 4504        };
 4505
 4506        let mat = completions_menu
 4507            .matches
 4508            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4509        let buffer_handle = completions_menu.buffer;
 4510        let completions = completions_menu.completions.read();
 4511        let completion = completions.get(mat.candidate_id)?;
 4512        cx.stop_propagation();
 4513
 4514        let snippet;
 4515        let text;
 4516
 4517        if completion.is_snippet() {
 4518            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4519            text = snippet.as_ref().unwrap().text.clone();
 4520        } else {
 4521            snippet = None;
 4522            text = completion.new_text.clone();
 4523        };
 4524        let selections = self.selections.all::<usize>(cx);
 4525        let buffer = buffer_handle.read(cx);
 4526        let old_range = completion.old_range.to_offset(buffer);
 4527        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4528
 4529        let newest_selection = self.selections.newest_anchor();
 4530        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4531            return None;
 4532        }
 4533
 4534        let lookbehind = newest_selection
 4535            .start
 4536            .text_anchor
 4537            .to_offset(buffer)
 4538            .saturating_sub(old_range.start);
 4539        let lookahead = old_range
 4540            .end
 4541            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4542        let mut common_prefix_len = old_text
 4543            .bytes()
 4544            .zip(text.bytes())
 4545            .take_while(|(a, b)| a == b)
 4546            .count();
 4547
 4548        let snapshot = self.buffer.read(cx).snapshot(cx);
 4549        let mut range_to_replace: Option<Range<isize>> = None;
 4550        let mut ranges = Vec::new();
 4551        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4552        for selection in &selections {
 4553            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4554                let start = selection.start.saturating_sub(lookbehind);
 4555                let end = selection.end + lookahead;
 4556                if selection.id == newest_selection.id {
 4557                    range_to_replace = Some(
 4558                        ((start + common_prefix_len) as isize - selection.start as isize)
 4559                            ..(end as isize - selection.start as isize),
 4560                    );
 4561                }
 4562                ranges.push(start + common_prefix_len..end);
 4563            } else {
 4564                common_prefix_len = 0;
 4565                ranges.clear();
 4566                ranges.extend(selections.iter().map(|s| {
 4567                    if s.id == newest_selection.id {
 4568                        range_to_replace = Some(
 4569                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4570                                - selection.start as isize
 4571                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4572                                    - selection.start as isize,
 4573                        );
 4574                        old_range.clone()
 4575                    } else {
 4576                        s.start..s.end
 4577                    }
 4578                }));
 4579                break;
 4580            }
 4581            if !self.linked_edit_ranges.is_empty() {
 4582                let start_anchor = snapshot.anchor_before(selection.head());
 4583                let end_anchor = snapshot.anchor_after(selection.tail());
 4584                if let Some(ranges) = self
 4585                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4586                {
 4587                    for (buffer, edits) in ranges {
 4588                        linked_edits.entry(buffer.clone()).or_default().extend(
 4589                            edits
 4590                                .into_iter()
 4591                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4592                        );
 4593                    }
 4594                }
 4595            }
 4596        }
 4597        let text = &text[common_prefix_len..];
 4598
 4599        cx.emit(EditorEvent::InputHandled {
 4600            utf16_range_to_replace: range_to_replace,
 4601            text: text.into(),
 4602        });
 4603
 4604        self.transact(cx, |this, cx| {
 4605            if let Some(mut snippet) = snippet {
 4606                snippet.text = text.to_string();
 4607                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4608                    tabstop.start -= common_prefix_len as isize;
 4609                    tabstop.end -= common_prefix_len as isize;
 4610                }
 4611
 4612                this.insert_snippet(&ranges, snippet, cx).log_err();
 4613            } else {
 4614                this.buffer.update(cx, |buffer, cx| {
 4615                    buffer.edit(
 4616                        ranges.iter().map(|range| (range.clone(), text)),
 4617                        this.autoindent_mode.clone(),
 4618                        cx,
 4619                    );
 4620                });
 4621            }
 4622            for (buffer, edits) in linked_edits {
 4623                buffer.update(cx, |buffer, cx| {
 4624                    let snapshot = buffer.snapshot();
 4625                    let edits = edits
 4626                        .into_iter()
 4627                        .map(|(range, text)| {
 4628                            use text::ToPoint as TP;
 4629                            let end_point = TP::to_point(&range.end, &snapshot);
 4630                            let start_point = TP::to_point(&range.start, &snapshot);
 4631                            (start_point..end_point, text)
 4632                        })
 4633                        .sorted_by_key(|(range, _)| range.start)
 4634                        .collect::<Vec<_>>();
 4635                    buffer.edit(edits, None, cx);
 4636                })
 4637            }
 4638
 4639            this.refresh_inline_completion(true, false, cx);
 4640        });
 4641
 4642        let show_new_completions_on_confirm = completion
 4643            .confirm
 4644            .as_ref()
 4645            .map_or(false, |confirm| confirm(intent, cx));
 4646        if show_new_completions_on_confirm {
 4647            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4648        }
 4649
 4650        let provider = self.completion_provider.as_ref()?;
 4651        let apply_edits = provider.apply_additional_edits_for_completion(
 4652            buffer_handle,
 4653            completion.clone(),
 4654            true,
 4655            cx,
 4656        );
 4657
 4658        let editor_settings = EditorSettings::get_global(cx);
 4659        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4660            // After the code completion is finished, users often want to know what signatures are needed.
 4661            // so we should automatically call signature_help
 4662            self.show_signature_help(&ShowSignatureHelp, cx);
 4663        }
 4664
 4665        Some(cx.foreground_executor().spawn(async move {
 4666            apply_edits.await?;
 4667            Ok(())
 4668        }))
 4669    }
 4670
 4671    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4672        let mut context_menu = self.context_menu.write();
 4673        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4674            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4675                // Toggle if we're selecting the same one
 4676                *context_menu = None;
 4677                cx.notify();
 4678                return;
 4679            } else {
 4680                // Otherwise, clear it and start a new one
 4681                *context_menu = None;
 4682                cx.notify();
 4683            }
 4684        }
 4685        drop(context_menu);
 4686        let snapshot = self.snapshot(cx);
 4687        let deployed_from_indicator = action.deployed_from_indicator;
 4688        let mut task = self.code_actions_task.take();
 4689        let action = action.clone();
 4690        cx.spawn(|editor, mut cx| async move {
 4691            while let Some(prev_task) = task {
 4692                prev_task.await.log_err();
 4693                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4694            }
 4695
 4696            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4697                if editor.focus_handle.is_focused(cx) {
 4698                    let multibuffer_point = action
 4699                        .deployed_from_indicator
 4700                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4701                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4702                    let (buffer, buffer_row) = snapshot
 4703                        .buffer_snapshot
 4704                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4705                        .and_then(|(buffer_snapshot, range)| {
 4706                            editor
 4707                                .buffer
 4708                                .read(cx)
 4709                                .buffer(buffer_snapshot.remote_id())
 4710                                .map(|buffer| (buffer, range.start.row))
 4711                        })?;
 4712                    let (_, code_actions) = editor
 4713                        .available_code_actions
 4714                        .clone()
 4715                        .and_then(|(location, code_actions)| {
 4716                            let snapshot = location.buffer.read(cx).snapshot();
 4717                            let point_range = location.range.to_point(&snapshot);
 4718                            let point_range = point_range.start.row..=point_range.end.row;
 4719                            if point_range.contains(&buffer_row) {
 4720                                Some((location, code_actions))
 4721                            } else {
 4722                                None
 4723                            }
 4724                        })
 4725                        .unzip();
 4726                    let buffer_id = buffer.read(cx).remote_id();
 4727                    let tasks = editor
 4728                        .tasks
 4729                        .get(&(buffer_id, buffer_row))
 4730                        .map(|t| Arc::new(t.to_owned()));
 4731                    if tasks.is_none() && code_actions.is_none() {
 4732                        return None;
 4733                    }
 4734
 4735                    editor.completion_tasks.clear();
 4736                    editor.discard_inline_completion(false, cx);
 4737                    let task_context =
 4738                        tasks
 4739                            .as_ref()
 4740                            .zip(editor.project.clone())
 4741                            .map(|(tasks, project)| {
 4742                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4743                            });
 4744
 4745                    Some(cx.spawn(|editor, mut cx| async move {
 4746                        let task_context = match task_context {
 4747                            Some(task_context) => task_context.await,
 4748                            None => None,
 4749                        };
 4750                        let resolved_tasks =
 4751                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4752                                Arc::new(ResolvedTasks {
 4753                                    templates: tasks.resolve(&task_context).collect(),
 4754                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4755                                        multibuffer_point.row,
 4756                                        tasks.column,
 4757                                    )),
 4758                                })
 4759                            });
 4760                        let spawn_straight_away = resolved_tasks
 4761                            .as_ref()
 4762                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4763                            && code_actions
 4764                                .as_ref()
 4765                                .map_or(true, |actions| actions.is_empty());
 4766                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4767                            *editor.context_menu.write() =
 4768                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4769                                    buffer,
 4770                                    actions: CodeActionContents {
 4771                                        tasks: resolved_tasks,
 4772                                        actions: code_actions,
 4773                                    },
 4774                                    selected_item: Default::default(),
 4775                                    scroll_handle: UniformListScrollHandle::default(),
 4776                                    deployed_from_indicator,
 4777                                }));
 4778                            if spawn_straight_away {
 4779                                if let Some(task) = editor.confirm_code_action(
 4780                                    &ConfirmCodeAction { item_ix: Some(0) },
 4781                                    cx,
 4782                                ) {
 4783                                    cx.notify();
 4784                                    return task;
 4785                                }
 4786                            }
 4787                            cx.notify();
 4788                            Task::ready(Ok(()))
 4789                        }) {
 4790                            task.await
 4791                        } else {
 4792                            Ok(())
 4793                        }
 4794                    }))
 4795                } else {
 4796                    Some(Task::ready(Ok(())))
 4797                }
 4798            })?;
 4799            if let Some(task) = spawned_test_task {
 4800                task.await?;
 4801            }
 4802
 4803            Ok::<_, anyhow::Error>(())
 4804        })
 4805        .detach_and_log_err(cx);
 4806    }
 4807
 4808    pub fn confirm_code_action(
 4809        &mut self,
 4810        action: &ConfirmCodeAction,
 4811        cx: &mut ViewContext<Self>,
 4812    ) -> Option<Task<Result<()>>> {
 4813        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4814            menu
 4815        } else {
 4816            return None;
 4817        };
 4818        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4819        let action = actions_menu.actions.get(action_ix)?;
 4820        let title = action.label();
 4821        let buffer = actions_menu.buffer;
 4822        let workspace = self.workspace()?;
 4823
 4824        match action {
 4825            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4826                workspace.update(cx, |workspace, cx| {
 4827                    workspace::tasks::schedule_resolved_task(
 4828                        workspace,
 4829                        task_source_kind,
 4830                        resolved_task,
 4831                        false,
 4832                        cx,
 4833                    );
 4834
 4835                    Some(Task::ready(Ok(())))
 4836                })
 4837            }
 4838            CodeActionsItem::CodeAction {
 4839                excerpt_id,
 4840                action,
 4841                provider,
 4842            } => {
 4843                let apply_code_action =
 4844                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4845                let workspace = workspace.downgrade();
 4846                Some(cx.spawn(|editor, cx| async move {
 4847                    let project_transaction = apply_code_action.await?;
 4848                    Self::open_project_transaction(
 4849                        &editor,
 4850                        workspace,
 4851                        project_transaction,
 4852                        title,
 4853                        cx,
 4854                    )
 4855                    .await
 4856                }))
 4857            }
 4858        }
 4859    }
 4860
 4861    pub async fn open_project_transaction(
 4862        this: &WeakView<Editor>,
 4863        workspace: WeakView<Workspace>,
 4864        transaction: ProjectTransaction,
 4865        title: String,
 4866        mut cx: AsyncWindowContext,
 4867    ) -> Result<()> {
 4868        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4869        cx.update(|cx| {
 4870            entries.sort_unstable_by_key(|(buffer, _)| {
 4871                buffer.read(cx).file().map(|f| f.path().clone())
 4872            });
 4873        })?;
 4874
 4875        // If the project transaction's edits are all contained within this editor, then
 4876        // avoid opening a new editor to display them.
 4877
 4878        if let Some((buffer, transaction)) = entries.first() {
 4879            if entries.len() == 1 {
 4880                let excerpt = this.update(&mut cx, |editor, cx| {
 4881                    editor
 4882                        .buffer()
 4883                        .read(cx)
 4884                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4885                })?;
 4886                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4887                    if excerpted_buffer == *buffer {
 4888                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4889                            let excerpt_range = excerpt_range.to_offset(buffer);
 4890                            buffer
 4891                                .edited_ranges_for_transaction::<usize>(transaction)
 4892                                .all(|range| {
 4893                                    excerpt_range.start <= range.start
 4894                                        && excerpt_range.end >= range.end
 4895                                })
 4896                        })?;
 4897
 4898                        if all_edits_within_excerpt {
 4899                            return Ok(());
 4900                        }
 4901                    }
 4902                }
 4903            }
 4904        } else {
 4905            return Ok(());
 4906        }
 4907
 4908        let mut ranges_to_highlight = Vec::new();
 4909        let excerpt_buffer = cx.new_model(|cx| {
 4910            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4911            for (buffer_handle, transaction) in &entries {
 4912                let buffer = buffer_handle.read(cx);
 4913                ranges_to_highlight.extend(
 4914                    multibuffer.push_excerpts_with_context_lines(
 4915                        buffer_handle.clone(),
 4916                        buffer
 4917                            .edited_ranges_for_transaction::<usize>(transaction)
 4918                            .collect(),
 4919                        DEFAULT_MULTIBUFFER_CONTEXT,
 4920                        cx,
 4921                    ),
 4922                );
 4923            }
 4924            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4925            multibuffer
 4926        })?;
 4927
 4928        workspace.update(&mut cx, |workspace, cx| {
 4929            let project = workspace.project().clone();
 4930            let editor =
 4931                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4932            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4933            editor.update(cx, |editor, cx| {
 4934                editor.highlight_background::<Self>(
 4935                    &ranges_to_highlight,
 4936                    |theme| theme.editor_highlighted_line_background,
 4937                    cx,
 4938                );
 4939            });
 4940        })?;
 4941
 4942        Ok(())
 4943    }
 4944
 4945    pub fn clear_code_action_providers(&mut self) {
 4946        self.code_action_providers.clear();
 4947        self.available_code_actions.take();
 4948    }
 4949
 4950    pub fn push_code_action_provider(
 4951        &mut self,
 4952        provider: Arc<dyn CodeActionProvider>,
 4953        cx: &mut ViewContext<Self>,
 4954    ) {
 4955        self.code_action_providers.push(provider);
 4956        self.refresh_code_actions(cx);
 4957    }
 4958
 4959    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4960        let buffer = self.buffer.read(cx);
 4961        let newest_selection = self.selections.newest_anchor().clone();
 4962        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4963        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4964        if start_buffer != end_buffer {
 4965            return None;
 4966        }
 4967
 4968        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4969            cx.background_executor()
 4970                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4971                .await;
 4972
 4973            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4974                let providers = this.code_action_providers.clone();
 4975                let tasks = this
 4976                    .code_action_providers
 4977                    .iter()
 4978                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4979                    .collect::<Vec<_>>();
 4980                (providers, tasks)
 4981            })?;
 4982
 4983            let mut actions = Vec::new();
 4984            for (provider, provider_actions) in
 4985                providers.into_iter().zip(future::join_all(tasks).await)
 4986            {
 4987                if let Some(provider_actions) = provider_actions.log_err() {
 4988                    actions.extend(provider_actions.into_iter().map(|action| {
 4989                        AvailableCodeAction {
 4990                            excerpt_id: newest_selection.start.excerpt_id,
 4991                            action,
 4992                            provider: provider.clone(),
 4993                        }
 4994                    }));
 4995                }
 4996            }
 4997
 4998            this.update(&mut cx, |this, cx| {
 4999                this.available_code_actions = if actions.is_empty() {
 5000                    None
 5001                } else {
 5002                    Some((
 5003                        Location {
 5004                            buffer: start_buffer,
 5005                            range: start..end,
 5006                        },
 5007                        actions.into(),
 5008                    ))
 5009                };
 5010                cx.notify();
 5011            })
 5012        }));
 5013        None
 5014    }
 5015
 5016    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5017        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5018            self.show_git_blame_inline = false;
 5019
 5020            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5021                cx.background_executor().timer(delay).await;
 5022
 5023                this.update(&mut cx, |this, cx| {
 5024                    this.show_git_blame_inline = true;
 5025                    cx.notify();
 5026                })
 5027                .log_err();
 5028            }));
 5029        }
 5030    }
 5031
 5032    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5033        if self.pending_rename.is_some() {
 5034            return None;
 5035        }
 5036
 5037        let provider = self.semantics_provider.clone()?;
 5038        let buffer = self.buffer.read(cx);
 5039        let newest_selection = self.selections.newest_anchor().clone();
 5040        let cursor_position = newest_selection.head();
 5041        let (cursor_buffer, cursor_buffer_position) =
 5042            buffer.text_anchor_for_position(cursor_position, cx)?;
 5043        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5044        if cursor_buffer != tail_buffer {
 5045            return None;
 5046        }
 5047
 5048        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5049            cx.background_executor()
 5050                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5051                .await;
 5052
 5053            let highlights = if let Some(highlights) = cx
 5054                .update(|cx| {
 5055                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5056                })
 5057                .ok()
 5058                .flatten()
 5059            {
 5060                highlights.await.log_err()
 5061            } else {
 5062                None
 5063            };
 5064
 5065            if let Some(highlights) = highlights {
 5066                this.update(&mut cx, |this, cx| {
 5067                    if this.pending_rename.is_some() {
 5068                        return;
 5069                    }
 5070
 5071                    let buffer_id = cursor_position.buffer_id;
 5072                    let buffer = this.buffer.read(cx);
 5073                    if !buffer
 5074                        .text_anchor_for_position(cursor_position, cx)
 5075                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5076                    {
 5077                        return;
 5078                    }
 5079
 5080                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5081                    let mut write_ranges = Vec::new();
 5082                    let mut read_ranges = Vec::new();
 5083                    for highlight in highlights {
 5084                        for (excerpt_id, excerpt_range) in
 5085                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5086                        {
 5087                            let start = highlight
 5088                                .range
 5089                                .start
 5090                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5091                            let end = highlight
 5092                                .range
 5093                                .end
 5094                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5095                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5096                                continue;
 5097                            }
 5098
 5099                            let range = Anchor {
 5100                                buffer_id,
 5101                                excerpt_id,
 5102                                text_anchor: start,
 5103                            }..Anchor {
 5104                                buffer_id,
 5105                                excerpt_id,
 5106                                text_anchor: end,
 5107                            };
 5108                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5109                                write_ranges.push(range);
 5110                            } else {
 5111                                read_ranges.push(range);
 5112                            }
 5113                        }
 5114                    }
 5115
 5116                    this.highlight_background::<DocumentHighlightRead>(
 5117                        &read_ranges,
 5118                        |theme| theme.editor_document_highlight_read_background,
 5119                        cx,
 5120                    );
 5121                    this.highlight_background::<DocumentHighlightWrite>(
 5122                        &write_ranges,
 5123                        |theme| theme.editor_document_highlight_write_background,
 5124                        cx,
 5125                    );
 5126                    cx.notify();
 5127                })
 5128                .log_err();
 5129            }
 5130        }));
 5131        None
 5132    }
 5133
 5134    pub fn refresh_inline_completion(
 5135        &mut self,
 5136        debounce: bool,
 5137        user_requested: bool,
 5138        cx: &mut ViewContext<Self>,
 5139    ) -> Option<()> {
 5140        let provider = self.inline_completion_provider()?;
 5141        let cursor = self.selections.newest_anchor().head();
 5142        let (buffer, cursor_buffer_position) =
 5143            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5144
 5145        if !user_requested
 5146            && (!self.enable_inline_completions
 5147                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5148        {
 5149            self.discard_inline_completion(false, cx);
 5150            return None;
 5151        }
 5152
 5153        self.update_visible_inline_completion(cx);
 5154        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5155        Some(())
 5156    }
 5157
 5158    fn cycle_inline_completion(
 5159        &mut self,
 5160        direction: Direction,
 5161        cx: &mut ViewContext<Self>,
 5162    ) -> Option<()> {
 5163        let provider = self.inline_completion_provider()?;
 5164        let cursor = self.selections.newest_anchor().head();
 5165        let (buffer, cursor_buffer_position) =
 5166            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5167        if !self.enable_inline_completions
 5168            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5169        {
 5170            return None;
 5171        }
 5172
 5173        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5174        self.update_visible_inline_completion(cx);
 5175
 5176        Some(())
 5177    }
 5178
 5179    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5180        if !self.has_active_inline_completion(cx) {
 5181            self.refresh_inline_completion(false, true, cx);
 5182            return;
 5183        }
 5184
 5185        self.update_visible_inline_completion(cx);
 5186    }
 5187
 5188    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5189        self.show_cursor_names(cx);
 5190    }
 5191
 5192    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5193        self.show_cursor_names = true;
 5194        cx.notify();
 5195        cx.spawn(|this, mut cx| async move {
 5196            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5197            this.update(&mut cx, |this, cx| {
 5198                this.show_cursor_names = false;
 5199                cx.notify()
 5200            })
 5201            .ok()
 5202        })
 5203        .detach();
 5204    }
 5205
 5206    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5207        if self.has_active_inline_completion(cx) {
 5208            self.cycle_inline_completion(Direction::Next, cx);
 5209        } else {
 5210            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5211            if is_copilot_disabled {
 5212                cx.propagate();
 5213            }
 5214        }
 5215    }
 5216
 5217    pub fn previous_inline_completion(
 5218        &mut self,
 5219        _: &PreviousInlineCompletion,
 5220        cx: &mut ViewContext<Self>,
 5221    ) {
 5222        if self.has_active_inline_completion(cx) {
 5223            self.cycle_inline_completion(Direction::Prev, cx);
 5224        } else {
 5225            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5226            if is_copilot_disabled {
 5227                cx.propagate();
 5228            }
 5229        }
 5230    }
 5231
 5232    pub fn accept_inline_completion(
 5233        &mut self,
 5234        _: &AcceptInlineCompletion,
 5235        cx: &mut ViewContext<Self>,
 5236    ) {
 5237        let Some(completion) = self.take_active_inline_completion(cx) else {
 5238            return;
 5239        };
 5240        if let Some(provider) = self.inline_completion_provider() {
 5241            provider.accept(cx);
 5242        }
 5243
 5244        cx.emit(EditorEvent::InputHandled {
 5245            utf16_range_to_replace: None,
 5246            text: completion.text.to_string().into(),
 5247        });
 5248
 5249        if let Some(range) = completion.delete_range {
 5250            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5251        }
 5252        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5253        self.refresh_inline_completion(true, true, cx);
 5254        cx.notify();
 5255    }
 5256
 5257    pub fn accept_partial_inline_completion(
 5258        &mut self,
 5259        _: &AcceptPartialInlineCompletion,
 5260        cx: &mut ViewContext<Self>,
 5261    ) {
 5262        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5263            if let Some(completion) = self.take_active_inline_completion(cx) {
 5264                let mut partial_completion = completion
 5265                    .text
 5266                    .chars()
 5267                    .by_ref()
 5268                    .take_while(|c| c.is_alphabetic())
 5269                    .collect::<String>();
 5270                if partial_completion.is_empty() {
 5271                    partial_completion = completion
 5272                        .text
 5273                        .chars()
 5274                        .by_ref()
 5275                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5276                        .collect::<String>();
 5277                }
 5278
 5279                cx.emit(EditorEvent::InputHandled {
 5280                    utf16_range_to_replace: None,
 5281                    text: partial_completion.clone().into(),
 5282                });
 5283
 5284                if let Some(range) = completion.delete_range {
 5285                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5286                }
 5287                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5288
 5289                self.refresh_inline_completion(true, true, cx);
 5290                cx.notify();
 5291            }
 5292        }
 5293    }
 5294
 5295    fn discard_inline_completion(
 5296        &mut self,
 5297        should_report_inline_completion_event: bool,
 5298        cx: &mut ViewContext<Self>,
 5299    ) -> bool {
 5300        if let Some(provider) = self.inline_completion_provider() {
 5301            provider.discard(should_report_inline_completion_event, cx);
 5302        }
 5303
 5304        self.take_active_inline_completion(cx).is_some()
 5305    }
 5306
 5307    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5308        if let Some(completion) = self.active_inline_completion.as_ref() {
 5309            let buffer = self.buffer.read(cx).read(cx);
 5310            completion.position.is_valid(&buffer)
 5311        } else {
 5312            false
 5313        }
 5314    }
 5315
 5316    fn take_active_inline_completion(
 5317        &mut self,
 5318        cx: &mut ViewContext<Self>,
 5319    ) -> Option<CompletionState> {
 5320        let completion = self.active_inline_completion.take()?;
 5321        let render_inlay_ids = completion.render_inlay_ids.clone();
 5322        self.display_map.update(cx, |map, cx| {
 5323            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5324        });
 5325        let buffer = self.buffer.read(cx).read(cx);
 5326
 5327        if completion.position.is_valid(&buffer) {
 5328            Some(completion)
 5329        } else {
 5330            None
 5331        }
 5332    }
 5333
 5334    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5335        let selection = self.selections.newest_anchor();
 5336        let cursor = selection.head();
 5337
 5338        let excerpt_id = cursor.excerpt_id;
 5339
 5340        if self.context_menu.read().is_none()
 5341            && self.completion_tasks.is_empty()
 5342            && selection.start == selection.end
 5343        {
 5344            if let Some(provider) = self.inline_completion_provider() {
 5345                if let Some((buffer, cursor_buffer_position)) =
 5346                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5347                {
 5348                    if let Some(proposal) =
 5349                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5350                    {
 5351                        let mut to_remove = Vec::new();
 5352                        if let Some(completion) = self.active_inline_completion.take() {
 5353                            to_remove.extend(completion.render_inlay_ids.iter());
 5354                        }
 5355
 5356                        let to_add = proposal
 5357                            .inlays
 5358                            .iter()
 5359                            .filter_map(|inlay| {
 5360                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5361                                let id = post_inc(&mut self.next_inlay_id);
 5362                                match inlay {
 5363                                    InlayProposal::Hint(position, hint) => {
 5364                                        let position =
 5365                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5366                                        Some(Inlay::hint(id, position, hint))
 5367                                    }
 5368                                    InlayProposal::Suggestion(position, text) => {
 5369                                        let position =
 5370                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5371                                        Some(Inlay::suggestion(id, position, text.clone()))
 5372                                    }
 5373                                }
 5374                            })
 5375                            .collect_vec();
 5376
 5377                        self.active_inline_completion = Some(CompletionState {
 5378                            position: cursor,
 5379                            text: proposal.text,
 5380                            delete_range: proposal.delete_range.and_then(|range| {
 5381                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5382                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5383                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5384                                Some(start?..end?)
 5385                            }),
 5386                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5387                        });
 5388
 5389                        self.display_map
 5390                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5391
 5392                        cx.notify();
 5393                        return;
 5394                    }
 5395                }
 5396            }
 5397        }
 5398
 5399        self.discard_inline_completion(false, cx);
 5400    }
 5401
 5402    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5403        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5404    }
 5405
 5406    fn render_code_actions_indicator(
 5407        &self,
 5408        _style: &EditorStyle,
 5409        row: DisplayRow,
 5410        is_active: bool,
 5411        cx: &mut ViewContext<Self>,
 5412    ) -> Option<IconButton> {
 5413        if self.available_code_actions.is_some() {
 5414            Some(
 5415                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5416                    .shape(ui::IconButtonShape::Square)
 5417                    .icon_size(IconSize::XSmall)
 5418                    .icon_color(Color::Muted)
 5419                    .selected(is_active)
 5420                    .tooltip({
 5421                        let focus_handle = self.focus_handle.clone();
 5422                        move |cx| {
 5423                            Tooltip::for_action_in(
 5424                                "Toggle Code Actions",
 5425                                &ToggleCodeActions {
 5426                                    deployed_from_indicator: None,
 5427                                },
 5428                                &focus_handle,
 5429                                cx,
 5430                            )
 5431                        }
 5432                    })
 5433                    .on_click(cx.listener(move |editor, _e, cx| {
 5434                        editor.focus(cx);
 5435                        editor.toggle_code_actions(
 5436                            &ToggleCodeActions {
 5437                                deployed_from_indicator: Some(row),
 5438                            },
 5439                            cx,
 5440                        );
 5441                    })),
 5442            )
 5443        } else {
 5444            None
 5445        }
 5446    }
 5447
 5448    fn clear_tasks(&mut self) {
 5449        self.tasks.clear()
 5450    }
 5451
 5452    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5453        if self.tasks.insert(key, value).is_some() {
 5454            // This case should hopefully be rare, but just in case...
 5455            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5456        }
 5457    }
 5458
 5459    fn build_tasks_context(
 5460        project: &Model<Project>,
 5461        buffer: &Model<Buffer>,
 5462        buffer_row: u32,
 5463        tasks: &Arc<RunnableTasks>,
 5464        cx: &mut ViewContext<Self>,
 5465    ) -> Task<Option<task::TaskContext>> {
 5466        let position = Point::new(buffer_row, tasks.column);
 5467        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5468        let location = Location {
 5469            buffer: buffer.clone(),
 5470            range: range_start..range_start,
 5471        };
 5472        // Fill in the environmental variables from the tree-sitter captures
 5473        let mut captured_task_variables = TaskVariables::default();
 5474        for (capture_name, value) in tasks.extra_variables.clone() {
 5475            captured_task_variables.insert(
 5476                task::VariableName::Custom(capture_name.into()),
 5477                value.clone(),
 5478            );
 5479        }
 5480        project.update(cx, |project, cx| {
 5481            project.task_store().update(cx, |task_store, cx| {
 5482                task_store.task_context_for_location(captured_task_variables, location, cx)
 5483            })
 5484        })
 5485    }
 5486
 5487    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5488        let Some((workspace, _)) = self.workspace.clone() else {
 5489            return;
 5490        };
 5491        let Some(project) = self.project.clone() else {
 5492            return;
 5493        };
 5494
 5495        // Try to find a closest, enclosing node using tree-sitter that has a
 5496        // task
 5497        let Some((buffer, buffer_row, tasks)) = self
 5498            .find_enclosing_node_task(cx)
 5499            // Or find the task that's closest in row-distance.
 5500            .or_else(|| self.find_closest_task(cx))
 5501        else {
 5502            return;
 5503        };
 5504
 5505        let reveal_strategy = action.reveal;
 5506        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5507        cx.spawn(|_, mut cx| async move {
 5508            let context = task_context.await?;
 5509            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5510
 5511            let resolved = resolved_task.resolved.as_mut()?;
 5512            resolved.reveal = reveal_strategy;
 5513
 5514            workspace
 5515                .update(&mut cx, |workspace, cx| {
 5516                    workspace::tasks::schedule_resolved_task(
 5517                        workspace,
 5518                        task_source_kind,
 5519                        resolved_task,
 5520                        false,
 5521                        cx,
 5522                    );
 5523                })
 5524                .ok()
 5525        })
 5526        .detach();
 5527    }
 5528
 5529    fn find_closest_task(
 5530        &mut self,
 5531        cx: &mut ViewContext<Self>,
 5532    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5533        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5534
 5535        let ((buffer_id, row), tasks) = self
 5536            .tasks
 5537            .iter()
 5538            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5539
 5540        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5541        let tasks = Arc::new(tasks.to_owned());
 5542        Some((buffer, *row, tasks))
 5543    }
 5544
 5545    fn find_enclosing_node_task(
 5546        &mut self,
 5547        cx: &mut ViewContext<Self>,
 5548    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5549        let snapshot = self.buffer.read(cx).snapshot(cx);
 5550        let offset = self.selections.newest::<usize>(cx).head();
 5551        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5552        let buffer_id = excerpt.buffer().remote_id();
 5553
 5554        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5555        let mut cursor = layer.node().walk();
 5556
 5557        while cursor.goto_first_child_for_byte(offset).is_some() {
 5558            if cursor.node().end_byte() == offset {
 5559                cursor.goto_next_sibling();
 5560            }
 5561        }
 5562
 5563        // Ascend to the smallest ancestor that contains the range and has a task.
 5564        loop {
 5565            let node = cursor.node();
 5566            let node_range = node.byte_range();
 5567            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5568
 5569            // Check if this node contains our offset
 5570            if node_range.start <= offset && node_range.end >= offset {
 5571                // If it contains offset, check for task
 5572                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5573                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5574                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5575                }
 5576            }
 5577
 5578            if !cursor.goto_parent() {
 5579                break;
 5580            }
 5581        }
 5582        None
 5583    }
 5584
 5585    fn render_run_indicator(
 5586        &self,
 5587        _style: &EditorStyle,
 5588        is_active: bool,
 5589        row: DisplayRow,
 5590        cx: &mut ViewContext<Self>,
 5591    ) -> IconButton {
 5592        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5593            .shape(ui::IconButtonShape::Square)
 5594            .icon_size(IconSize::XSmall)
 5595            .icon_color(Color::Muted)
 5596            .selected(is_active)
 5597            .on_click(cx.listener(move |editor, _e, cx| {
 5598                editor.focus(cx);
 5599                editor.toggle_code_actions(
 5600                    &ToggleCodeActions {
 5601                        deployed_from_indicator: Some(row),
 5602                    },
 5603                    cx,
 5604                );
 5605            }))
 5606    }
 5607
 5608    pub fn context_menu_visible(&self) -> bool {
 5609        self.context_menu
 5610            .read()
 5611            .as_ref()
 5612            .map_or(false, |menu| menu.visible())
 5613    }
 5614
 5615    fn render_context_menu(
 5616        &self,
 5617        cursor_position: DisplayPoint,
 5618        style: &EditorStyle,
 5619        max_height: Pixels,
 5620        cx: &mut ViewContext<Editor>,
 5621    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5622        self.context_menu.read().as_ref().map(|menu| {
 5623            menu.render(
 5624                cursor_position,
 5625                style,
 5626                max_height,
 5627                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5628                cx,
 5629            )
 5630        })
 5631    }
 5632
 5633    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5634        cx.notify();
 5635        self.completion_tasks.clear();
 5636        let context_menu = self.context_menu.write().take();
 5637        if context_menu.is_some() {
 5638            self.update_visible_inline_completion(cx);
 5639        }
 5640        context_menu
 5641    }
 5642
 5643    pub fn insert_snippet(
 5644        &mut self,
 5645        insertion_ranges: &[Range<usize>],
 5646        snippet: Snippet,
 5647        cx: &mut ViewContext<Self>,
 5648    ) -> Result<()> {
 5649        struct Tabstop<T> {
 5650            is_end_tabstop: bool,
 5651            ranges: Vec<Range<T>>,
 5652        }
 5653
 5654        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5655            let snippet_text: Arc<str> = snippet.text.clone().into();
 5656            buffer.edit(
 5657                insertion_ranges
 5658                    .iter()
 5659                    .cloned()
 5660                    .map(|range| (range, snippet_text.clone())),
 5661                Some(AutoindentMode::EachLine),
 5662                cx,
 5663            );
 5664
 5665            let snapshot = &*buffer.read(cx);
 5666            let snippet = &snippet;
 5667            snippet
 5668                .tabstops
 5669                .iter()
 5670                .map(|tabstop| {
 5671                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5672                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5673                    });
 5674                    let mut tabstop_ranges = tabstop
 5675                        .iter()
 5676                        .flat_map(|tabstop_range| {
 5677                            let mut delta = 0_isize;
 5678                            insertion_ranges.iter().map(move |insertion_range| {
 5679                                let insertion_start = insertion_range.start as isize + delta;
 5680                                delta +=
 5681                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5682
 5683                                let start = ((insertion_start + tabstop_range.start) as usize)
 5684                                    .min(snapshot.len());
 5685                                let end = ((insertion_start + tabstop_range.end) as usize)
 5686                                    .min(snapshot.len());
 5687                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5688                            })
 5689                        })
 5690                        .collect::<Vec<_>>();
 5691                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5692
 5693                    Tabstop {
 5694                        is_end_tabstop,
 5695                        ranges: tabstop_ranges,
 5696                    }
 5697                })
 5698                .collect::<Vec<_>>()
 5699        });
 5700        if let Some(tabstop) = tabstops.first() {
 5701            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5702                s.select_ranges(tabstop.ranges.iter().cloned());
 5703            });
 5704
 5705            // If we're already at the last tabstop and it's at the end of the snippet,
 5706            // we're done, we don't need to keep the state around.
 5707            if !tabstop.is_end_tabstop {
 5708                let ranges = tabstops
 5709                    .into_iter()
 5710                    .map(|tabstop| tabstop.ranges)
 5711                    .collect::<Vec<_>>();
 5712                self.snippet_stack.push(SnippetState {
 5713                    active_index: 0,
 5714                    ranges,
 5715                });
 5716            }
 5717
 5718            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5719            if self.autoclose_regions.is_empty() {
 5720                let snapshot = self.buffer.read(cx).snapshot(cx);
 5721                for selection in &mut self.selections.all::<Point>(cx) {
 5722                    let selection_head = selection.head();
 5723                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5724                        continue;
 5725                    };
 5726
 5727                    let mut bracket_pair = None;
 5728                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5729                    let prev_chars = snapshot
 5730                        .reversed_chars_at(selection_head)
 5731                        .collect::<String>();
 5732                    for (pair, enabled) in scope.brackets() {
 5733                        if enabled
 5734                            && pair.close
 5735                            && prev_chars.starts_with(pair.start.as_str())
 5736                            && next_chars.starts_with(pair.end.as_str())
 5737                        {
 5738                            bracket_pair = Some(pair.clone());
 5739                            break;
 5740                        }
 5741                    }
 5742                    if let Some(pair) = bracket_pair {
 5743                        let start = snapshot.anchor_after(selection_head);
 5744                        let end = snapshot.anchor_after(selection_head);
 5745                        self.autoclose_regions.push(AutocloseRegion {
 5746                            selection_id: selection.id,
 5747                            range: start..end,
 5748                            pair,
 5749                        });
 5750                    }
 5751                }
 5752            }
 5753        }
 5754        Ok(())
 5755    }
 5756
 5757    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5758        self.move_to_snippet_tabstop(Bias::Right, cx)
 5759    }
 5760
 5761    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5762        self.move_to_snippet_tabstop(Bias::Left, cx)
 5763    }
 5764
 5765    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5766        if let Some(mut snippet) = self.snippet_stack.pop() {
 5767            match bias {
 5768                Bias::Left => {
 5769                    if snippet.active_index > 0 {
 5770                        snippet.active_index -= 1;
 5771                    } else {
 5772                        self.snippet_stack.push(snippet);
 5773                        return false;
 5774                    }
 5775                }
 5776                Bias::Right => {
 5777                    if snippet.active_index + 1 < snippet.ranges.len() {
 5778                        snippet.active_index += 1;
 5779                    } else {
 5780                        self.snippet_stack.push(snippet);
 5781                        return false;
 5782                    }
 5783                }
 5784            }
 5785            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5786                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5787                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5788                });
 5789                // If snippet state is not at the last tabstop, push it back on the stack
 5790                if snippet.active_index + 1 < snippet.ranges.len() {
 5791                    self.snippet_stack.push(snippet);
 5792                }
 5793                return true;
 5794            }
 5795        }
 5796
 5797        false
 5798    }
 5799
 5800    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5801        self.transact(cx, |this, cx| {
 5802            this.select_all(&SelectAll, cx);
 5803            this.insert("", cx);
 5804        });
 5805    }
 5806
 5807    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5808        self.transact(cx, |this, cx| {
 5809            this.select_autoclose_pair(cx);
 5810            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5811            if !this.linked_edit_ranges.is_empty() {
 5812                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5813                let snapshot = this.buffer.read(cx).snapshot(cx);
 5814
 5815                for selection in selections.iter() {
 5816                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5817                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5818                    if selection_start.buffer_id != selection_end.buffer_id {
 5819                        continue;
 5820                    }
 5821                    if let Some(ranges) =
 5822                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5823                    {
 5824                        for (buffer, entries) in ranges {
 5825                            linked_ranges.entry(buffer).or_default().extend(entries);
 5826                        }
 5827                    }
 5828                }
 5829            }
 5830
 5831            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5832            if !this.selections.line_mode {
 5833                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5834                for selection in &mut selections {
 5835                    if selection.is_empty() {
 5836                        let old_head = selection.head();
 5837                        let mut new_head =
 5838                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5839                                .to_point(&display_map);
 5840                        if let Some((buffer, line_buffer_range)) = display_map
 5841                            .buffer_snapshot
 5842                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5843                        {
 5844                            let indent_size =
 5845                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5846                            let indent_len = match indent_size.kind {
 5847                                IndentKind::Space => {
 5848                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5849                                }
 5850                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5851                            };
 5852                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5853                                let indent_len = indent_len.get();
 5854                                new_head = cmp::min(
 5855                                    new_head,
 5856                                    MultiBufferPoint::new(
 5857                                        old_head.row,
 5858                                        ((old_head.column - 1) / indent_len) * indent_len,
 5859                                    ),
 5860                                );
 5861                            }
 5862                        }
 5863
 5864                        selection.set_head(new_head, SelectionGoal::None);
 5865                    }
 5866                }
 5867            }
 5868
 5869            this.signature_help_state.set_backspace_pressed(true);
 5870            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5871            this.insert("", cx);
 5872            let empty_str: Arc<str> = Arc::from("");
 5873            for (buffer, edits) in linked_ranges {
 5874                let snapshot = buffer.read(cx).snapshot();
 5875                use text::ToPoint as TP;
 5876
 5877                let edits = edits
 5878                    .into_iter()
 5879                    .map(|range| {
 5880                        let end_point = TP::to_point(&range.end, &snapshot);
 5881                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5882
 5883                        if end_point == start_point {
 5884                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5885                                .saturating_sub(1);
 5886                            start_point = TP::to_point(&offset, &snapshot);
 5887                        };
 5888
 5889                        (start_point..end_point, empty_str.clone())
 5890                    })
 5891                    .sorted_by_key(|(range, _)| range.start)
 5892                    .collect::<Vec<_>>();
 5893                buffer.update(cx, |this, cx| {
 5894                    this.edit(edits, None, cx);
 5895                })
 5896            }
 5897            this.refresh_inline_completion(true, false, cx);
 5898            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5899        });
 5900    }
 5901
 5902    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5903        self.transact(cx, |this, cx| {
 5904            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5905                let line_mode = s.line_mode;
 5906                s.move_with(|map, selection| {
 5907                    if selection.is_empty() && !line_mode {
 5908                        let cursor = movement::right(map, selection.head());
 5909                        selection.end = cursor;
 5910                        selection.reversed = true;
 5911                        selection.goal = SelectionGoal::None;
 5912                    }
 5913                })
 5914            });
 5915            this.insert("", cx);
 5916            this.refresh_inline_completion(true, false, cx);
 5917        });
 5918    }
 5919
 5920    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5921        if self.move_to_prev_snippet_tabstop(cx) {
 5922            return;
 5923        }
 5924
 5925        self.outdent(&Outdent, cx);
 5926    }
 5927
 5928    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5929        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5930            return;
 5931        }
 5932
 5933        let mut selections = self.selections.all_adjusted(cx);
 5934        let buffer = self.buffer.read(cx);
 5935        let snapshot = buffer.snapshot(cx);
 5936        let rows_iter = selections.iter().map(|s| s.head().row);
 5937        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5938
 5939        let mut edits = Vec::new();
 5940        let mut prev_edited_row = 0;
 5941        let mut row_delta = 0;
 5942        for selection in &mut selections {
 5943            if selection.start.row != prev_edited_row {
 5944                row_delta = 0;
 5945            }
 5946            prev_edited_row = selection.end.row;
 5947
 5948            // If the selection is non-empty, then increase the indentation of the selected lines.
 5949            if !selection.is_empty() {
 5950                row_delta =
 5951                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5952                continue;
 5953            }
 5954
 5955            // If the selection is empty and the cursor is in the leading whitespace before the
 5956            // suggested indentation, then auto-indent the line.
 5957            let cursor = selection.head();
 5958            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5959            if let Some(suggested_indent) =
 5960                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5961            {
 5962                if cursor.column < suggested_indent.len
 5963                    && cursor.column <= current_indent.len
 5964                    && current_indent.len <= suggested_indent.len
 5965                {
 5966                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5967                    selection.end = selection.start;
 5968                    if row_delta == 0 {
 5969                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5970                            cursor.row,
 5971                            current_indent,
 5972                            suggested_indent,
 5973                        ));
 5974                        row_delta = suggested_indent.len - current_indent.len;
 5975                    }
 5976                    continue;
 5977                }
 5978            }
 5979
 5980            // Otherwise, insert a hard or soft tab.
 5981            let settings = buffer.settings_at(cursor, cx);
 5982            let tab_size = if settings.hard_tabs {
 5983                IndentSize::tab()
 5984            } else {
 5985                let tab_size = settings.tab_size.get();
 5986                let char_column = snapshot
 5987                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5988                    .flat_map(str::chars)
 5989                    .count()
 5990                    + row_delta as usize;
 5991                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5992                IndentSize::spaces(chars_to_next_tab_stop)
 5993            };
 5994            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5995            selection.end = selection.start;
 5996            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5997            row_delta += tab_size.len;
 5998        }
 5999
 6000        self.transact(cx, |this, cx| {
 6001            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6002            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6003            this.refresh_inline_completion(true, false, cx);
 6004        });
 6005    }
 6006
 6007    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6008        if self.read_only(cx) {
 6009            return;
 6010        }
 6011        let mut selections = self.selections.all::<Point>(cx);
 6012        let mut prev_edited_row = 0;
 6013        let mut row_delta = 0;
 6014        let mut edits = Vec::new();
 6015        let buffer = self.buffer.read(cx);
 6016        let snapshot = buffer.snapshot(cx);
 6017        for selection in &mut selections {
 6018            if selection.start.row != prev_edited_row {
 6019                row_delta = 0;
 6020            }
 6021            prev_edited_row = selection.end.row;
 6022
 6023            row_delta =
 6024                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6025        }
 6026
 6027        self.transact(cx, |this, cx| {
 6028            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6029            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6030        });
 6031    }
 6032
 6033    fn indent_selection(
 6034        buffer: &MultiBuffer,
 6035        snapshot: &MultiBufferSnapshot,
 6036        selection: &mut Selection<Point>,
 6037        edits: &mut Vec<(Range<Point>, String)>,
 6038        delta_for_start_row: u32,
 6039        cx: &AppContext,
 6040    ) -> u32 {
 6041        let settings = buffer.settings_at(selection.start, cx);
 6042        let tab_size = settings.tab_size.get();
 6043        let indent_kind = if settings.hard_tabs {
 6044            IndentKind::Tab
 6045        } else {
 6046            IndentKind::Space
 6047        };
 6048        let mut start_row = selection.start.row;
 6049        let mut end_row = selection.end.row + 1;
 6050
 6051        // If a selection ends at the beginning of a line, don't indent
 6052        // that last line.
 6053        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6054            end_row -= 1;
 6055        }
 6056
 6057        // Avoid re-indenting a row that has already been indented by a
 6058        // previous selection, but still update this selection's column
 6059        // to reflect that indentation.
 6060        if delta_for_start_row > 0 {
 6061            start_row += 1;
 6062            selection.start.column += delta_for_start_row;
 6063            if selection.end.row == selection.start.row {
 6064                selection.end.column += delta_for_start_row;
 6065            }
 6066        }
 6067
 6068        let mut delta_for_end_row = 0;
 6069        let has_multiple_rows = start_row + 1 != end_row;
 6070        for row in start_row..end_row {
 6071            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6072            let indent_delta = match (current_indent.kind, indent_kind) {
 6073                (IndentKind::Space, IndentKind::Space) => {
 6074                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6075                    IndentSize::spaces(columns_to_next_tab_stop)
 6076                }
 6077                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6078                (_, IndentKind::Tab) => IndentSize::tab(),
 6079            };
 6080
 6081            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6082                0
 6083            } else {
 6084                selection.start.column
 6085            };
 6086            let row_start = Point::new(row, start);
 6087            edits.push((
 6088                row_start..row_start,
 6089                indent_delta.chars().collect::<String>(),
 6090            ));
 6091
 6092            // Update this selection's endpoints to reflect the indentation.
 6093            if row == selection.start.row {
 6094                selection.start.column += indent_delta.len;
 6095            }
 6096            if row == selection.end.row {
 6097                selection.end.column += indent_delta.len;
 6098                delta_for_end_row = indent_delta.len;
 6099            }
 6100        }
 6101
 6102        if selection.start.row == selection.end.row {
 6103            delta_for_start_row + delta_for_end_row
 6104        } else {
 6105            delta_for_end_row
 6106        }
 6107    }
 6108
 6109    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6110        if self.read_only(cx) {
 6111            return;
 6112        }
 6113        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6114        let selections = self.selections.all::<Point>(cx);
 6115        let mut deletion_ranges = Vec::new();
 6116        let mut last_outdent = None;
 6117        {
 6118            let buffer = self.buffer.read(cx);
 6119            let snapshot = buffer.snapshot(cx);
 6120            for selection in &selections {
 6121                let settings = buffer.settings_at(selection.start, cx);
 6122                let tab_size = settings.tab_size.get();
 6123                let mut rows = selection.spanned_rows(false, &display_map);
 6124
 6125                // Avoid re-outdenting a row that has already been outdented by a
 6126                // previous selection.
 6127                if let Some(last_row) = last_outdent {
 6128                    if last_row == rows.start {
 6129                        rows.start = rows.start.next_row();
 6130                    }
 6131                }
 6132                let has_multiple_rows = rows.len() > 1;
 6133                for row in rows.iter_rows() {
 6134                    let indent_size = snapshot.indent_size_for_line(row);
 6135                    if indent_size.len > 0 {
 6136                        let deletion_len = match indent_size.kind {
 6137                            IndentKind::Space => {
 6138                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6139                                if columns_to_prev_tab_stop == 0 {
 6140                                    tab_size
 6141                                } else {
 6142                                    columns_to_prev_tab_stop
 6143                                }
 6144                            }
 6145                            IndentKind::Tab => 1,
 6146                        };
 6147                        let start = if has_multiple_rows
 6148                            || deletion_len > selection.start.column
 6149                            || indent_size.len < selection.start.column
 6150                        {
 6151                            0
 6152                        } else {
 6153                            selection.start.column - deletion_len
 6154                        };
 6155                        deletion_ranges.push(
 6156                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6157                        );
 6158                        last_outdent = Some(row);
 6159                    }
 6160                }
 6161            }
 6162        }
 6163
 6164        self.transact(cx, |this, cx| {
 6165            this.buffer.update(cx, |buffer, cx| {
 6166                let empty_str: Arc<str> = Arc::default();
 6167                buffer.edit(
 6168                    deletion_ranges
 6169                        .into_iter()
 6170                        .map(|range| (range, empty_str.clone())),
 6171                    None,
 6172                    cx,
 6173                );
 6174            });
 6175            let selections = this.selections.all::<usize>(cx);
 6176            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6177        });
 6178    }
 6179
 6180    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6181        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6182        let selections = self.selections.all::<Point>(cx);
 6183
 6184        let mut new_cursors = Vec::new();
 6185        let mut edit_ranges = Vec::new();
 6186        let mut selections = selections.iter().peekable();
 6187        while let Some(selection) = selections.next() {
 6188            let mut rows = selection.spanned_rows(false, &display_map);
 6189            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6190
 6191            // Accumulate contiguous regions of rows that we want to delete.
 6192            while let Some(next_selection) = selections.peek() {
 6193                let next_rows = next_selection.spanned_rows(false, &display_map);
 6194                if next_rows.start <= rows.end {
 6195                    rows.end = next_rows.end;
 6196                    selections.next().unwrap();
 6197                } else {
 6198                    break;
 6199                }
 6200            }
 6201
 6202            let buffer = &display_map.buffer_snapshot;
 6203            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6204            let edit_end;
 6205            let cursor_buffer_row;
 6206            if buffer.max_point().row >= rows.end.0 {
 6207                // If there's a line after the range, delete the \n from the end of the row range
 6208                // and position the cursor on the next line.
 6209                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6210                cursor_buffer_row = rows.end;
 6211            } else {
 6212                // If there isn't a line after the range, delete the \n from the line before the
 6213                // start of the row range and position the cursor there.
 6214                edit_start = edit_start.saturating_sub(1);
 6215                edit_end = buffer.len();
 6216                cursor_buffer_row = rows.start.previous_row();
 6217            }
 6218
 6219            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6220            *cursor.column_mut() =
 6221                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6222
 6223            new_cursors.push((
 6224                selection.id,
 6225                buffer.anchor_after(cursor.to_point(&display_map)),
 6226            ));
 6227            edit_ranges.push(edit_start..edit_end);
 6228        }
 6229
 6230        self.transact(cx, |this, cx| {
 6231            let buffer = this.buffer.update(cx, |buffer, cx| {
 6232                let empty_str: Arc<str> = Arc::default();
 6233                buffer.edit(
 6234                    edit_ranges
 6235                        .into_iter()
 6236                        .map(|range| (range, empty_str.clone())),
 6237                    None,
 6238                    cx,
 6239                );
 6240                buffer.snapshot(cx)
 6241            });
 6242            let new_selections = new_cursors
 6243                .into_iter()
 6244                .map(|(id, cursor)| {
 6245                    let cursor = cursor.to_point(&buffer);
 6246                    Selection {
 6247                        id,
 6248                        start: cursor,
 6249                        end: cursor,
 6250                        reversed: false,
 6251                        goal: SelectionGoal::None,
 6252                    }
 6253                })
 6254                .collect();
 6255
 6256            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6257                s.select(new_selections);
 6258            });
 6259        });
 6260    }
 6261
 6262    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6263        if self.read_only(cx) {
 6264            return;
 6265        }
 6266        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6267        for selection in self.selections.all::<Point>(cx) {
 6268            let start = MultiBufferRow(selection.start.row);
 6269            let end = if selection.start.row == selection.end.row {
 6270                MultiBufferRow(selection.start.row + 1)
 6271            } else {
 6272                MultiBufferRow(selection.end.row)
 6273            };
 6274
 6275            if let Some(last_row_range) = row_ranges.last_mut() {
 6276                if start <= last_row_range.end {
 6277                    last_row_range.end = end;
 6278                    continue;
 6279                }
 6280            }
 6281            row_ranges.push(start..end);
 6282        }
 6283
 6284        let snapshot = self.buffer.read(cx).snapshot(cx);
 6285        let mut cursor_positions = Vec::new();
 6286        for row_range in &row_ranges {
 6287            let anchor = snapshot.anchor_before(Point::new(
 6288                row_range.end.previous_row().0,
 6289                snapshot.line_len(row_range.end.previous_row()),
 6290            ));
 6291            cursor_positions.push(anchor..anchor);
 6292        }
 6293
 6294        self.transact(cx, |this, cx| {
 6295            for row_range in row_ranges.into_iter().rev() {
 6296                for row in row_range.iter_rows().rev() {
 6297                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6298                    let next_line_row = row.next_row();
 6299                    let indent = snapshot.indent_size_for_line(next_line_row);
 6300                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6301
 6302                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6303                        " "
 6304                    } else {
 6305                        ""
 6306                    };
 6307
 6308                    this.buffer.update(cx, |buffer, cx| {
 6309                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6310                    });
 6311                }
 6312            }
 6313
 6314            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6315                s.select_anchor_ranges(cursor_positions)
 6316            });
 6317        });
 6318    }
 6319
 6320    pub fn sort_lines_case_sensitive(
 6321        &mut self,
 6322        _: &SortLinesCaseSensitive,
 6323        cx: &mut ViewContext<Self>,
 6324    ) {
 6325        self.manipulate_lines(cx, |lines| lines.sort())
 6326    }
 6327
 6328    pub fn sort_lines_case_insensitive(
 6329        &mut self,
 6330        _: &SortLinesCaseInsensitive,
 6331        cx: &mut ViewContext<Self>,
 6332    ) {
 6333        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6334    }
 6335
 6336    pub fn unique_lines_case_insensitive(
 6337        &mut self,
 6338        _: &UniqueLinesCaseInsensitive,
 6339        cx: &mut ViewContext<Self>,
 6340    ) {
 6341        self.manipulate_lines(cx, |lines| {
 6342            let mut seen = HashSet::default();
 6343            lines.retain(|line| seen.insert(line.to_lowercase()));
 6344        })
 6345    }
 6346
 6347    pub fn unique_lines_case_sensitive(
 6348        &mut self,
 6349        _: &UniqueLinesCaseSensitive,
 6350        cx: &mut ViewContext<Self>,
 6351    ) {
 6352        self.manipulate_lines(cx, |lines| {
 6353            let mut seen = HashSet::default();
 6354            lines.retain(|line| seen.insert(*line));
 6355        })
 6356    }
 6357
 6358    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6359        let mut revert_changes = HashMap::default();
 6360        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6361        for hunk in hunks_for_rows(
 6362            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6363            &multi_buffer_snapshot,
 6364        ) {
 6365            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6366        }
 6367        if !revert_changes.is_empty() {
 6368            self.transact(cx, |editor, cx| {
 6369                editor.revert(revert_changes, cx);
 6370            });
 6371        }
 6372    }
 6373
 6374    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6375        let Some(project) = self.project.clone() else {
 6376            return;
 6377        };
 6378        self.reload(project, cx).detach_and_notify_err(cx);
 6379    }
 6380
 6381    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6382        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6383        if !revert_changes.is_empty() {
 6384            self.transact(cx, |editor, cx| {
 6385                editor.revert(revert_changes, cx);
 6386            });
 6387        }
 6388    }
 6389
 6390    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6391        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6392            let project_path = buffer.read(cx).project_path(cx)?;
 6393            let project = self.project.as_ref()?.read(cx);
 6394            let entry = project.entry_for_path(&project_path, cx)?;
 6395            let parent = match &entry.canonical_path {
 6396                Some(canonical_path) => canonical_path.to_path_buf(),
 6397                None => project.absolute_path(&project_path, cx)?,
 6398            }
 6399            .parent()?
 6400            .to_path_buf();
 6401            Some(parent)
 6402        }) {
 6403            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6404        }
 6405    }
 6406
 6407    fn gather_revert_changes(
 6408        &mut self,
 6409        selections: &[Selection<Anchor>],
 6410        cx: &mut ViewContext<'_, Editor>,
 6411    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6412        let mut revert_changes = HashMap::default();
 6413        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6414        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6415            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6416        }
 6417        revert_changes
 6418    }
 6419
 6420    pub fn prepare_revert_change(
 6421        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6422        multi_buffer: &Model<MultiBuffer>,
 6423        hunk: &MultiBufferDiffHunk,
 6424        cx: &AppContext,
 6425    ) -> Option<()> {
 6426        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6427        let buffer = buffer.read(cx);
 6428        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6429        let buffer_snapshot = buffer.snapshot();
 6430        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6431        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6432            probe
 6433                .0
 6434                .start
 6435                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6436                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6437        }) {
 6438            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6439            Some(())
 6440        } else {
 6441            None
 6442        }
 6443    }
 6444
 6445    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6446        self.manipulate_lines(cx, |lines| lines.reverse())
 6447    }
 6448
 6449    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6450        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6451    }
 6452
 6453    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6454    where
 6455        Fn: FnMut(&mut Vec<&str>),
 6456    {
 6457        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6458        let buffer = self.buffer.read(cx).snapshot(cx);
 6459
 6460        let mut edits = Vec::new();
 6461
 6462        let selections = self.selections.all::<Point>(cx);
 6463        let mut selections = selections.iter().peekable();
 6464        let mut contiguous_row_selections = Vec::new();
 6465        let mut new_selections = Vec::new();
 6466        let mut added_lines = 0;
 6467        let mut removed_lines = 0;
 6468
 6469        while let Some(selection) = selections.next() {
 6470            let (start_row, end_row) = consume_contiguous_rows(
 6471                &mut contiguous_row_selections,
 6472                selection,
 6473                &display_map,
 6474                &mut selections,
 6475            );
 6476
 6477            let start_point = Point::new(start_row.0, 0);
 6478            let end_point = Point::new(
 6479                end_row.previous_row().0,
 6480                buffer.line_len(end_row.previous_row()),
 6481            );
 6482            let text = buffer
 6483                .text_for_range(start_point..end_point)
 6484                .collect::<String>();
 6485
 6486            let mut lines = text.split('\n').collect_vec();
 6487
 6488            let lines_before = lines.len();
 6489            callback(&mut lines);
 6490            let lines_after = lines.len();
 6491
 6492            edits.push((start_point..end_point, lines.join("\n")));
 6493
 6494            // Selections must change based on added and removed line count
 6495            let start_row =
 6496                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6497            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6498            new_selections.push(Selection {
 6499                id: selection.id,
 6500                start: start_row,
 6501                end: end_row,
 6502                goal: SelectionGoal::None,
 6503                reversed: selection.reversed,
 6504            });
 6505
 6506            if lines_after > lines_before {
 6507                added_lines += lines_after - lines_before;
 6508            } else if lines_before > lines_after {
 6509                removed_lines += lines_before - lines_after;
 6510            }
 6511        }
 6512
 6513        self.transact(cx, |this, cx| {
 6514            let buffer = this.buffer.update(cx, |buffer, cx| {
 6515                buffer.edit(edits, None, cx);
 6516                buffer.snapshot(cx)
 6517            });
 6518
 6519            // Recalculate offsets on newly edited buffer
 6520            let new_selections = new_selections
 6521                .iter()
 6522                .map(|s| {
 6523                    let start_point = Point::new(s.start.0, 0);
 6524                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6525                    Selection {
 6526                        id: s.id,
 6527                        start: buffer.point_to_offset(start_point),
 6528                        end: buffer.point_to_offset(end_point),
 6529                        goal: s.goal,
 6530                        reversed: s.reversed,
 6531                    }
 6532                })
 6533                .collect();
 6534
 6535            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6536                s.select(new_selections);
 6537            });
 6538
 6539            this.request_autoscroll(Autoscroll::fit(), cx);
 6540        });
 6541    }
 6542
 6543    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6544        self.manipulate_text(cx, |text| text.to_uppercase())
 6545    }
 6546
 6547    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6548        self.manipulate_text(cx, |text| text.to_lowercase())
 6549    }
 6550
 6551    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6552        self.manipulate_text(cx, |text| {
 6553            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6554            // https://github.com/rutrum/convert-case/issues/16
 6555            text.split('\n')
 6556                .map(|line| line.to_case(Case::Title))
 6557                .join("\n")
 6558        })
 6559    }
 6560
 6561    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6562        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6563    }
 6564
 6565    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6566        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6567    }
 6568
 6569    pub fn convert_to_upper_camel_case(
 6570        &mut self,
 6571        _: &ConvertToUpperCamelCase,
 6572        cx: &mut ViewContext<Self>,
 6573    ) {
 6574        self.manipulate_text(cx, |text| {
 6575            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6576            // https://github.com/rutrum/convert-case/issues/16
 6577            text.split('\n')
 6578                .map(|line| line.to_case(Case::UpperCamel))
 6579                .join("\n")
 6580        })
 6581    }
 6582
 6583    pub fn convert_to_lower_camel_case(
 6584        &mut self,
 6585        _: &ConvertToLowerCamelCase,
 6586        cx: &mut ViewContext<Self>,
 6587    ) {
 6588        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6589    }
 6590
 6591    pub fn convert_to_opposite_case(
 6592        &mut self,
 6593        _: &ConvertToOppositeCase,
 6594        cx: &mut ViewContext<Self>,
 6595    ) {
 6596        self.manipulate_text(cx, |text| {
 6597            text.chars()
 6598                .fold(String::with_capacity(text.len()), |mut t, c| {
 6599                    if c.is_uppercase() {
 6600                        t.extend(c.to_lowercase());
 6601                    } else {
 6602                        t.extend(c.to_uppercase());
 6603                    }
 6604                    t
 6605                })
 6606        })
 6607    }
 6608
 6609    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6610    where
 6611        Fn: FnMut(&str) -> String,
 6612    {
 6613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6614        let buffer = self.buffer.read(cx).snapshot(cx);
 6615
 6616        let mut new_selections = Vec::new();
 6617        let mut edits = Vec::new();
 6618        let mut selection_adjustment = 0i32;
 6619
 6620        for selection in self.selections.all::<usize>(cx) {
 6621            let selection_is_empty = selection.is_empty();
 6622
 6623            let (start, end) = if selection_is_empty {
 6624                let word_range = movement::surrounding_word(
 6625                    &display_map,
 6626                    selection.start.to_display_point(&display_map),
 6627                );
 6628                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6629                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6630                (start, end)
 6631            } else {
 6632                (selection.start, selection.end)
 6633            };
 6634
 6635            let text = buffer.text_for_range(start..end).collect::<String>();
 6636            let old_length = text.len() as i32;
 6637            let text = callback(&text);
 6638
 6639            new_selections.push(Selection {
 6640                start: (start as i32 - selection_adjustment) as usize,
 6641                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6642                goal: SelectionGoal::None,
 6643                ..selection
 6644            });
 6645
 6646            selection_adjustment += old_length - text.len() as i32;
 6647
 6648            edits.push((start..end, text));
 6649        }
 6650
 6651        self.transact(cx, |this, cx| {
 6652            this.buffer.update(cx, |buffer, cx| {
 6653                buffer.edit(edits, None, cx);
 6654            });
 6655
 6656            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6657                s.select(new_selections);
 6658            });
 6659
 6660            this.request_autoscroll(Autoscroll::fit(), cx);
 6661        });
 6662    }
 6663
 6664    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6665        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6666        let buffer = &display_map.buffer_snapshot;
 6667        let selections = self.selections.all::<Point>(cx);
 6668
 6669        let mut edits = Vec::new();
 6670        let mut selections_iter = selections.iter().peekable();
 6671        while let Some(selection) = selections_iter.next() {
 6672            // Avoid duplicating the same lines twice.
 6673            let mut rows = selection.spanned_rows(false, &display_map);
 6674
 6675            while let Some(next_selection) = selections_iter.peek() {
 6676                let next_rows = next_selection.spanned_rows(false, &display_map);
 6677                if next_rows.start < rows.end {
 6678                    rows.end = next_rows.end;
 6679                    selections_iter.next().unwrap();
 6680                } else {
 6681                    break;
 6682                }
 6683            }
 6684
 6685            // Copy the text from the selected row region and splice it either at the start
 6686            // or end of the region.
 6687            let start = Point::new(rows.start.0, 0);
 6688            let end = Point::new(
 6689                rows.end.previous_row().0,
 6690                buffer.line_len(rows.end.previous_row()),
 6691            );
 6692            let text = buffer
 6693                .text_for_range(start..end)
 6694                .chain(Some("\n"))
 6695                .collect::<String>();
 6696            let insert_location = if upwards {
 6697                Point::new(rows.end.0, 0)
 6698            } else {
 6699                start
 6700            };
 6701            edits.push((insert_location..insert_location, text));
 6702        }
 6703
 6704        self.transact(cx, |this, cx| {
 6705            this.buffer.update(cx, |buffer, cx| {
 6706                buffer.edit(edits, None, cx);
 6707            });
 6708
 6709            this.request_autoscroll(Autoscroll::fit(), cx);
 6710        });
 6711    }
 6712
 6713    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6714        self.duplicate_line(true, cx);
 6715    }
 6716
 6717    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6718        self.duplicate_line(false, cx);
 6719    }
 6720
 6721    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6722        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6723        let buffer = self.buffer.read(cx).snapshot(cx);
 6724
 6725        let mut edits = Vec::new();
 6726        let mut unfold_ranges = Vec::new();
 6727        let mut refold_ranges = Vec::new();
 6728
 6729        let selections = self.selections.all::<Point>(cx);
 6730        let mut selections = selections.iter().peekable();
 6731        let mut contiguous_row_selections = Vec::new();
 6732        let mut new_selections = Vec::new();
 6733
 6734        while let Some(selection) = selections.next() {
 6735            // Find all the selections that span a contiguous row range
 6736            let (start_row, end_row) = consume_contiguous_rows(
 6737                &mut contiguous_row_selections,
 6738                selection,
 6739                &display_map,
 6740                &mut selections,
 6741            );
 6742
 6743            // Move the text spanned by the row range to be before the line preceding the row range
 6744            if start_row.0 > 0 {
 6745                let range_to_move = Point::new(
 6746                    start_row.previous_row().0,
 6747                    buffer.line_len(start_row.previous_row()),
 6748                )
 6749                    ..Point::new(
 6750                        end_row.previous_row().0,
 6751                        buffer.line_len(end_row.previous_row()),
 6752                    );
 6753                let insertion_point = display_map
 6754                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6755                    .0;
 6756
 6757                // Don't move lines across excerpts
 6758                if buffer
 6759                    .excerpt_boundaries_in_range((
 6760                        Bound::Excluded(insertion_point),
 6761                        Bound::Included(range_to_move.end),
 6762                    ))
 6763                    .next()
 6764                    .is_none()
 6765                {
 6766                    let text = buffer
 6767                        .text_for_range(range_to_move.clone())
 6768                        .flat_map(|s| s.chars())
 6769                        .skip(1)
 6770                        .chain(['\n'])
 6771                        .collect::<String>();
 6772
 6773                    edits.push((
 6774                        buffer.anchor_after(range_to_move.start)
 6775                            ..buffer.anchor_before(range_to_move.end),
 6776                        String::new(),
 6777                    ));
 6778                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6779                    edits.push((insertion_anchor..insertion_anchor, text));
 6780
 6781                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6782
 6783                    // Move selections up
 6784                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6785                        |mut selection| {
 6786                            selection.start.row -= row_delta;
 6787                            selection.end.row -= row_delta;
 6788                            selection
 6789                        },
 6790                    ));
 6791
 6792                    // Move folds up
 6793                    unfold_ranges.push(range_to_move.clone());
 6794                    for fold in display_map.folds_in_range(
 6795                        buffer.anchor_before(range_to_move.start)
 6796                            ..buffer.anchor_after(range_to_move.end),
 6797                    ) {
 6798                        let mut start = fold.range.start.to_point(&buffer);
 6799                        let mut end = fold.range.end.to_point(&buffer);
 6800                        start.row -= row_delta;
 6801                        end.row -= row_delta;
 6802                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6803                    }
 6804                }
 6805            }
 6806
 6807            // If we didn't move line(s), preserve the existing selections
 6808            new_selections.append(&mut contiguous_row_selections);
 6809        }
 6810
 6811        self.transact(cx, |this, cx| {
 6812            this.unfold_ranges(unfold_ranges, true, true, cx);
 6813            this.buffer.update(cx, |buffer, cx| {
 6814                for (range, text) in edits {
 6815                    buffer.edit([(range, text)], None, cx);
 6816                }
 6817            });
 6818            this.fold_ranges(refold_ranges, true, cx);
 6819            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6820                s.select(new_selections);
 6821            })
 6822        });
 6823    }
 6824
 6825    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6826        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6827        let buffer = self.buffer.read(cx).snapshot(cx);
 6828
 6829        let mut edits = Vec::new();
 6830        let mut unfold_ranges = Vec::new();
 6831        let mut refold_ranges = Vec::new();
 6832
 6833        let selections = self.selections.all::<Point>(cx);
 6834        let mut selections = selections.iter().peekable();
 6835        let mut contiguous_row_selections = Vec::new();
 6836        let mut new_selections = Vec::new();
 6837
 6838        while let Some(selection) = selections.next() {
 6839            // Find all the selections that span a contiguous row range
 6840            let (start_row, end_row) = consume_contiguous_rows(
 6841                &mut contiguous_row_selections,
 6842                selection,
 6843                &display_map,
 6844                &mut selections,
 6845            );
 6846
 6847            // Move the text spanned by the row range to be after the last line of the row range
 6848            if end_row.0 <= buffer.max_point().row {
 6849                let range_to_move =
 6850                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6851                let insertion_point = display_map
 6852                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6853                    .0;
 6854
 6855                // Don't move lines across excerpt boundaries
 6856                if buffer
 6857                    .excerpt_boundaries_in_range((
 6858                        Bound::Excluded(range_to_move.start),
 6859                        Bound::Included(insertion_point),
 6860                    ))
 6861                    .next()
 6862                    .is_none()
 6863                {
 6864                    let mut text = String::from("\n");
 6865                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6866                    text.pop(); // Drop trailing newline
 6867                    edits.push((
 6868                        buffer.anchor_after(range_to_move.start)
 6869                            ..buffer.anchor_before(range_to_move.end),
 6870                        String::new(),
 6871                    ));
 6872                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6873                    edits.push((insertion_anchor..insertion_anchor, text));
 6874
 6875                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6876
 6877                    // Move selections down
 6878                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6879                        |mut selection| {
 6880                            selection.start.row += row_delta;
 6881                            selection.end.row += row_delta;
 6882                            selection
 6883                        },
 6884                    ));
 6885
 6886                    // Move folds down
 6887                    unfold_ranges.push(range_to_move.clone());
 6888                    for fold in display_map.folds_in_range(
 6889                        buffer.anchor_before(range_to_move.start)
 6890                            ..buffer.anchor_after(range_to_move.end),
 6891                    ) {
 6892                        let mut start = fold.range.start.to_point(&buffer);
 6893                        let mut end = fold.range.end.to_point(&buffer);
 6894                        start.row += row_delta;
 6895                        end.row += row_delta;
 6896                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6897                    }
 6898                }
 6899            }
 6900
 6901            // If we didn't move line(s), preserve the existing selections
 6902            new_selections.append(&mut contiguous_row_selections);
 6903        }
 6904
 6905        self.transact(cx, |this, cx| {
 6906            this.unfold_ranges(unfold_ranges, true, true, cx);
 6907            this.buffer.update(cx, |buffer, cx| {
 6908                for (range, text) in edits {
 6909                    buffer.edit([(range, text)], None, cx);
 6910                }
 6911            });
 6912            this.fold_ranges(refold_ranges, true, cx);
 6913            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6914        });
 6915    }
 6916
 6917    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6918        let text_layout_details = &self.text_layout_details(cx);
 6919        self.transact(cx, |this, cx| {
 6920            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6921                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6922                let line_mode = s.line_mode;
 6923                s.move_with(|display_map, selection| {
 6924                    if !selection.is_empty() || line_mode {
 6925                        return;
 6926                    }
 6927
 6928                    let mut head = selection.head();
 6929                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6930                    if head.column() == display_map.line_len(head.row()) {
 6931                        transpose_offset = display_map
 6932                            .buffer_snapshot
 6933                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6934                    }
 6935
 6936                    if transpose_offset == 0 {
 6937                        return;
 6938                    }
 6939
 6940                    *head.column_mut() += 1;
 6941                    head = display_map.clip_point(head, Bias::Right);
 6942                    let goal = SelectionGoal::HorizontalPosition(
 6943                        display_map
 6944                            .x_for_display_point(head, text_layout_details)
 6945                            .into(),
 6946                    );
 6947                    selection.collapse_to(head, goal);
 6948
 6949                    let transpose_start = display_map
 6950                        .buffer_snapshot
 6951                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6952                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6953                        let transpose_end = display_map
 6954                            .buffer_snapshot
 6955                            .clip_offset(transpose_offset + 1, Bias::Right);
 6956                        if let Some(ch) =
 6957                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6958                        {
 6959                            edits.push((transpose_start..transpose_offset, String::new()));
 6960                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6961                        }
 6962                    }
 6963                });
 6964                edits
 6965            });
 6966            this.buffer
 6967                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6968            let selections = this.selections.all::<usize>(cx);
 6969            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6970                s.select(selections);
 6971            });
 6972        });
 6973    }
 6974
 6975    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6976        self.rewrap_impl(true, cx)
 6977    }
 6978
 6979    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6980        let buffer = self.buffer.read(cx).snapshot(cx);
 6981        let selections = self.selections.all::<Point>(cx);
 6982        let mut selections = selections.iter().peekable();
 6983
 6984        let mut edits = Vec::new();
 6985        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6986
 6987        while let Some(selection) = selections.next() {
 6988            let mut start_row = selection.start.row;
 6989            let mut end_row = selection.end.row;
 6990
 6991            // Skip selections that overlap with a range that has already been rewrapped.
 6992            let selection_range = start_row..end_row;
 6993            if rewrapped_row_ranges
 6994                .iter()
 6995                .any(|range| range.overlaps(&selection_range))
 6996            {
 6997                continue;
 6998            }
 6999
 7000            let mut should_rewrap = !only_text;
 7001
 7002            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7003                match language_scope.language_name().0.as_ref() {
 7004                    "Markdown" | "Plain Text" => {
 7005                        should_rewrap = true;
 7006                    }
 7007                    _ => {}
 7008                }
 7009            }
 7010
 7011            // Since not all lines in the selection may be at the same indent
 7012            // level, choose the indent size that is the most common between all
 7013            // of the lines.
 7014            //
 7015            // If there is a tie, we use the deepest indent.
 7016            let (indent_size, indent_end) = {
 7017                let mut indent_size_occurrences = HashMap::default();
 7018                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7019
 7020                for row in start_row..=end_row {
 7021                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7022                    rows_by_indent_size.entry(indent).or_default().push(row);
 7023                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7024                }
 7025
 7026                let indent_size = indent_size_occurrences
 7027                    .into_iter()
 7028                    .max_by_key(|(indent, count)| (*count, indent.len))
 7029                    .map(|(indent, _)| indent)
 7030                    .unwrap_or_default();
 7031                let row = rows_by_indent_size[&indent_size][0];
 7032                let indent_end = Point::new(row, indent_size.len);
 7033
 7034                (indent_size, indent_end)
 7035            };
 7036
 7037            let mut line_prefix = indent_size.chars().collect::<String>();
 7038
 7039            if let Some(comment_prefix) =
 7040                buffer
 7041                    .language_scope_at(selection.head())
 7042                    .and_then(|language| {
 7043                        language
 7044                            .line_comment_prefixes()
 7045                            .iter()
 7046                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7047                            .cloned()
 7048                    })
 7049            {
 7050                line_prefix.push_str(&comment_prefix);
 7051                should_rewrap = true;
 7052            }
 7053
 7054            if selection.is_empty() {
 7055                'expand_upwards: while start_row > 0 {
 7056                    let prev_row = start_row - 1;
 7057                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7058                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7059                    {
 7060                        start_row = prev_row;
 7061                    } else {
 7062                        break 'expand_upwards;
 7063                    }
 7064                }
 7065
 7066                'expand_downwards: while end_row < buffer.max_point().row {
 7067                    let next_row = end_row + 1;
 7068                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7069                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7070                    {
 7071                        end_row = next_row;
 7072                    } else {
 7073                        break 'expand_downwards;
 7074                    }
 7075                }
 7076            }
 7077
 7078            if !should_rewrap {
 7079                continue;
 7080            }
 7081
 7082            let start = Point::new(start_row, 0);
 7083            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7084            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7085            let Some(lines_without_prefixes) = selection_text
 7086                .lines()
 7087                .map(|line| {
 7088                    line.strip_prefix(&line_prefix)
 7089                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7090                        .ok_or_else(|| {
 7091                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7092                        })
 7093                })
 7094                .collect::<Result<Vec<_>, _>>()
 7095                .log_err()
 7096            else {
 7097                continue;
 7098            };
 7099
 7100            let unwrapped_text = lines_without_prefixes.join(" ");
 7101            let wrap_column = buffer
 7102                .settings_at(Point::new(start_row, 0), cx)
 7103                .preferred_line_length as usize;
 7104            let mut wrapped_text = String::new();
 7105            let mut current_line = line_prefix.clone();
 7106            for word in unwrapped_text.split_whitespace() {
 7107                if current_line.len() + word.len() >= wrap_column {
 7108                    wrapped_text.push_str(&current_line);
 7109                    wrapped_text.push('\n');
 7110                    current_line.truncate(line_prefix.len());
 7111                }
 7112
 7113                if current_line.len() > line_prefix.len() {
 7114                    current_line.push(' ');
 7115                }
 7116
 7117                current_line.push_str(word);
 7118            }
 7119
 7120            if !current_line.is_empty() {
 7121                wrapped_text.push_str(&current_line);
 7122            }
 7123
 7124            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7125            let mut offset = start.to_offset(&buffer);
 7126            let mut moved_since_edit = true;
 7127
 7128            for change in diff.iter_all_changes() {
 7129                let value = change.value();
 7130                match change.tag() {
 7131                    ChangeTag::Equal => {
 7132                        offset += value.len();
 7133                        moved_since_edit = true;
 7134                    }
 7135                    ChangeTag::Delete => {
 7136                        let start = buffer.anchor_after(offset);
 7137                        let end = buffer.anchor_before(offset + value.len());
 7138
 7139                        if moved_since_edit {
 7140                            edits.push((start..end, String::new()));
 7141                        } else {
 7142                            edits.last_mut().unwrap().0.end = end;
 7143                        }
 7144
 7145                        offset += value.len();
 7146                        moved_since_edit = false;
 7147                    }
 7148                    ChangeTag::Insert => {
 7149                        if moved_since_edit {
 7150                            let anchor = buffer.anchor_after(offset);
 7151                            edits.push((anchor..anchor, value.to_string()));
 7152                        } else {
 7153                            edits.last_mut().unwrap().1.push_str(value);
 7154                        }
 7155
 7156                        moved_since_edit = false;
 7157                    }
 7158                }
 7159            }
 7160
 7161            rewrapped_row_ranges.push(start_row..=end_row);
 7162        }
 7163
 7164        self.buffer
 7165            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7166    }
 7167
 7168    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7169        let mut text = String::new();
 7170        let buffer = self.buffer.read(cx).snapshot(cx);
 7171        let mut selections = self.selections.all::<Point>(cx);
 7172        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7173        {
 7174            let max_point = buffer.max_point();
 7175            let mut is_first = true;
 7176            for selection in &mut selections {
 7177                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7178                if is_entire_line {
 7179                    selection.start = Point::new(selection.start.row, 0);
 7180                    if !selection.is_empty() && selection.end.column == 0 {
 7181                        selection.end = cmp::min(max_point, selection.end);
 7182                    } else {
 7183                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7184                    }
 7185                    selection.goal = SelectionGoal::None;
 7186                }
 7187                if is_first {
 7188                    is_first = false;
 7189                } else {
 7190                    text += "\n";
 7191                }
 7192                let mut len = 0;
 7193                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7194                    text.push_str(chunk);
 7195                    len += chunk.len();
 7196                }
 7197                clipboard_selections.push(ClipboardSelection {
 7198                    len,
 7199                    is_entire_line,
 7200                    first_line_indent: buffer
 7201                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7202                        .len,
 7203                });
 7204            }
 7205        }
 7206
 7207        self.transact(cx, |this, cx| {
 7208            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7209                s.select(selections);
 7210            });
 7211            this.insert("", cx);
 7212            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7213                text,
 7214                clipboard_selections,
 7215            ));
 7216        });
 7217    }
 7218
 7219    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7220        let selections = self.selections.all::<Point>(cx);
 7221        let buffer = self.buffer.read(cx).read(cx);
 7222        let mut text = String::new();
 7223
 7224        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7225        {
 7226            let max_point = buffer.max_point();
 7227            let mut is_first = true;
 7228            for selection in selections.iter() {
 7229                let mut start = selection.start;
 7230                let mut end = selection.end;
 7231                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7232                if is_entire_line {
 7233                    start = Point::new(start.row, 0);
 7234                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7235                }
 7236                if is_first {
 7237                    is_first = false;
 7238                } else {
 7239                    text += "\n";
 7240                }
 7241                let mut len = 0;
 7242                for chunk in buffer.text_for_range(start..end) {
 7243                    text.push_str(chunk);
 7244                    len += chunk.len();
 7245                }
 7246                clipboard_selections.push(ClipboardSelection {
 7247                    len,
 7248                    is_entire_line,
 7249                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7250                });
 7251            }
 7252        }
 7253
 7254        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7255            text,
 7256            clipboard_selections,
 7257        ));
 7258    }
 7259
 7260    pub fn do_paste(
 7261        &mut self,
 7262        text: &String,
 7263        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7264        handle_entire_lines: bool,
 7265        cx: &mut ViewContext<Self>,
 7266    ) {
 7267        if self.read_only(cx) {
 7268            return;
 7269        }
 7270
 7271        let clipboard_text = Cow::Borrowed(text);
 7272
 7273        self.transact(cx, |this, cx| {
 7274            if let Some(mut clipboard_selections) = clipboard_selections {
 7275                let old_selections = this.selections.all::<usize>(cx);
 7276                let all_selections_were_entire_line =
 7277                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7278                let first_selection_indent_column =
 7279                    clipboard_selections.first().map(|s| s.first_line_indent);
 7280                if clipboard_selections.len() != old_selections.len() {
 7281                    clipboard_selections.drain(..);
 7282                }
 7283
 7284                this.buffer.update(cx, |buffer, cx| {
 7285                    let snapshot = buffer.read(cx);
 7286                    let mut start_offset = 0;
 7287                    let mut edits = Vec::new();
 7288                    let mut original_indent_columns = Vec::new();
 7289                    for (ix, selection) in old_selections.iter().enumerate() {
 7290                        let to_insert;
 7291                        let entire_line;
 7292                        let original_indent_column;
 7293                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7294                            let end_offset = start_offset + clipboard_selection.len;
 7295                            to_insert = &clipboard_text[start_offset..end_offset];
 7296                            entire_line = clipboard_selection.is_entire_line;
 7297                            start_offset = end_offset + 1;
 7298                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7299                        } else {
 7300                            to_insert = clipboard_text.as_str();
 7301                            entire_line = all_selections_were_entire_line;
 7302                            original_indent_column = first_selection_indent_column
 7303                        }
 7304
 7305                        // If the corresponding selection was empty when this slice of the
 7306                        // clipboard text was written, then the entire line containing the
 7307                        // selection was copied. If this selection is also currently empty,
 7308                        // then paste the line before the current line of the buffer.
 7309                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7310                            let column = selection.start.to_point(&snapshot).column as usize;
 7311                            let line_start = selection.start - column;
 7312                            line_start..line_start
 7313                        } else {
 7314                            selection.range()
 7315                        };
 7316
 7317                        edits.push((range, to_insert));
 7318                        original_indent_columns.extend(original_indent_column);
 7319                    }
 7320                    drop(snapshot);
 7321
 7322                    buffer.edit(
 7323                        edits,
 7324                        Some(AutoindentMode::Block {
 7325                            original_indent_columns,
 7326                        }),
 7327                        cx,
 7328                    );
 7329                });
 7330
 7331                let selections = this.selections.all::<usize>(cx);
 7332                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7333            } else {
 7334                this.insert(&clipboard_text, cx);
 7335            }
 7336        });
 7337    }
 7338
 7339    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7340        if let Some(item) = cx.read_from_clipboard() {
 7341            let entries = item.entries();
 7342
 7343            match entries.first() {
 7344                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7345                // of all the pasted entries.
 7346                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7347                    .do_paste(
 7348                        clipboard_string.text(),
 7349                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7350                        true,
 7351                        cx,
 7352                    ),
 7353                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7354            }
 7355        }
 7356    }
 7357
 7358    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7359        if self.read_only(cx) {
 7360            return;
 7361        }
 7362
 7363        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7364            if let Some((selections, _)) =
 7365                self.selection_history.transaction(transaction_id).cloned()
 7366            {
 7367                self.change_selections(None, cx, |s| {
 7368                    s.select_anchors(selections.to_vec());
 7369                });
 7370            }
 7371            self.request_autoscroll(Autoscroll::fit(), cx);
 7372            self.unmark_text(cx);
 7373            self.refresh_inline_completion(true, false, cx);
 7374            cx.emit(EditorEvent::Edited { transaction_id });
 7375            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7376        }
 7377    }
 7378
 7379    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7380        if self.read_only(cx) {
 7381            return;
 7382        }
 7383
 7384        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7385            if let Some((_, Some(selections))) =
 7386                self.selection_history.transaction(transaction_id).cloned()
 7387            {
 7388                self.change_selections(None, cx, |s| {
 7389                    s.select_anchors(selections.to_vec());
 7390                });
 7391            }
 7392            self.request_autoscroll(Autoscroll::fit(), cx);
 7393            self.unmark_text(cx);
 7394            self.refresh_inline_completion(true, false, cx);
 7395            cx.emit(EditorEvent::Edited { transaction_id });
 7396        }
 7397    }
 7398
 7399    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7400        self.buffer
 7401            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7402    }
 7403
 7404    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7405        self.buffer
 7406            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7407    }
 7408
 7409    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7410        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7411            let line_mode = s.line_mode;
 7412            s.move_with(|map, selection| {
 7413                let cursor = if selection.is_empty() && !line_mode {
 7414                    movement::left(map, selection.start)
 7415                } else {
 7416                    selection.start
 7417                };
 7418                selection.collapse_to(cursor, SelectionGoal::None);
 7419            });
 7420        })
 7421    }
 7422
 7423    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7424        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7425            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7426        })
 7427    }
 7428
 7429    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7430        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7431            let line_mode = s.line_mode;
 7432            s.move_with(|map, selection| {
 7433                let cursor = if selection.is_empty() && !line_mode {
 7434                    movement::right(map, selection.end)
 7435                } else {
 7436                    selection.end
 7437                };
 7438                selection.collapse_to(cursor, SelectionGoal::None)
 7439            });
 7440        })
 7441    }
 7442
 7443    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7444        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7445            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7446        })
 7447    }
 7448
 7449    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7450        if self.take_rename(true, cx).is_some() {
 7451            return;
 7452        }
 7453
 7454        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7455            cx.propagate();
 7456            return;
 7457        }
 7458
 7459        let text_layout_details = &self.text_layout_details(cx);
 7460        let selection_count = self.selections.count();
 7461        let first_selection = self.selections.first_anchor();
 7462
 7463        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7464            let line_mode = s.line_mode;
 7465            s.move_with(|map, selection| {
 7466                if !selection.is_empty() && !line_mode {
 7467                    selection.goal = SelectionGoal::None;
 7468                }
 7469                let (cursor, goal) = movement::up(
 7470                    map,
 7471                    selection.start,
 7472                    selection.goal,
 7473                    false,
 7474                    text_layout_details,
 7475                );
 7476                selection.collapse_to(cursor, goal);
 7477            });
 7478        });
 7479
 7480        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7481        {
 7482            cx.propagate();
 7483        }
 7484    }
 7485
 7486    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7487        if self.take_rename(true, cx).is_some() {
 7488            return;
 7489        }
 7490
 7491        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7492            cx.propagate();
 7493            return;
 7494        }
 7495
 7496        let text_layout_details = &self.text_layout_details(cx);
 7497
 7498        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7499            let line_mode = s.line_mode;
 7500            s.move_with(|map, selection| {
 7501                if !selection.is_empty() && !line_mode {
 7502                    selection.goal = SelectionGoal::None;
 7503                }
 7504                let (cursor, goal) = movement::up_by_rows(
 7505                    map,
 7506                    selection.start,
 7507                    action.lines,
 7508                    selection.goal,
 7509                    false,
 7510                    text_layout_details,
 7511                );
 7512                selection.collapse_to(cursor, goal);
 7513            });
 7514        })
 7515    }
 7516
 7517    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7518        if self.take_rename(true, cx).is_some() {
 7519            return;
 7520        }
 7521
 7522        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7523            cx.propagate();
 7524            return;
 7525        }
 7526
 7527        let text_layout_details = &self.text_layout_details(cx);
 7528
 7529        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7530            let line_mode = s.line_mode;
 7531            s.move_with(|map, selection| {
 7532                if !selection.is_empty() && !line_mode {
 7533                    selection.goal = SelectionGoal::None;
 7534                }
 7535                let (cursor, goal) = movement::down_by_rows(
 7536                    map,
 7537                    selection.start,
 7538                    action.lines,
 7539                    selection.goal,
 7540                    false,
 7541                    text_layout_details,
 7542                );
 7543                selection.collapse_to(cursor, goal);
 7544            });
 7545        })
 7546    }
 7547
 7548    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7549        let text_layout_details = &self.text_layout_details(cx);
 7550        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7551            s.move_heads_with(|map, head, goal| {
 7552                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7553            })
 7554        })
 7555    }
 7556
 7557    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7558        let text_layout_details = &self.text_layout_details(cx);
 7559        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7560            s.move_heads_with(|map, head, goal| {
 7561                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7562            })
 7563        })
 7564    }
 7565
 7566    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7567        let Some(row_count) = self.visible_row_count() else {
 7568            return;
 7569        };
 7570
 7571        let text_layout_details = &self.text_layout_details(cx);
 7572
 7573        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7574            s.move_heads_with(|map, head, goal| {
 7575                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7576            })
 7577        })
 7578    }
 7579
 7580    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7581        if self.take_rename(true, cx).is_some() {
 7582            return;
 7583        }
 7584
 7585        if self
 7586            .context_menu
 7587            .write()
 7588            .as_mut()
 7589            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7590            .unwrap_or(false)
 7591        {
 7592            return;
 7593        }
 7594
 7595        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7596            cx.propagate();
 7597            return;
 7598        }
 7599
 7600        let Some(row_count) = self.visible_row_count() else {
 7601            return;
 7602        };
 7603
 7604        let autoscroll = if action.center_cursor {
 7605            Autoscroll::center()
 7606        } else {
 7607            Autoscroll::fit()
 7608        };
 7609
 7610        let text_layout_details = &self.text_layout_details(cx);
 7611
 7612        self.change_selections(Some(autoscroll), cx, |s| {
 7613            let line_mode = s.line_mode;
 7614            s.move_with(|map, selection| {
 7615                if !selection.is_empty() && !line_mode {
 7616                    selection.goal = SelectionGoal::None;
 7617                }
 7618                let (cursor, goal) = movement::up_by_rows(
 7619                    map,
 7620                    selection.end,
 7621                    row_count,
 7622                    selection.goal,
 7623                    false,
 7624                    text_layout_details,
 7625                );
 7626                selection.collapse_to(cursor, goal);
 7627            });
 7628        });
 7629    }
 7630
 7631    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7632        let text_layout_details = &self.text_layout_details(cx);
 7633        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7634            s.move_heads_with(|map, head, goal| {
 7635                movement::up(map, head, goal, false, text_layout_details)
 7636            })
 7637        })
 7638    }
 7639
 7640    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7641        self.take_rename(true, cx);
 7642
 7643        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7644            cx.propagate();
 7645            return;
 7646        }
 7647
 7648        let text_layout_details = &self.text_layout_details(cx);
 7649        let selection_count = self.selections.count();
 7650        let first_selection = self.selections.first_anchor();
 7651
 7652        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7653            let line_mode = s.line_mode;
 7654            s.move_with(|map, selection| {
 7655                if !selection.is_empty() && !line_mode {
 7656                    selection.goal = SelectionGoal::None;
 7657                }
 7658                let (cursor, goal) = movement::down(
 7659                    map,
 7660                    selection.end,
 7661                    selection.goal,
 7662                    false,
 7663                    text_layout_details,
 7664                );
 7665                selection.collapse_to(cursor, goal);
 7666            });
 7667        });
 7668
 7669        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7670        {
 7671            cx.propagate();
 7672        }
 7673    }
 7674
 7675    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7676        let Some(row_count) = self.visible_row_count() else {
 7677            return;
 7678        };
 7679
 7680        let text_layout_details = &self.text_layout_details(cx);
 7681
 7682        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7683            s.move_heads_with(|map, head, goal| {
 7684                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7685            })
 7686        })
 7687    }
 7688
 7689    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7690        if self.take_rename(true, cx).is_some() {
 7691            return;
 7692        }
 7693
 7694        if self
 7695            .context_menu
 7696            .write()
 7697            .as_mut()
 7698            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7699            .unwrap_or(false)
 7700        {
 7701            return;
 7702        }
 7703
 7704        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7705            cx.propagate();
 7706            return;
 7707        }
 7708
 7709        let Some(row_count) = self.visible_row_count() else {
 7710            return;
 7711        };
 7712
 7713        let autoscroll = if action.center_cursor {
 7714            Autoscroll::center()
 7715        } else {
 7716            Autoscroll::fit()
 7717        };
 7718
 7719        let text_layout_details = &self.text_layout_details(cx);
 7720        self.change_selections(Some(autoscroll), cx, |s| {
 7721            let line_mode = s.line_mode;
 7722            s.move_with(|map, selection| {
 7723                if !selection.is_empty() && !line_mode {
 7724                    selection.goal = SelectionGoal::None;
 7725                }
 7726                let (cursor, goal) = movement::down_by_rows(
 7727                    map,
 7728                    selection.end,
 7729                    row_count,
 7730                    selection.goal,
 7731                    false,
 7732                    text_layout_details,
 7733                );
 7734                selection.collapse_to(cursor, goal);
 7735            });
 7736        });
 7737    }
 7738
 7739    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7740        let text_layout_details = &self.text_layout_details(cx);
 7741        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7742            s.move_heads_with(|map, head, goal| {
 7743                movement::down(map, head, goal, false, text_layout_details)
 7744            })
 7745        });
 7746    }
 7747
 7748    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7749        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7750            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7751        }
 7752    }
 7753
 7754    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7755        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7756            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7757        }
 7758    }
 7759
 7760    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7761        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7762            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7763        }
 7764    }
 7765
 7766    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7767        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7768            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7769        }
 7770    }
 7771
 7772    pub fn move_to_previous_word_start(
 7773        &mut self,
 7774        _: &MoveToPreviousWordStart,
 7775        cx: &mut ViewContext<Self>,
 7776    ) {
 7777        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7778            s.move_cursors_with(|map, head, _| {
 7779                (
 7780                    movement::previous_word_start(map, head),
 7781                    SelectionGoal::None,
 7782                )
 7783            });
 7784        })
 7785    }
 7786
 7787    pub fn move_to_previous_subword_start(
 7788        &mut self,
 7789        _: &MoveToPreviousSubwordStart,
 7790        cx: &mut ViewContext<Self>,
 7791    ) {
 7792        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7793            s.move_cursors_with(|map, head, _| {
 7794                (
 7795                    movement::previous_subword_start(map, head),
 7796                    SelectionGoal::None,
 7797                )
 7798            });
 7799        })
 7800    }
 7801
 7802    pub fn select_to_previous_word_start(
 7803        &mut self,
 7804        _: &SelectToPreviousWordStart,
 7805        cx: &mut ViewContext<Self>,
 7806    ) {
 7807        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7808            s.move_heads_with(|map, head, _| {
 7809                (
 7810                    movement::previous_word_start(map, head),
 7811                    SelectionGoal::None,
 7812                )
 7813            });
 7814        })
 7815    }
 7816
 7817    pub fn select_to_previous_subword_start(
 7818        &mut self,
 7819        _: &SelectToPreviousSubwordStart,
 7820        cx: &mut ViewContext<Self>,
 7821    ) {
 7822        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7823            s.move_heads_with(|map, head, _| {
 7824                (
 7825                    movement::previous_subword_start(map, head),
 7826                    SelectionGoal::None,
 7827                )
 7828            });
 7829        })
 7830    }
 7831
 7832    pub fn delete_to_previous_word_start(
 7833        &mut self,
 7834        action: &DeleteToPreviousWordStart,
 7835        cx: &mut ViewContext<Self>,
 7836    ) {
 7837        self.transact(cx, |this, cx| {
 7838            this.select_autoclose_pair(cx);
 7839            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7840                let line_mode = s.line_mode;
 7841                s.move_with(|map, selection| {
 7842                    if selection.is_empty() && !line_mode {
 7843                        let cursor = if action.ignore_newlines {
 7844                            movement::previous_word_start(map, selection.head())
 7845                        } else {
 7846                            movement::previous_word_start_or_newline(map, selection.head())
 7847                        };
 7848                        selection.set_head(cursor, SelectionGoal::None);
 7849                    }
 7850                });
 7851            });
 7852            this.insert("", cx);
 7853        });
 7854    }
 7855
 7856    pub fn delete_to_previous_subword_start(
 7857        &mut self,
 7858        _: &DeleteToPreviousSubwordStart,
 7859        cx: &mut ViewContext<Self>,
 7860    ) {
 7861        self.transact(cx, |this, cx| {
 7862            this.select_autoclose_pair(cx);
 7863            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7864                let line_mode = s.line_mode;
 7865                s.move_with(|map, selection| {
 7866                    if selection.is_empty() && !line_mode {
 7867                        let cursor = movement::previous_subword_start(map, selection.head());
 7868                        selection.set_head(cursor, SelectionGoal::None);
 7869                    }
 7870                });
 7871            });
 7872            this.insert("", cx);
 7873        });
 7874    }
 7875
 7876    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7877        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7878            s.move_cursors_with(|map, head, _| {
 7879                (movement::next_word_end(map, head), SelectionGoal::None)
 7880            });
 7881        })
 7882    }
 7883
 7884    pub fn move_to_next_subword_end(
 7885        &mut self,
 7886        _: &MoveToNextSubwordEnd,
 7887        cx: &mut ViewContext<Self>,
 7888    ) {
 7889        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7890            s.move_cursors_with(|map, head, _| {
 7891                (movement::next_subword_end(map, head), SelectionGoal::None)
 7892            });
 7893        })
 7894    }
 7895
 7896    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7897        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7898            s.move_heads_with(|map, head, _| {
 7899                (movement::next_word_end(map, head), SelectionGoal::None)
 7900            });
 7901        })
 7902    }
 7903
 7904    pub fn select_to_next_subword_end(
 7905        &mut self,
 7906        _: &SelectToNextSubwordEnd,
 7907        cx: &mut ViewContext<Self>,
 7908    ) {
 7909        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7910            s.move_heads_with(|map, head, _| {
 7911                (movement::next_subword_end(map, head), SelectionGoal::None)
 7912            });
 7913        })
 7914    }
 7915
 7916    pub fn delete_to_next_word_end(
 7917        &mut self,
 7918        action: &DeleteToNextWordEnd,
 7919        cx: &mut ViewContext<Self>,
 7920    ) {
 7921        self.transact(cx, |this, cx| {
 7922            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7923                let line_mode = s.line_mode;
 7924                s.move_with(|map, selection| {
 7925                    if selection.is_empty() && !line_mode {
 7926                        let cursor = if action.ignore_newlines {
 7927                            movement::next_word_end(map, selection.head())
 7928                        } else {
 7929                            movement::next_word_end_or_newline(map, selection.head())
 7930                        };
 7931                        selection.set_head(cursor, SelectionGoal::None);
 7932                    }
 7933                });
 7934            });
 7935            this.insert("", cx);
 7936        });
 7937    }
 7938
 7939    pub fn delete_to_next_subword_end(
 7940        &mut self,
 7941        _: &DeleteToNextSubwordEnd,
 7942        cx: &mut ViewContext<Self>,
 7943    ) {
 7944        self.transact(cx, |this, cx| {
 7945            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7946                s.move_with(|map, selection| {
 7947                    if selection.is_empty() {
 7948                        let cursor = movement::next_subword_end(map, selection.head());
 7949                        selection.set_head(cursor, SelectionGoal::None);
 7950                    }
 7951                });
 7952            });
 7953            this.insert("", cx);
 7954        });
 7955    }
 7956
 7957    pub fn move_to_beginning_of_line(
 7958        &mut self,
 7959        action: &MoveToBeginningOfLine,
 7960        cx: &mut ViewContext<Self>,
 7961    ) {
 7962        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7963            s.move_cursors_with(|map, head, _| {
 7964                (
 7965                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7966                    SelectionGoal::None,
 7967                )
 7968            });
 7969        })
 7970    }
 7971
 7972    pub fn select_to_beginning_of_line(
 7973        &mut self,
 7974        action: &SelectToBeginningOfLine,
 7975        cx: &mut ViewContext<Self>,
 7976    ) {
 7977        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7978            s.move_heads_with(|map, head, _| {
 7979                (
 7980                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7981                    SelectionGoal::None,
 7982                )
 7983            });
 7984        });
 7985    }
 7986
 7987    pub fn delete_to_beginning_of_line(
 7988        &mut self,
 7989        _: &DeleteToBeginningOfLine,
 7990        cx: &mut ViewContext<Self>,
 7991    ) {
 7992        self.transact(cx, |this, cx| {
 7993            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7994                s.move_with(|_, selection| {
 7995                    selection.reversed = true;
 7996                });
 7997            });
 7998
 7999            this.select_to_beginning_of_line(
 8000                &SelectToBeginningOfLine {
 8001                    stop_at_soft_wraps: false,
 8002                },
 8003                cx,
 8004            );
 8005            this.backspace(&Backspace, cx);
 8006        });
 8007    }
 8008
 8009    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8010        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8011            s.move_cursors_with(|map, head, _| {
 8012                (
 8013                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8014                    SelectionGoal::None,
 8015                )
 8016            });
 8017        })
 8018    }
 8019
 8020    pub fn select_to_end_of_line(
 8021        &mut self,
 8022        action: &SelectToEndOfLine,
 8023        cx: &mut ViewContext<Self>,
 8024    ) {
 8025        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8026            s.move_heads_with(|map, head, _| {
 8027                (
 8028                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8029                    SelectionGoal::None,
 8030                )
 8031            });
 8032        })
 8033    }
 8034
 8035    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8036        self.transact(cx, |this, cx| {
 8037            this.select_to_end_of_line(
 8038                &SelectToEndOfLine {
 8039                    stop_at_soft_wraps: false,
 8040                },
 8041                cx,
 8042            );
 8043            this.delete(&Delete, cx);
 8044        });
 8045    }
 8046
 8047    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8048        self.transact(cx, |this, cx| {
 8049            this.select_to_end_of_line(
 8050                &SelectToEndOfLine {
 8051                    stop_at_soft_wraps: false,
 8052                },
 8053                cx,
 8054            );
 8055            this.cut(&Cut, cx);
 8056        });
 8057    }
 8058
 8059    pub fn move_to_start_of_paragraph(
 8060        &mut self,
 8061        _: &MoveToStartOfParagraph,
 8062        cx: &mut ViewContext<Self>,
 8063    ) {
 8064        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8065            cx.propagate();
 8066            return;
 8067        }
 8068
 8069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8070            s.move_with(|map, selection| {
 8071                selection.collapse_to(
 8072                    movement::start_of_paragraph(map, selection.head(), 1),
 8073                    SelectionGoal::None,
 8074                )
 8075            });
 8076        })
 8077    }
 8078
 8079    pub fn move_to_end_of_paragraph(
 8080        &mut self,
 8081        _: &MoveToEndOfParagraph,
 8082        cx: &mut ViewContext<Self>,
 8083    ) {
 8084        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8085            cx.propagate();
 8086            return;
 8087        }
 8088
 8089        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8090            s.move_with(|map, selection| {
 8091                selection.collapse_to(
 8092                    movement::end_of_paragraph(map, selection.head(), 1),
 8093                    SelectionGoal::None,
 8094                )
 8095            });
 8096        })
 8097    }
 8098
 8099    pub fn select_to_start_of_paragraph(
 8100        &mut self,
 8101        _: &SelectToStartOfParagraph,
 8102        cx: &mut ViewContext<Self>,
 8103    ) {
 8104        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8105            cx.propagate();
 8106            return;
 8107        }
 8108
 8109        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8110            s.move_heads_with(|map, head, _| {
 8111                (
 8112                    movement::start_of_paragraph(map, head, 1),
 8113                    SelectionGoal::None,
 8114                )
 8115            });
 8116        })
 8117    }
 8118
 8119    pub fn select_to_end_of_paragraph(
 8120        &mut self,
 8121        _: &SelectToEndOfParagraph,
 8122        cx: &mut ViewContext<Self>,
 8123    ) {
 8124        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8125            cx.propagate();
 8126            return;
 8127        }
 8128
 8129        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8130            s.move_heads_with(|map, head, _| {
 8131                (
 8132                    movement::end_of_paragraph(map, head, 1),
 8133                    SelectionGoal::None,
 8134                )
 8135            });
 8136        })
 8137    }
 8138
 8139    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8140        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8141            cx.propagate();
 8142            return;
 8143        }
 8144
 8145        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8146            s.select_ranges(vec![0..0]);
 8147        });
 8148    }
 8149
 8150    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8151        let mut selection = self.selections.last::<Point>(cx);
 8152        selection.set_head(Point::zero(), SelectionGoal::None);
 8153
 8154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8155            s.select(vec![selection]);
 8156        });
 8157    }
 8158
 8159    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8160        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8161            cx.propagate();
 8162            return;
 8163        }
 8164
 8165        let cursor = self.buffer.read(cx).read(cx).len();
 8166        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8167            s.select_ranges(vec![cursor..cursor])
 8168        });
 8169    }
 8170
 8171    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8172        self.nav_history = nav_history;
 8173    }
 8174
 8175    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8176        self.nav_history.as_ref()
 8177    }
 8178
 8179    fn push_to_nav_history(
 8180        &mut self,
 8181        cursor_anchor: Anchor,
 8182        new_position: Option<Point>,
 8183        cx: &mut ViewContext<Self>,
 8184    ) {
 8185        if let Some(nav_history) = self.nav_history.as_mut() {
 8186            let buffer = self.buffer.read(cx).read(cx);
 8187            let cursor_position = cursor_anchor.to_point(&buffer);
 8188            let scroll_state = self.scroll_manager.anchor();
 8189            let scroll_top_row = scroll_state.top_row(&buffer);
 8190            drop(buffer);
 8191
 8192            if let Some(new_position) = new_position {
 8193                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8194                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8195                    return;
 8196                }
 8197            }
 8198
 8199            nav_history.push(
 8200                Some(NavigationData {
 8201                    cursor_anchor,
 8202                    cursor_position,
 8203                    scroll_anchor: scroll_state,
 8204                    scroll_top_row,
 8205                }),
 8206                cx,
 8207            );
 8208        }
 8209    }
 8210
 8211    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8212        let buffer = self.buffer.read(cx).snapshot(cx);
 8213        let mut selection = self.selections.first::<usize>(cx);
 8214        selection.set_head(buffer.len(), SelectionGoal::None);
 8215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8216            s.select(vec![selection]);
 8217        });
 8218    }
 8219
 8220    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8221        let end = self.buffer.read(cx).read(cx).len();
 8222        self.change_selections(None, cx, |s| {
 8223            s.select_ranges(vec![0..end]);
 8224        });
 8225    }
 8226
 8227    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8228        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8229        let mut selections = self.selections.all::<Point>(cx);
 8230        let max_point = display_map.buffer_snapshot.max_point();
 8231        for selection in &mut selections {
 8232            let rows = selection.spanned_rows(true, &display_map);
 8233            selection.start = Point::new(rows.start.0, 0);
 8234            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8235            selection.reversed = false;
 8236        }
 8237        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8238            s.select(selections);
 8239        });
 8240    }
 8241
 8242    pub fn split_selection_into_lines(
 8243        &mut self,
 8244        _: &SplitSelectionIntoLines,
 8245        cx: &mut ViewContext<Self>,
 8246    ) {
 8247        let mut to_unfold = Vec::new();
 8248        let mut new_selection_ranges = Vec::new();
 8249        {
 8250            let selections = self.selections.all::<Point>(cx);
 8251            let buffer = self.buffer.read(cx).read(cx);
 8252            for selection in selections {
 8253                for row in selection.start.row..selection.end.row {
 8254                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8255                    new_selection_ranges.push(cursor..cursor);
 8256                }
 8257                new_selection_ranges.push(selection.end..selection.end);
 8258                to_unfold.push(selection.start..selection.end);
 8259            }
 8260        }
 8261        self.unfold_ranges(to_unfold, true, true, cx);
 8262        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8263            s.select_ranges(new_selection_ranges);
 8264        });
 8265    }
 8266
 8267    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8268        self.add_selection(true, cx);
 8269    }
 8270
 8271    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8272        self.add_selection(false, cx);
 8273    }
 8274
 8275    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8277        let mut selections = self.selections.all::<Point>(cx);
 8278        let text_layout_details = self.text_layout_details(cx);
 8279        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8280            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8281            let range = oldest_selection.display_range(&display_map).sorted();
 8282
 8283            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8284            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8285            let positions = start_x.min(end_x)..start_x.max(end_x);
 8286
 8287            selections.clear();
 8288            let mut stack = Vec::new();
 8289            for row in range.start.row().0..=range.end.row().0 {
 8290                if let Some(selection) = self.selections.build_columnar_selection(
 8291                    &display_map,
 8292                    DisplayRow(row),
 8293                    &positions,
 8294                    oldest_selection.reversed,
 8295                    &text_layout_details,
 8296                ) {
 8297                    stack.push(selection.id);
 8298                    selections.push(selection);
 8299                }
 8300            }
 8301
 8302            if above {
 8303                stack.reverse();
 8304            }
 8305
 8306            AddSelectionsState { above, stack }
 8307        });
 8308
 8309        let last_added_selection = *state.stack.last().unwrap();
 8310        let mut new_selections = Vec::new();
 8311        if above == state.above {
 8312            let end_row = if above {
 8313                DisplayRow(0)
 8314            } else {
 8315                display_map.max_point().row()
 8316            };
 8317
 8318            'outer: for selection in selections {
 8319                if selection.id == last_added_selection {
 8320                    let range = selection.display_range(&display_map).sorted();
 8321                    debug_assert_eq!(range.start.row(), range.end.row());
 8322                    let mut row = range.start.row();
 8323                    let positions =
 8324                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8325                            px(start)..px(end)
 8326                        } else {
 8327                            let start_x =
 8328                                display_map.x_for_display_point(range.start, &text_layout_details);
 8329                            let end_x =
 8330                                display_map.x_for_display_point(range.end, &text_layout_details);
 8331                            start_x.min(end_x)..start_x.max(end_x)
 8332                        };
 8333
 8334                    while row != end_row {
 8335                        if above {
 8336                            row.0 -= 1;
 8337                        } else {
 8338                            row.0 += 1;
 8339                        }
 8340
 8341                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8342                            &display_map,
 8343                            row,
 8344                            &positions,
 8345                            selection.reversed,
 8346                            &text_layout_details,
 8347                        ) {
 8348                            state.stack.push(new_selection.id);
 8349                            if above {
 8350                                new_selections.push(new_selection);
 8351                                new_selections.push(selection);
 8352                            } else {
 8353                                new_selections.push(selection);
 8354                                new_selections.push(new_selection);
 8355                            }
 8356
 8357                            continue 'outer;
 8358                        }
 8359                    }
 8360                }
 8361
 8362                new_selections.push(selection);
 8363            }
 8364        } else {
 8365            new_selections = selections;
 8366            new_selections.retain(|s| s.id != last_added_selection);
 8367            state.stack.pop();
 8368        }
 8369
 8370        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8371            s.select(new_selections);
 8372        });
 8373        if state.stack.len() > 1 {
 8374            self.add_selections_state = Some(state);
 8375        }
 8376    }
 8377
 8378    pub fn select_next_match_internal(
 8379        &mut self,
 8380        display_map: &DisplaySnapshot,
 8381        replace_newest: bool,
 8382        autoscroll: Option<Autoscroll>,
 8383        cx: &mut ViewContext<Self>,
 8384    ) -> Result<()> {
 8385        fn select_next_match_ranges(
 8386            this: &mut Editor,
 8387            range: Range<usize>,
 8388            replace_newest: bool,
 8389            auto_scroll: Option<Autoscroll>,
 8390            cx: &mut ViewContext<Editor>,
 8391        ) {
 8392            this.unfold_ranges([range.clone()], false, true, cx);
 8393            this.change_selections(auto_scroll, cx, |s| {
 8394                if replace_newest {
 8395                    s.delete(s.newest_anchor().id);
 8396                }
 8397                s.insert_range(range.clone());
 8398            });
 8399        }
 8400
 8401        let buffer = &display_map.buffer_snapshot;
 8402        let mut selections = self.selections.all::<usize>(cx);
 8403        if let Some(mut select_next_state) = self.select_next_state.take() {
 8404            let query = &select_next_state.query;
 8405            if !select_next_state.done {
 8406                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8407                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8408                let mut next_selected_range = None;
 8409
 8410                let bytes_after_last_selection =
 8411                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8412                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8413                let query_matches = query
 8414                    .stream_find_iter(bytes_after_last_selection)
 8415                    .map(|result| (last_selection.end, result))
 8416                    .chain(
 8417                        query
 8418                            .stream_find_iter(bytes_before_first_selection)
 8419                            .map(|result| (0, result)),
 8420                    );
 8421
 8422                for (start_offset, query_match) in query_matches {
 8423                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8424                    let offset_range =
 8425                        start_offset + query_match.start()..start_offset + query_match.end();
 8426                    let display_range = offset_range.start.to_display_point(display_map)
 8427                        ..offset_range.end.to_display_point(display_map);
 8428
 8429                    if !select_next_state.wordwise
 8430                        || (!movement::is_inside_word(display_map, display_range.start)
 8431                            && !movement::is_inside_word(display_map, display_range.end))
 8432                    {
 8433                        // TODO: This is n^2, because we might check all the selections
 8434                        if !selections
 8435                            .iter()
 8436                            .any(|selection| selection.range().overlaps(&offset_range))
 8437                        {
 8438                            next_selected_range = Some(offset_range);
 8439                            break;
 8440                        }
 8441                    }
 8442                }
 8443
 8444                if let Some(next_selected_range) = next_selected_range {
 8445                    select_next_match_ranges(
 8446                        self,
 8447                        next_selected_range,
 8448                        replace_newest,
 8449                        autoscroll,
 8450                        cx,
 8451                    );
 8452                } else {
 8453                    select_next_state.done = true;
 8454                }
 8455            }
 8456
 8457            self.select_next_state = Some(select_next_state);
 8458        } else {
 8459            let mut only_carets = true;
 8460            let mut same_text_selected = true;
 8461            let mut selected_text = None;
 8462
 8463            let mut selections_iter = selections.iter().peekable();
 8464            while let Some(selection) = selections_iter.next() {
 8465                if selection.start != selection.end {
 8466                    only_carets = false;
 8467                }
 8468
 8469                if same_text_selected {
 8470                    if selected_text.is_none() {
 8471                        selected_text =
 8472                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8473                    }
 8474
 8475                    if let Some(next_selection) = selections_iter.peek() {
 8476                        if next_selection.range().len() == selection.range().len() {
 8477                            let next_selected_text = buffer
 8478                                .text_for_range(next_selection.range())
 8479                                .collect::<String>();
 8480                            if Some(next_selected_text) != selected_text {
 8481                                same_text_selected = false;
 8482                                selected_text = None;
 8483                            }
 8484                        } else {
 8485                            same_text_selected = false;
 8486                            selected_text = None;
 8487                        }
 8488                    }
 8489                }
 8490            }
 8491
 8492            if only_carets {
 8493                for selection in &mut selections {
 8494                    let word_range = movement::surrounding_word(
 8495                        display_map,
 8496                        selection.start.to_display_point(display_map),
 8497                    );
 8498                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8499                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8500                    selection.goal = SelectionGoal::None;
 8501                    selection.reversed = false;
 8502                    select_next_match_ranges(
 8503                        self,
 8504                        selection.start..selection.end,
 8505                        replace_newest,
 8506                        autoscroll,
 8507                        cx,
 8508                    );
 8509                }
 8510
 8511                if selections.len() == 1 {
 8512                    let selection = selections
 8513                        .last()
 8514                        .expect("ensured that there's only one selection");
 8515                    let query = buffer
 8516                        .text_for_range(selection.start..selection.end)
 8517                        .collect::<String>();
 8518                    let is_empty = query.is_empty();
 8519                    let select_state = SelectNextState {
 8520                        query: AhoCorasick::new(&[query])?,
 8521                        wordwise: true,
 8522                        done: is_empty,
 8523                    };
 8524                    self.select_next_state = Some(select_state);
 8525                } else {
 8526                    self.select_next_state = None;
 8527                }
 8528            } else if let Some(selected_text) = selected_text {
 8529                self.select_next_state = Some(SelectNextState {
 8530                    query: AhoCorasick::new(&[selected_text])?,
 8531                    wordwise: false,
 8532                    done: false,
 8533                });
 8534                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8535            }
 8536        }
 8537        Ok(())
 8538    }
 8539
 8540    pub fn select_all_matches(
 8541        &mut self,
 8542        _action: &SelectAllMatches,
 8543        cx: &mut ViewContext<Self>,
 8544    ) -> Result<()> {
 8545        self.push_to_selection_history();
 8546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8547
 8548        self.select_next_match_internal(&display_map, false, None, cx)?;
 8549        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8550            return Ok(());
 8551        };
 8552        if select_next_state.done {
 8553            return Ok(());
 8554        }
 8555
 8556        let mut new_selections = self.selections.all::<usize>(cx);
 8557
 8558        let buffer = &display_map.buffer_snapshot;
 8559        let query_matches = select_next_state
 8560            .query
 8561            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8562
 8563        for query_match in query_matches {
 8564            let query_match = query_match.unwrap(); // can only fail due to I/O
 8565            let offset_range = query_match.start()..query_match.end();
 8566            let display_range = offset_range.start.to_display_point(&display_map)
 8567                ..offset_range.end.to_display_point(&display_map);
 8568
 8569            if !select_next_state.wordwise
 8570                || (!movement::is_inside_word(&display_map, display_range.start)
 8571                    && !movement::is_inside_word(&display_map, display_range.end))
 8572            {
 8573                self.selections.change_with(cx, |selections| {
 8574                    new_selections.push(Selection {
 8575                        id: selections.new_selection_id(),
 8576                        start: offset_range.start,
 8577                        end: offset_range.end,
 8578                        reversed: false,
 8579                        goal: SelectionGoal::None,
 8580                    });
 8581                });
 8582            }
 8583        }
 8584
 8585        new_selections.sort_by_key(|selection| selection.start);
 8586        let mut ix = 0;
 8587        while ix + 1 < new_selections.len() {
 8588            let current_selection = &new_selections[ix];
 8589            let next_selection = &new_selections[ix + 1];
 8590            if current_selection.range().overlaps(&next_selection.range()) {
 8591                if current_selection.id < next_selection.id {
 8592                    new_selections.remove(ix + 1);
 8593                } else {
 8594                    new_selections.remove(ix);
 8595                }
 8596            } else {
 8597                ix += 1;
 8598            }
 8599        }
 8600
 8601        select_next_state.done = true;
 8602        self.unfold_ranges(
 8603            new_selections.iter().map(|selection| selection.range()),
 8604            false,
 8605            false,
 8606            cx,
 8607        );
 8608        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8609            selections.select(new_selections)
 8610        });
 8611
 8612        Ok(())
 8613    }
 8614
 8615    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8616        self.push_to_selection_history();
 8617        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8618        self.select_next_match_internal(
 8619            &display_map,
 8620            action.replace_newest,
 8621            Some(Autoscroll::newest()),
 8622            cx,
 8623        )?;
 8624        Ok(())
 8625    }
 8626
 8627    pub fn select_previous(
 8628        &mut self,
 8629        action: &SelectPrevious,
 8630        cx: &mut ViewContext<Self>,
 8631    ) -> Result<()> {
 8632        self.push_to_selection_history();
 8633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8634        let buffer = &display_map.buffer_snapshot;
 8635        let mut selections = self.selections.all::<usize>(cx);
 8636        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8637            let query = &select_prev_state.query;
 8638            if !select_prev_state.done {
 8639                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8640                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8641                let mut next_selected_range = None;
 8642                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8643                let bytes_before_last_selection =
 8644                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8645                let bytes_after_first_selection =
 8646                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8647                let query_matches = query
 8648                    .stream_find_iter(bytes_before_last_selection)
 8649                    .map(|result| (last_selection.start, result))
 8650                    .chain(
 8651                        query
 8652                            .stream_find_iter(bytes_after_first_selection)
 8653                            .map(|result| (buffer.len(), result)),
 8654                    );
 8655                for (end_offset, query_match) in query_matches {
 8656                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8657                    let offset_range =
 8658                        end_offset - query_match.end()..end_offset - query_match.start();
 8659                    let display_range = offset_range.start.to_display_point(&display_map)
 8660                        ..offset_range.end.to_display_point(&display_map);
 8661
 8662                    if !select_prev_state.wordwise
 8663                        || (!movement::is_inside_word(&display_map, display_range.start)
 8664                            && !movement::is_inside_word(&display_map, display_range.end))
 8665                    {
 8666                        next_selected_range = Some(offset_range);
 8667                        break;
 8668                    }
 8669                }
 8670
 8671                if let Some(next_selected_range) = next_selected_range {
 8672                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8673                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8674                        if action.replace_newest {
 8675                            s.delete(s.newest_anchor().id);
 8676                        }
 8677                        s.insert_range(next_selected_range);
 8678                    });
 8679                } else {
 8680                    select_prev_state.done = true;
 8681                }
 8682            }
 8683
 8684            self.select_prev_state = Some(select_prev_state);
 8685        } else {
 8686            let mut only_carets = true;
 8687            let mut same_text_selected = true;
 8688            let mut selected_text = None;
 8689
 8690            let mut selections_iter = selections.iter().peekable();
 8691            while let Some(selection) = selections_iter.next() {
 8692                if selection.start != selection.end {
 8693                    only_carets = false;
 8694                }
 8695
 8696                if same_text_selected {
 8697                    if selected_text.is_none() {
 8698                        selected_text =
 8699                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8700                    }
 8701
 8702                    if let Some(next_selection) = selections_iter.peek() {
 8703                        if next_selection.range().len() == selection.range().len() {
 8704                            let next_selected_text = buffer
 8705                                .text_for_range(next_selection.range())
 8706                                .collect::<String>();
 8707                            if Some(next_selected_text) != selected_text {
 8708                                same_text_selected = false;
 8709                                selected_text = None;
 8710                            }
 8711                        } else {
 8712                            same_text_selected = false;
 8713                            selected_text = None;
 8714                        }
 8715                    }
 8716                }
 8717            }
 8718
 8719            if only_carets {
 8720                for selection in &mut selections {
 8721                    let word_range = movement::surrounding_word(
 8722                        &display_map,
 8723                        selection.start.to_display_point(&display_map),
 8724                    );
 8725                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8726                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8727                    selection.goal = SelectionGoal::None;
 8728                    selection.reversed = false;
 8729                }
 8730                if selections.len() == 1 {
 8731                    let selection = selections
 8732                        .last()
 8733                        .expect("ensured that there's only one selection");
 8734                    let query = buffer
 8735                        .text_for_range(selection.start..selection.end)
 8736                        .collect::<String>();
 8737                    let is_empty = query.is_empty();
 8738                    let select_state = SelectNextState {
 8739                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8740                        wordwise: true,
 8741                        done: is_empty,
 8742                    };
 8743                    self.select_prev_state = Some(select_state);
 8744                } else {
 8745                    self.select_prev_state = None;
 8746                }
 8747
 8748                self.unfold_ranges(
 8749                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8750                    false,
 8751                    true,
 8752                    cx,
 8753                );
 8754                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8755                    s.select(selections);
 8756                });
 8757            } else if let Some(selected_text) = selected_text {
 8758                self.select_prev_state = Some(SelectNextState {
 8759                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8760                    wordwise: false,
 8761                    done: false,
 8762                });
 8763                self.select_previous(action, cx)?;
 8764            }
 8765        }
 8766        Ok(())
 8767    }
 8768
 8769    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8770        let text_layout_details = &self.text_layout_details(cx);
 8771        self.transact(cx, |this, cx| {
 8772            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8773            let mut edits = Vec::new();
 8774            let mut selection_edit_ranges = Vec::new();
 8775            let mut last_toggled_row = None;
 8776            let snapshot = this.buffer.read(cx).read(cx);
 8777            let empty_str: Arc<str> = Arc::default();
 8778            let mut suffixes_inserted = Vec::new();
 8779            let ignore_indent = action.ignore_indent;
 8780
 8781            fn comment_prefix_range(
 8782                snapshot: &MultiBufferSnapshot,
 8783                row: MultiBufferRow,
 8784                comment_prefix: &str,
 8785                comment_prefix_whitespace: &str,
 8786                ignore_indent: bool,
 8787            ) -> Range<Point> {
 8788                let indent_size = if ignore_indent {
 8789                    0
 8790                } else {
 8791                    snapshot.indent_size_for_line(row).len
 8792                };
 8793
 8794                let start = Point::new(row.0, indent_size);
 8795
 8796                let mut line_bytes = snapshot
 8797                    .bytes_in_range(start..snapshot.max_point())
 8798                    .flatten()
 8799                    .copied();
 8800
 8801                // If this line currently begins with the line comment prefix, then record
 8802                // the range containing the prefix.
 8803                if line_bytes
 8804                    .by_ref()
 8805                    .take(comment_prefix.len())
 8806                    .eq(comment_prefix.bytes())
 8807                {
 8808                    // Include any whitespace that matches the comment prefix.
 8809                    let matching_whitespace_len = line_bytes
 8810                        .zip(comment_prefix_whitespace.bytes())
 8811                        .take_while(|(a, b)| a == b)
 8812                        .count() as u32;
 8813                    let end = Point::new(
 8814                        start.row,
 8815                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8816                    );
 8817                    start..end
 8818                } else {
 8819                    start..start
 8820                }
 8821            }
 8822
 8823            fn comment_suffix_range(
 8824                snapshot: &MultiBufferSnapshot,
 8825                row: MultiBufferRow,
 8826                comment_suffix: &str,
 8827                comment_suffix_has_leading_space: bool,
 8828            ) -> Range<Point> {
 8829                let end = Point::new(row.0, snapshot.line_len(row));
 8830                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8831
 8832                let mut line_end_bytes = snapshot
 8833                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8834                    .flatten()
 8835                    .copied();
 8836
 8837                let leading_space_len = if suffix_start_column > 0
 8838                    && line_end_bytes.next() == Some(b' ')
 8839                    && comment_suffix_has_leading_space
 8840                {
 8841                    1
 8842                } else {
 8843                    0
 8844                };
 8845
 8846                // If this line currently begins with the line comment prefix, then record
 8847                // the range containing the prefix.
 8848                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8849                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8850                    start..end
 8851                } else {
 8852                    end..end
 8853                }
 8854            }
 8855
 8856            // TODO: Handle selections that cross excerpts
 8857            for selection in &mut selections {
 8858                let start_column = snapshot
 8859                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8860                    .len;
 8861                let language = if let Some(language) =
 8862                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8863                {
 8864                    language
 8865                } else {
 8866                    continue;
 8867                };
 8868
 8869                selection_edit_ranges.clear();
 8870
 8871                // If multiple selections contain a given row, avoid processing that
 8872                // row more than once.
 8873                let mut start_row = MultiBufferRow(selection.start.row);
 8874                if last_toggled_row == Some(start_row) {
 8875                    start_row = start_row.next_row();
 8876                }
 8877                let end_row =
 8878                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8879                        MultiBufferRow(selection.end.row - 1)
 8880                    } else {
 8881                        MultiBufferRow(selection.end.row)
 8882                    };
 8883                last_toggled_row = Some(end_row);
 8884
 8885                if start_row > end_row {
 8886                    continue;
 8887                }
 8888
 8889                // If the language has line comments, toggle those.
 8890                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8891
 8892                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8893                if ignore_indent {
 8894                    full_comment_prefixes = full_comment_prefixes
 8895                        .into_iter()
 8896                        .map(|s| Arc::from(s.trim_end()))
 8897                        .collect();
 8898                }
 8899
 8900                if !full_comment_prefixes.is_empty() {
 8901                    let first_prefix = full_comment_prefixes
 8902                        .first()
 8903                        .expect("prefixes is non-empty");
 8904                    let prefix_trimmed_lengths = full_comment_prefixes
 8905                        .iter()
 8906                        .map(|p| p.trim_end_matches(' ').len())
 8907                        .collect::<SmallVec<[usize; 4]>>();
 8908
 8909                    let mut all_selection_lines_are_comments = true;
 8910
 8911                    for row in start_row.0..=end_row.0 {
 8912                        let row = MultiBufferRow(row);
 8913                        if start_row < end_row && snapshot.is_line_blank(row) {
 8914                            continue;
 8915                        }
 8916
 8917                        let prefix_range = full_comment_prefixes
 8918                            .iter()
 8919                            .zip(prefix_trimmed_lengths.iter().copied())
 8920                            .map(|(prefix, trimmed_prefix_len)| {
 8921                                comment_prefix_range(
 8922                                    snapshot.deref(),
 8923                                    row,
 8924                                    &prefix[..trimmed_prefix_len],
 8925                                    &prefix[trimmed_prefix_len..],
 8926                                    ignore_indent,
 8927                                )
 8928                            })
 8929                            .max_by_key(|range| range.end.column - range.start.column)
 8930                            .expect("prefixes is non-empty");
 8931
 8932                        if prefix_range.is_empty() {
 8933                            all_selection_lines_are_comments = false;
 8934                        }
 8935
 8936                        selection_edit_ranges.push(prefix_range);
 8937                    }
 8938
 8939                    if all_selection_lines_are_comments {
 8940                        edits.extend(
 8941                            selection_edit_ranges
 8942                                .iter()
 8943                                .cloned()
 8944                                .map(|range| (range, empty_str.clone())),
 8945                        );
 8946                    } else {
 8947                        let min_column = selection_edit_ranges
 8948                            .iter()
 8949                            .map(|range| range.start.column)
 8950                            .min()
 8951                            .unwrap_or(0);
 8952                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8953                            let position = Point::new(range.start.row, min_column);
 8954                            (position..position, first_prefix.clone())
 8955                        }));
 8956                    }
 8957                } else if let Some((full_comment_prefix, comment_suffix)) =
 8958                    language.block_comment_delimiters()
 8959                {
 8960                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8961                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8962                    let prefix_range = comment_prefix_range(
 8963                        snapshot.deref(),
 8964                        start_row,
 8965                        comment_prefix,
 8966                        comment_prefix_whitespace,
 8967                        ignore_indent,
 8968                    );
 8969                    let suffix_range = comment_suffix_range(
 8970                        snapshot.deref(),
 8971                        end_row,
 8972                        comment_suffix.trim_start_matches(' '),
 8973                        comment_suffix.starts_with(' '),
 8974                    );
 8975
 8976                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8977                        edits.push((
 8978                            prefix_range.start..prefix_range.start,
 8979                            full_comment_prefix.clone(),
 8980                        ));
 8981                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8982                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8983                    } else {
 8984                        edits.push((prefix_range, empty_str.clone()));
 8985                        edits.push((suffix_range, empty_str.clone()));
 8986                    }
 8987                } else {
 8988                    continue;
 8989                }
 8990            }
 8991
 8992            drop(snapshot);
 8993            this.buffer.update(cx, |buffer, cx| {
 8994                buffer.edit(edits, None, cx);
 8995            });
 8996
 8997            // Adjust selections so that they end before any comment suffixes that
 8998            // were inserted.
 8999            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9000            let mut selections = this.selections.all::<Point>(cx);
 9001            let snapshot = this.buffer.read(cx).read(cx);
 9002            for selection in &mut selections {
 9003                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9004                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9005                        Ordering::Less => {
 9006                            suffixes_inserted.next();
 9007                            continue;
 9008                        }
 9009                        Ordering::Greater => break,
 9010                        Ordering::Equal => {
 9011                            if selection.end.column == snapshot.line_len(row) {
 9012                                if selection.is_empty() {
 9013                                    selection.start.column -= suffix_len as u32;
 9014                                }
 9015                                selection.end.column -= suffix_len as u32;
 9016                            }
 9017                            break;
 9018                        }
 9019                    }
 9020                }
 9021            }
 9022
 9023            drop(snapshot);
 9024            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9025
 9026            let selections = this.selections.all::<Point>(cx);
 9027            let selections_on_single_row = selections.windows(2).all(|selections| {
 9028                selections[0].start.row == selections[1].start.row
 9029                    && selections[0].end.row == selections[1].end.row
 9030                    && selections[0].start.row == selections[0].end.row
 9031            });
 9032            let selections_selecting = selections
 9033                .iter()
 9034                .any(|selection| selection.start != selection.end);
 9035            let advance_downwards = action.advance_downwards
 9036                && selections_on_single_row
 9037                && !selections_selecting
 9038                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9039
 9040            if advance_downwards {
 9041                let snapshot = this.buffer.read(cx).snapshot(cx);
 9042
 9043                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9044                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9045                        let mut point = display_point.to_point(display_snapshot);
 9046                        point.row += 1;
 9047                        point = snapshot.clip_point(point, Bias::Left);
 9048                        let display_point = point.to_display_point(display_snapshot);
 9049                        let goal = SelectionGoal::HorizontalPosition(
 9050                            display_snapshot
 9051                                .x_for_display_point(display_point, text_layout_details)
 9052                                .into(),
 9053                        );
 9054                        (display_point, goal)
 9055                    })
 9056                });
 9057            }
 9058        });
 9059    }
 9060
 9061    pub fn select_enclosing_symbol(
 9062        &mut self,
 9063        _: &SelectEnclosingSymbol,
 9064        cx: &mut ViewContext<Self>,
 9065    ) {
 9066        let buffer = self.buffer.read(cx).snapshot(cx);
 9067        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9068
 9069        fn update_selection(
 9070            selection: &Selection<usize>,
 9071            buffer_snap: &MultiBufferSnapshot,
 9072        ) -> Option<Selection<usize>> {
 9073            let cursor = selection.head();
 9074            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9075            for symbol in symbols.iter().rev() {
 9076                let start = symbol.range.start.to_offset(buffer_snap);
 9077                let end = symbol.range.end.to_offset(buffer_snap);
 9078                let new_range = start..end;
 9079                if start < selection.start || end > selection.end {
 9080                    return Some(Selection {
 9081                        id: selection.id,
 9082                        start: new_range.start,
 9083                        end: new_range.end,
 9084                        goal: SelectionGoal::None,
 9085                        reversed: selection.reversed,
 9086                    });
 9087                }
 9088            }
 9089            None
 9090        }
 9091
 9092        let mut selected_larger_symbol = false;
 9093        let new_selections = old_selections
 9094            .iter()
 9095            .map(|selection| match update_selection(selection, &buffer) {
 9096                Some(new_selection) => {
 9097                    if new_selection.range() != selection.range() {
 9098                        selected_larger_symbol = true;
 9099                    }
 9100                    new_selection
 9101                }
 9102                None => selection.clone(),
 9103            })
 9104            .collect::<Vec<_>>();
 9105
 9106        if selected_larger_symbol {
 9107            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9108                s.select(new_selections);
 9109            });
 9110        }
 9111    }
 9112
 9113    pub fn select_larger_syntax_node(
 9114        &mut self,
 9115        _: &SelectLargerSyntaxNode,
 9116        cx: &mut ViewContext<Self>,
 9117    ) {
 9118        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9119        let buffer = self.buffer.read(cx).snapshot(cx);
 9120        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9121
 9122        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9123        let mut selected_larger_node = false;
 9124        let new_selections = old_selections
 9125            .iter()
 9126            .map(|selection| {
 9127                let old_range = selection.start..selection.end;
 9128                let mut new_range = old_range.clone();
 9129                while let Some(containing_range) =
 9130                    buffer.range_for_syntax_ancestor(new_range.clone())
 9131                {
 9132                    new_range = containing_range;
 9133                    if !display_map.intersects_fold(new_range.start)
 9134                        && !display_map.intersects_fold(new_range.end)
 9135                    {
 9136                        break;
 9137                    }
 9138                }
 9139
 9140                selected_larger_node |= new_range != old_range;
 9141                Selection {
 9142                    id: selection.id,
 9143                    start: new_range.start,
 9144                    end: new_range.end,
 9145                    goal: SelectionGoal::None,
 9146                    reversed: selection.reversed,
 9147                }
 9148            })
 9149            .collect::<Vec<_>>();
 9150
 9151        if selected_larger_node {
 9152            stack.push(old_selections);
 9153            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9154                s.select(new_selections);
 9155            });
 9156        }
 9157        self.select_larger_syntax_node_stack = stack;
 9158    }
 9159
 9160    pub fn select_smaller_syntax_node(
 9161        &mut self,
 9162        _: &SelectSmallerSyntaxNode,
 9163        cx: &mut ViewContext<Self>,
 9164    ) {
 9165        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9166        if let Some(selections) = stack.pop() {
 9167            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9168                s.select(selections.to_vec());
 9169            });
 9170        }
 9171        self.select_larger_syntax_node_stack = stack;
 9172    }
 9173
 9174    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9175        if !EditorSettings::get_global(cx).gutter.runnables {
 9176            self.clear_tasks();
 9177            return Task::ready(());
 9178        }
 9179        let project = self.project.clone();
 9180        cx.spawn(|this, mut cx| async move {
 9181            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9182                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9183            }) else {
 9184                return;
 9185            };
 9186
 9187            let Some(project) = project else {
 9188                return;
 9189            };
 9190
 9191            let hide_runnables = project
 9192                .update(&mut cx, |project, cx| {
 9193                    // Do not display any test indicators in non-dev server remote projects.
 9194                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9195                })
 9196                .unwrap_or(true);
 9197            if hide_runnables {
 9198                return;
 9199            }
 9200            let new_rows =
 9201                cx.background_executor()
 9202                    .spawn({
 9203                        let snapshot = display_snapshot.clone();
 9204                        async move {
 9205                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9206                        }
 9207                    })
 9208                    .await;
 9209            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9210
 9211            this.update(&mut cx, |this, _| {
 9212                this.clear_tasks();
 9213                for (key, value) in rows {
 9214                    this.insert_tasks(key, value);
 9215                }
 9216            })
 9217            .ok();
 9218        })
 9219    }
 9220    fn fetch_runnable_ranges(
 9221        snapshot: &DisplaySnapshot,
 9222        range: Range<Anchor>,
 9223    ) -> Vec<language::RunnableRange> {
 9224        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9225    }
 9226
 9227    fn runnable_rows(
 9228        project: Model<Project>,
 9229        snapshot: DisplaySnapshot,
 9230        runnable_ranges: Vec<RunnableRange>,
 9231        mut cx: AsyncWindowContext,
 9232    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9233        runnable_ranges
 9234            .into_iter()
 9235            .filter_map(|mut runnable| {
 9236                let tasks = cx
 9237                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9238                    .ok()?;
 9239                if tasks.is_empty() {
 9240                    return None;
 9241                }
 9242
 9243                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9244
 9245                let row = snapshot
 9246                    .buffer_snapshot
 9247                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9248                    .1
 9249                    .start
 9250                    .row;
 9251
 9252                let context_range =
 9253                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9254                Some((
 9255                    (runnable.buffer_id, row),
 9256                    RunnableTasks {
 9257                        templates: tasks,
 9258                        offset: MultiBufferOffset(runnable.run_range.start),
 9259                        context_range,
 9260                        column: point.column,
 9261                        extra_variables: runnable.extra_captures,
 9262                    },
 9263                ))
 9264            })
 9265            .collect()
 9266    }
 9267
 9268    fn templates_with_tags(
 9269        project: &Model<Project>,
 9270        runnable: &mut Runnable,
 9271        cx: &WindowContext<'_>,
 9272    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9273        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9274            let (worktree_id, file) = project
 9275                .buffer_for_id(runnable.buffer, cx)
 9276                .and_then(|buffer| buffer.read(cx).file())
 9277                .map(|file| (file.worktree_id(cx), file.clone()))
 9278                .unzip();
 9279
 9280            (
 9281                project.task_store().read(cx).task_inventory().cloned(),
 9282                worktree_id,
 9283                file,
 9284            )
 9285        });
 9286
 9287        let tags = mem::take(&mut runnable.tags);
 9288        let mut tags: Vec<_> = tags
 9289            .into_iter()
 9290            .flat_map(|tag| {
 9291                let tag = tag.0.clone();
 9292                inventory
 9293                    .as_ref()
 9294                    .into_iter()
 9295                    .flat_map(|inventory| {
 9296                        inventory.read(cx).list_tasks(
 9297                            file.clone(),
 9298                            Some(runnable.language.clone()),
 9299                            worktree_id,
 9300                            cx,
 9301                        )
 9302                    })
 9303                    .filter(move |(_, template)| {
 9304                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9305                    })
 9306            })
 9307            .sorted_by_key(|(kind, _)| kind.to_owned())
 9308            .collect();
 9309        if let Some((leading_tag_source, _)) = tags.first() {
 9310            // Strongest source wins; if we have worktree tag binding, prefer that to
 9311            // global and language bindings;
 9312            // if we have a global binding, prefer that to language binding.
 9313            let first_mismatch = tags
 9314                .iter()
 9315                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9316            if let Some(index) = first_mismatch {
 9317                tags.truncate(index);
 9318            }
 9319        }
 9320
 9321        tags
 9322    }
 9323
 9324    pub fn move_to_enclosing_bracket(
 9325        &mut self,
 9326        _: &MoveToEnclosingBracket,
 9327        cx: &mut ViewContext<Self>,
 9328    ) {
 9329        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9330            s.move_offsets_with(|snapshot, selection| {
 9331                let Some(enclosing_bracket_ranges) =
 9332                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9333                else {
 9334                    return;
 9335                };
 9336
 9337                let mut best_length = usize::MAX;
 9338                let mut best_inside = false;
 9339                let mut best_in_bracket_range = false;
 9340                let mut best_destination = None;
 9341                for (open, close) in enclosing_bracket_ranges {
 9342                    let close = close.to_inclusive();
 9343                    let length = close.end() - open.start;
 9344                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9345                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9346                        || close.contains(&selection.head());
 9347
 9348                    // If best is next to a bracket and current isn't, skip
 9349                    if !in_bracket_range && best_in_bracket_range {
 9350                        continue;
 9351                    }
 9352
 9353                    // Prefer smaller lengths unless best is inside and current isn't
 9354                    if length > best_length && (best_inside || !inside) {
 9355                        continue;
 9356                    }
 9357
 9358                    best_length = length;
 9359                    best_inside = inside;
 9360                    best_in_bracket_range = in_bracket_range;
 9361                    best_destination = Some(
 9362                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9363                            if inside {
 9364                                open.end
 9365                            } else {
 9366                                open.start
 9367                            }
 9368                        } else if inside {
 9369                            *close.start()
 9370                        } else {
 9371                            *close.end()
 9372                        },
 9373                    );
 9374                }
 9375
 9376                if let Some(destination) = best_destination {
 9377                    selection.collapse_to(destination, SelectionGoal::None);
 9378                }
 9379            })
 9380        });
 9381    }
 9382
 9383    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9384        self.end_selection(cx);
 9385        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9386        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9387            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9388            self.select_next_state = entry.select_next_state;
 9389            self.select_prev_state = entry.select_prev_state;
 9390            self.add_selections_state = entry.add_selections_state;
 9391            self.request_autoscroll(Autoscroll::newest(), cx);
 9392        }
 9393        self.selection_history.mode = SelectionHistoryMode::Normal;
 9394    }
 9395
 9396    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9397        self.end_selection(cx);
 9398        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9399        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9400            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9401            self.select_next_state = entry.select_next_state;
 9402            self.select_prev_state = entry.select_prev_state;
 9403            self.add_selections_state = entry.add_selections_state;
 9404            self.request_autoscroll(Autoscroll::newest(), cx);
 9405        }
 9406        self.selection_history.mode = SelectionHistoryMode::Normal;
 9407    }
 9408
 9409    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9410        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9411    }
 9412
 9413    pub fn expand_excerpts_down(
 9414        &mut self,
 9415        action: &ExpandExcerptsDown,
 9416        cx: &mut ViewContext<Self>,
 9417    ) {
 9418        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9419    }
 9420
 9421    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9422        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9423    }
 9424
 9425    pub fn expand_excerpts_for_direction(
 9426        &mut self,
 9427        lines: u32,
 9428        direction: ExpandExcerptDirection,
 9429        cx: &mut ViewContext<Self>,
 9430    ) {
 9431        let selections = self.selections.disjoint_anchors();
 9432
 9433        let lines = if lines == 0 {
 9434            EditorSettings::get_global(cx).expand_excerpt_lines
 9435        } else {
 9436            lines
 9437        };
 9438
 9439        self.buffer.update(cx, |buffer, cx| {
 9440            buffer.expand_excerpts(
 9441                selections
 9442                    .iter()
 9443                    .map(|selection| selection.head().excerpt_id)
 9444                    .dedup(),
 9445                lines,
 9446                direction,
 9447                cx,
 9448            )
 9449        })
 9450    }
 9451
 9452    pub fn expand_excerpt(
 9453        &mut self,
 9454        excerpt: ExcerptId,
 9455        direction: ExpandExcerptDirection,
 9456        cx: &mut ViewContext<Self>,
 9457    ) {
 9458        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9459        self.buffer.update(cx, |buffer, cx| {
 9460            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9461        })
 9462    }
 9463
 9464    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9465        self.go_to_diagnostic_impl(Direction::Next, cx)
 9466    }
 9467
 9468    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9469        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9470    }
 9471
 9472    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9473        let buffer = self.buffer.read(cx).snapshot(cx);
 9474        let selection = self.selections.newest::<usize>(cx);
 9475
 9476        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9477        if direction == Direction::Next {
 9478            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9479                let (group_id, jump_to) = popover.activation_info();
 9480                if self.activate_diagnostics(group_id, cx) {
 9481                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9482                        let mut new_selection = s.newest_anchor().clone();
 9483                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9484                        s.select_anchors(vec![new_selection.clone()]);
 9485                    });
 9486                }
 9487                return;
 9488            }
 9489        }
 9490
 9491        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9492            active_diagnostics
 9493                .primary_range
 9494                .to_offset(&buffer)
 9495                .to_inclusive()
 9496        });
 9497        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9498            if active_primary_range.contains(&selection.head()) {
 9499                *active_primary_range.start()
 9500            } else {
 9501                selection.head()
 9502            }
 9503        } else {
 9504            selection.head()
 9505        };
 9506        let snapshot = self.snapshot(cx);
 9507        loop {
 9508            let diagnostics = if direction == Direction::Prev {
 9509                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9510            } else {
 9511                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9512            }
 9513            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9514            let group = diagnostics
 9515                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9516                // be sorted in a stable way
 9517                // skip until we are at current active diagnostic, if it exists
 9518                .skip_while(|entry| {
 9519                    (match direction {
 9520                        Direction::Prev => entry.range.start >= search_start,
 9521                        Direction::Next => entry.range.start <= search_start,
 9522                    }) && self
 9523                        .active_diagnostics
 9524                        .as_ref()
 9525                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9526                })
 9527                .find_map(|entry| {
 9528                    if entry.diagnostic.is_primary
 9529                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9530                        && !entry.range.is_empty()
 9531                        // if we match with the active diagnostic, skip it
 9532                        && Some(entry.diagnostic.group_id)
 9533                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9534                    {
 9535                        Some((entry.range, entry.diagnostic.group_id))
 9536                    } else {
 9537                        None
 9538                    }
 9539                });
 9540
 9541            if let Some((primary_range, group_id)) = group {
 9542                if self.activate_diagnostics(group_id, cx) {
 9543                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9544                        s.select(vec![Selection {
 9545                            id: selection.id,
 9546                            start: primary_range.start,
 9547                            end: primary_range.start,
 9548                            reversed: false,
 9549                            goal: SelectionGoal::None,
 9550                        }]);
 9551                    });
 9552                }
 9553                break;
 9554            } else {
 9555                // Cycle around to the start of the buffer, potentially moving back to the start of
 9556                // the currently active diagnostic.
 9557                active_primary_range.take();
 9558                if direction == Direction::Prev {
 9559                    if search_start == buffer.len() {
 9560                        break;
 9561                    } else {
 9562                        search_start = buffer.len();
 9563                    }
 9564                } else if search_start == 0 {
 9565                    break;
 9566                } else {
 9567                    search_start = 0;
 9568                }
 9569            }
 9570        }
 9571    }
 9572
 9573    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9574        let snapshot = self
 9575            .display_map
 9576            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9577        let selection = self.selections.newest::<Point>(cx);
 9578        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9579    }
 9580
 9581    fn go_to_hunk_after_position(
 9582        &mut self,
 9583        snapshot: &DisplaySnapshot,
 9584        position: Point,
 9585        cx: &mut ViewContext<'_, Editor>,
 9586    ) -> Option<MultiBufferDiffHunk> {
 9587        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9588            snapshot,
 9589            position,
 9590            false,
 9591            snapshot
 9592                .buffer_snapshot
 9593                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9594            cx,
 9595        ) {
 9596            return Some(hunk);
 9597        }
 9598
 9599        let wrapped_point = Point::zero();
 9600        self.go_to_next_hunk_in_direction(
 9601            snapshot,
 9602            wrapped_point,
 9603            true,
 9604            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9605                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9606            ),
 9607            cx,
 9608        )
 9609    }
 9610
 9611    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9612        let snapshot = self
 9613            .display_map
 9614            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9615        let selection = self.selections.newest::<Point>(cx);
 9616
 9617        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9618    }
 9619
 9620    fn go_to_hunk_before_position(
 9621        &mut self,
 9622        snapshot: &DisplaySnapshot,
 9623        position: Point,
 9624        cx: &mut ViewContext<'_, Editor>,
 9625    ) -> Option<MultiBufferDiffHunk> {
 9626        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9627            snapshot,
 9628            position,
 9629            false,
 9630            snapshot
 9631                .buffer_snapshot
 9632                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9633            cx,
 9634        ) {
 9635            return Some(hunk);
 9636        }
 9637
 9638        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9639        self.go_to_next_hunk_in_direction(
 9640            snapshot,
 9641            wrapped_point,
 9642            true,
 9643            snapshot
 9644                .buffer_snapshot
 9645                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9646            cx,
 9647        )
 9648    }
 9649
 9650    fn go_to_next_hunk_in_direction(
 9651        &mut self,
 9652        snapshot: &DisplaySnapshot,
 9653        initial_point: Point,
 9654        is_wrapped: bool,
 9655        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9656        cx: &mut ViewContext<Editor>,
 9657    ) -> Option<MultiBufferDiffHunk> {
 9658        let display_point = initial_point.to_display_point(snapshot);
 9659        let mut hunks = hunks
 9660            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9661            .filter(|(display_hunk, _)| {
 9662                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9663            })
 9664            .dedup();
 9665
 9666        if let Some((display_hunk, hunk)) = hunks.next() {
 9667            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9668                let row = display_hunk.start_display_row();
 9669                let point = DisplayPoint::new(row, 0);
 9670                s.select_display_ranges([point..point]);
 9671            });
 9672
 9673            Some(hunk)
 9674        } else {
 9675            None
 9676        }
 9677    }
 9678
 9679    pub fn go_to_definition(
 9680        &mut self,
 9681        _: &GoToDefinition,
 9682        cx: &mut ViewContext<Self>,
 9683    ) -> Task<Result<Navigated>> {
 9684        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9685        cx.spawn(|editor, mut cx| async move {
 9686            if definition.await? == Navigated::Yes {
 9687                return Ok(Navigated::Yes);
 9688            }
 9689            match editor.update(&mut cx, |editor, cx| {
 9690                editor.find_all_references(&FindAllReferences, cx)
 9691            })? {
 9692                Some(references) => references.await,
 9693                None => Ok(Navigated::No),
 9694            }
 9695        })
 9696    }
 9697
 9698    pub fn go_to_declaration(
 9699        &mut self,
 9700        _: &GoToDeclaration,
 9701        cx: &mut ViewContext<Self>,
 9702    ) -> Task<Result<Navigated>> {
 9703        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9704    }
 9705
 9706    pub fn go_to_declaration_split(
 9707        &mut self,
 9708        _: &GoToDeclaration,
 9709        cx: &mut ViewContext<Self>,
 9710    ) -> Task<Result<Navigated>> {
 9711        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9712    }
 9713
 9714    pub fn go_to_implementation(
 9715        &mut self,
 9716        _: &GoToImplementation,
 9717        cx: &mut ViewContext<Self>,
 9718    ) -> Task<Result<Navigated>> {
 9719        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9720    }
 9721
 9722    pub fn go_to_implementation_split(
 9723        &mut self,
 9724        _: &GoToImplementationSplit,
 9725        cx: &mut ViewContext<Self>,
 9726    ) -> Task<Result<Navigated>> {
 9727        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9728    }
 9729
 9730    pub fn go_to_type_definition(
 9731        &mut self,
 9732        _: &GoToTypeDefinition,
 9733        cx: &mut ViewContext<Self>,
 9734    ) -> Task<Result<Navigated>> {
 9735        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9736    }
 9737
 9738    pub fn go_to_definition_split(
 9739        &mut self,
 9740        _: &GoToDefinitionSplit,
 9741        cx: &mut ViewContext<Self>,
 9742    ) -> Task<Result<Navigated>> {
 9743        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9744    }
 9745
 9746    pub fn go_to_type_definition_split(
 9747        &mut self,
 9748        _: &GoToTypeDefinitionSplit,
 9749        cx: &mut ViewContext<Self>,
 9750    ) -> Task<Result<Navigated>> {
 9751        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9752    }
 9753
 9754    fn go_to_definition_of_kind(
 9755        &mut self,
 9756        kind: GotoDefinitionKind,
 9757        split: bool,
 9758        cx: &mut ViewContext<Self>,
 9759    ) -> Task<Result<Navigated>> {
 9760        let Some(provider) = self.semantics_provider.clone() else {
 9761            return Task::ready(Ok(Navigated::No));
 9762        };
 9763        let head = self.selections.newest::<usize>(cx).head();
 9764        let buffer = self.buffer.read(cx);
 9765        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9766            text_anchor
 9767        } else {
 9768            return Task::ready(Ok(Navigated::No));
 9769        };
 9770
 9771        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9772            return Task::ready(Ok(Navigated::No));
 9773        };
 9774
 9775        cx.spawn(|editor, mut cx| async move {
 9776            let definitions = definitions.await?;
 9777            let navigated = editor
 9778                .update(&mut cx, |editor, cx| {
 9779                    editor.navigate_to_hover_links(
 9780                        Some(kind),
 9781                        definitions
 9782                            .into_iter()
 9783                            .filter(|location| {
 9784                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9785                            })
 9786                            .map(HoverLink::Text)
 9787                            .collect::<Vec<_>>(),
 9788                        split,
 9789                        cx,
 9790                    )
 9791                })?
 9792                .await?;
 9793            anyhow::Ok(navigated)
 9794        })
 9795    }
 9796
 9797    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9798        let position = self.selections.newest_anchor().head();
 9799        let Some((buffer, buffer_position)) =
 9800            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9801        else {
 9802            return;
 9803        };
 9804
 9805        cx.spawn(|editor, mut cx| async move {
 9806            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9807                editor.update(&mut cx, |_, cx| {
 9808                    cx.open_url(&url);
 9809                })
 9810            } else {
 9811                Ok(())
 9812            }
 9813        })
 9814        .detach();
 9815    }
 9816
 9817    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9818        let Some(workspace) = self.workspace() else {
 9819            return;
 9820        };
 9821
 9822        let position = self.selections.newest_anchor().head();
 9823
 9824        let Some((buffer, buffer_position)) =
 9825            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9826        else {
 9827            return;
 9828        };
 9829
 9830        let project = self.project.clone();
 9831
 9832        cx.spawn(|_, mut cx| async move {
 9833            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9834
 9835            if let Some((_, path)) = result {
 9836                workspace
 9837                    .update(&mut cx, |workspace, cx| {
 9838                        workspace.open_resolved_path(path, cx)
 9839                    })?
 9840                    .await?;
 9841            }
 9842            anyhow::Ok(())
 9843        })
 9844        .detach();
 9845    }
 9846
 9847    pub(crate) fn navigate_to_hover_links(
 9848        &mut self,
 9849        kind: Option<GotoDefinitionKind>,
 9850        mut definitions: Vec<HoverLink>,
 9851        split: bool,
 9852        cx: &mut ViewContext<Editor>,
 9853    ) -> Task<Result<Navigated>> {
 9854        // If there is one definition, just open it directly
 9855        if definitions.len() == 1 {
 9856            let definition = definitions.pop().unwrap();
 9857
 9858            enum TargetTaskResult {
 9859                Location(Option<Location>),
 9860                AlreadyNavigated,
 9861            }
 9862
 9863            let target_task = match definition {
 9864                HoverLink::Text(link) => {
 9865                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9866                }
 9867                HoverLink::InlayHint(lsp_location, server_id) => {
 9868                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9869                    cx.background_executor().spawn(async move {
 9870                        let location = computation.await?;
 9871                        Ok(TargetTaskResult::Location(location))
 9872                    })
 9873                }
 9874                HoverLink::Url(url) => {
 9875                    cx.open_url(&url);
 9876                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9877                }
 9878                HoverLink::File(path) => {
 9879                    if let Some(workspace) = self.workspace() {
 9880                        cx.spawn(|_, mut cx| async move {
 9881                            workspace
 9882                                .update(&mut cx, |workspace, cx| {
 9883                                    workspace.open_resolved_path(path, cx)
 9884                                })?
 9885                                .await
 9886                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9887                        })
 9888                    } else {
 9889                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9890                    }
 9891                }
 9892            };
 9893            cx.spawn(|editor, mut cx| async move {
 9894                let target = match target_task.await.context("target resolution task")? {
 9895                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9896                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9897                    TargetTaskResult::Location(Some(target)) => target,
 9898                };
 9899
 9900                editor.update(&mut cx, |editor, cx| {
 9901                    let Some(workspace) = editor.workspace() else {
 9902                        return Navigated::No;
 9903                    };
 9904                    let pane = workspace.read(cx).active_pane().clone();
 9905
 9906                    let range = target.range.to_offset(target.buffer.read(cx));
 9907                    let range = editor.range_for_match(&range);
 9908
 9909                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9910                        let buffer = target.buffer.read(cx);
 9911                        let range = check_multiline_range(buffer, range);
 9912                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9913                            s.select_ranges([range]);
 9914                        });
 9915                    } else {
 9916                        cx.window_context().defer(move |cx| {
 9917                            let target_editor: View<Self> =
 9918                                workspace.update(cx, |workspace, cx| {
 9919                                    let pane = if split {
 9920                                        workspace.adjacent_pane(cx)
 9921                                    } else {
 9922                                        workspace.active_pane().clone()
 9923                                    };
 9924
 9925                                    workspace.open_project_item(
 9926                                        pane,
 9927                                        target.buffer.clone(),
 9928                                        true,
 9929                                        true,
 9930                                        cx,
 9931                                    )
 9932                                });
 9933                            target_editor.update(cx, |target_editor, cx| {
 9934                                // When selecting a definition in a different buffer, disable the nav history
 9935                                // to avoid creating a history entry at the previous cursor location.
 9936                                pane.update(cx, |pane, _| pane.disable_history());
 9937                                let buffer = target.buffer.read(cx);
 9938                                let range = check_multiline_range(buffer, range);
 9939                                target_editor.change_selections(
 9940                                    Some(Autoscroll::focused()),
 9941                                    cx,
 9942                                    |s| {
 9943                                        s.select_ranges([range]);
 9944                                    },
 9945                                );
 9946                                pane.update(cx, |pane, _| pane.enable_history());
 9947                            });
 9948                        });
 9949                    }
 9950                    Navigated::Yes
 9951                })
 9952            })
 9953        } else if !definitions.is_empty() {
 9954            cx.spawn(|editor, mut cx| async move {
 9955                let (title, location_tasks, workspace) = editor
 9956                    .update(&mut cx, |editor, cx| {
 9957                        let tab_kind = match kind {
 9958                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9959                            _ => "Definitions",
 9960                        };
 9961                        let title = definitions
 9962                            .iter()
 9963                            .find_map(|definition| match definition {
 9964                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9965                                    let buffer = origin.buffer.read(cx);
 9966                                    format!(
 9967                                        "{} for {}",
 9968                                        tab_kind,
 9969                                        buffer
 9970                                            .text_for_range(origin.range.clone())
 9971                                            .collect::<String>()
 9972                                    )
 9973                                }),
 9974                                HoverLink::InlayHint(_, _) => None,
 9975                                HoverLink::Url(_) => None,
 9976                                HoverLink::File(_) => None,
 9977                            })
 9978                            .unwrap_or(tab_kind.to_string());
 9979                        let location_tasks = definitions
 9980                            .into_iter()
 9981                            .map(|definition| match definition {
 9982                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9983                                HoverLink::InlayHint(lsp_location, server_id) => {
 9984                                    editor.compute_target_location(lsp_location, server_id, cx)
 9985                                }
 9986                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9987                                HoverLink::File(_) => Task::ready(Ok(None)),
 9988                            })
 9989                            .collect::<Vec<_>>();
 9990                        (title, location_tasks, editor.workspace().clone())
 9991                    })
 9992                    .context("location tasks preparation")?;
 9993
 9994                let locations = future::join_all(location_tasks)
 9995                    .await
 9996                    .into_iter()
 9997                    .filter_map(|location| location.transpose())
 9998                    .collect::<Result<_>>()
 9999                    .context("location tasks")?;
10000
10001                let Some(workspace) = workspace else {
10002                    return Ok(Navigated::No);
10003                };
10004                let opened = workspace
10005                    .update(&mut cx, |workspace, cx| {
10006                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10007                    })
10008                    .ok();
10009
10010                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10011            })
10012        } else {
10013            Task::ready(Ok(Navigated::No))
10014        }
10015    }
10016
10017    fn compute_target_location(
10018        &self,
10019        lsp_location: lsp::Location,
10020        server_id: LanguageServerId,
10021        cx: &mut ViewContext<Self>,
10022    ) -> Task<anyhow::Result<Option<Location>>> {
10023        let Some(project) = self.project.clone() else {
10024            return Task::Ready(Some(Ok(None)));
10025        };
10026
10027        cx.spawn(move |editor, mut cx| async move {
10028            let location_task = editor.update(&mut cx, |_, cx| {
10029                project.update(cx, |project, cx| {
10030                    let language_server_name = project
10031                        .language_server_statuses(cx)
10032                        .find(|(id, _)| server_id == *id)
10033                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10034                    language_server_name.map(|language_server_name| {
10035                        project.open_local_buffer_via_lsp(
10036                            lsp_location.uri.clone(),
10037                            server_id,
10038                            language_server_name,
10039                            cx,
10040                        )
10041                    })
10042                })
10043            })?;
10044            let location = match location_task {
10045                Some(task) => Some({
10046                    let target_buffer_handle = task.await.context("open local buffer")?;
10047                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10048                        let target_start = target_buffer
10049                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10050                        let target_end = target_buffer
10051                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10052                        target_buffer.anchor_after(target_start)
10053                            ..target_buffer.anchor_before(target_end)
10054                    })?;
10055                    Location {
10056                        buffer: target_buffer_handle,
10057                        range,
10058                    }
10059                }),
10060                None => None,
10061            };
10062            Ok(location)
10063        })
10064    }
10065
10066    pub fn find_all_references(
10067        &mut self,
10068        _: &FindAllReferences,
10069        cx: &mut ViewContext<Self>,
10070    ) -> Option<Task<Result<Navigated>>> {
10071        let selection = self.selections.newest::<usize>(cx);
10072        let multi_buffer = self.buffer.read(cx);
10073        let head = selection.head();
10074
10075        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10076        let head_anchor = multi_buffer_snapshot.anchor_at(
10077            head,
10078            if head < selection.tail() {
10079                Bias::Right
10080            } else {
10081                Bias::Left
10082            },
10083        );
10084
10085        match self
10086            .find_all_references_task_sources
10087            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10088        {
10089            Ok(_) => {
10090                log::info!(
10091                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10092                );
10093                return None;
10094            }
10095            Err(i) => {
10096                self.find_all_references_task_sources.insert(i, head_anchor);
10097            }
10098        }
10099
10100        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10101        let workspace = self.workspace()?;
10102        let project = workspace.read(cx).project().clone();
10103        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10104        Some(cx.spawn(|editor, mut cx| async move {
10105            let _cleanup = defer({
10106                let mut cx = cx.clone();
10107                move || {
10108                    let _ = editor.update(&mut cx, |editor, _| {
10109                        if let Ok(i) =
10110                            editor
10111                                .find_all_references_task_sources
10112                                .binary_search_by(|anchor| {
10113                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10114                                })
10115                        {
10116                            editor.find_all_references_task_sources.remove(i);
10117                        }
10118                    });
10119                }
10120            });
10121
10122            let locations = references.await?;
10123            if locations.is_empty() {
10124                return anyhow::Ok(Navigated::No);
10125            }
10126
10127            workspace.update(&mut cx, |workspace, cx| {
10128                let title = locations
10129                    .first()
10130                    .as_ref()
10131                    .map(|location| {
10132                        let buffer = location.buffer.read(cx);
10133                        format!(
10134                            "References to `{}`",
10135                            buffer
10136                                .text_for_range(location.range.clone())
10137                                .collect::<String>()
10138                        )
10139                    })
10140                    .unwrap();
10141                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10142                Navigated::Yes
10143            })
10144        }))
10145    }
10146
10147    /// Opens a multibuffer with the given project locations in it
10148    pub fn open_locations_in_multibuffer(
10149        workspace: &mut Workspace,
10150        mut locations: Vec<Location>,
10151        title: String,
10152        split: bool,
10153        cx: &mut ViewContext<Workspace>,
10154    ) {
10155        // If there are multiple definitions, open them in a multibuffer
10156        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10157        let mut locations = locations.into_iter().peekable();
10158        let mut ranges_to_highlight = Vec::new();
10159        let capability = workspace.project().read(cx).capability();
10160
10161        let excerpt_buffer = cx.new_model(|cx| {
10162            let mut multibuffer = MultiBuffer::new(capability);
10163            while let Some(location) = locations.next() {
10164                let buffer = location.buffer.read(cx);
10165                let mut ranges_for_buffer = Vec::new();
10166                let range = location.range.to_offset(buffer);
10167                ranges_for_buffer.push(range.clone());
10168
10169                while let Some(next_location) = locations.peek() {
10170                    if next_location.buffer == location.buffer {
10171                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10172                        locations.next();
10173                    } else {
10174                        break;
10175                    }
10176                }
10177
10178                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10179                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10180                    location.buffer.clone(),
10181                    ranges_for_buffer,
10182                    DEFAULT_MULTIBUFFER_CONTEXT,
10183                    cx,
10184                ))
10185            }
10186
10187            multibuffer.with_title(title)
10188        });
10189
10190        let editor = cx.new_view(|cx| {
10191            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10192        });
10193        editor.update(cx, |editor, cx| {
10194            if let Some(first_range) = ranges_to_highlight.first() {
10195                editor.change_selections(None, cx, |selections| {
10196                    selections.clear_disjoint();
10197                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10198                });
10199            }
10200            editor.highlight_background::<Self>(
10201                &ranges_to_highlight,
10202                |theme| theme.editor_highlighted_line_background,
10203                cx,
10204            );
10205        });
10206
10207        let item = Box::new(editor);
10208        let item_id = item.item_id();
10209
10210        if split {
10211            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10212        } else {
10213            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10214                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10215                    pane.close_current_preview_item(cx)
10216                } else {
10217                    None
10218                }
10219            });
10220            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10221        }
10222        workspace.active_pane().update(cx, |pane, cx| {
10223            pane.set_preview_item_id(Some(item_id), cx);
10224        });
10225    }
10226
10227    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10228        use language::ToOffset as _;
10229
10230        let provider = self.semantics_provider.clone()?;
10231        let selection = self.selections.newest_anchor().clone();
10232        let (cursor_buffer, cursor_buffer_position) = self
10233            .buffer
10234            .read(cx)
10235            .text_anchor_for_position(selection.head(), cx)?;
10236        let (tail_buffer, cursor_buffer_position_end) = self
10237            .buffer
10238            .read(cx)
10239            .text_anchor_for_position(selection.tail(), cx)?;
10240        if tail_buffer != cursor_buffer {
10241            return None;
10242        }
10243
10244        let snapshot = cursor_buffer.read(cx).snapshot();
10245        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10246        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10247        let prepare_rename = provider
10248            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10249            .unwrap_or_else(|| Task::ready(Ok(None)));
10250        drop(snapshot);
10251
10252        Some(cx.spawn(|this, mut cx| async move {
10253            let rename_range = if let Some(range) = prepare_rename.await? {
10254                Some(range)
10255            } else {
10256                this.update(&mut cx, |this, cx| {
10257                    let buffer = this.buffer.read(cx).snapshot(cx);
10258                    let mut buffer_highlights = this
10259                        .document_highlights_for_position(selection.head(), &buffer)
10260                        .filter(|highlight| {
10261                            highlight.start.excerpt_id == selection.head().excerpt_id
10262                                && highlight.end.excerpt_id == selection.head().excerpt_id
10263                        });
10264                    buffer_highlights
10265                        .next()
10266                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10267                })?
10268            };
10269            if let Some(rename_range) = rename_range {
10270                this.update(&mut cx, |this, cx| {
10271                    let snapshot = cursor_buffer.read(cx).snapshot();
10272                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10273                    let cursor_offset_in_rename_range =
10274                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10275                    let cursor_offset_in_rename_range_end =
10276                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10277
10278                    this.take_rename(false, cx);
10279                    let buffer = this.buffer.read(cx).read(cx);
10280                    let cursor_offset = selection.head().to_offset(&buffer);
10281                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10282                    let rename_end = rename_start + rename_buffer_range.len();
10283                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10284                    let mut old_highlight_id = None;
10285                    let old_name: Arc<str> = buffer
10286                        .chunks(rename_start..rename_end, true)
10287                        .map(|chunk| {
10288                            if old_highlight_id.is_none() {
10289                                old_highlight_id = chunk.syntax_highlight_id;
10290                            }
10291                            chunk.text
10292                        })
10293                        .collect::<String>()
10294                        .into();
10295
10296                    drop(buffer);
10297
10298                    // Position the selection in the rename editor so that it matches the current selection.
10299                    this.show_local_selections = false;
10300                    let rename_editor = cx.new_view(|cx| {
10301                        let mut editor = Editor::single_line(cx);
10302                        editor.buffer.update(cx, |buffer, cx| {
10303                            buffer.edit([(0..0, old_name.clone())], None, cx)
10304                        });
10305                        let rename_selection_range = match cursor_offset_in_rename_range
10306                            .cmp(&cursor_offset_in_rename_range_end)
10307                        {
10308                            Ordering::Equal => {
10309                                editor.select_all(&SelectAll, cx);
10310                                return editor;
10311                            }
10312                            Ordering::Less => {
10313                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10314                            }
10315                            Ordering::Greater => {
10316                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10317                            }
10318                        };
10319                        if rename_selection_range.end > old_name.len() {
10320                            editor.select_all(&SelectAll, cx);
10321                        } else {
10322                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10323                                s.select_ranges([rename_selection_range]);
10324                            });
10325                        }
10326                        editor
10327                    });
10328                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10329                        if e == &EditorEvent::Focused {
10330                            cx.emit(EditorEvent::FocusedIn)
10331                        }
10332                    })
10333                    .detach();
10334
10335                    let write_highlights =
10336                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10337                    let read_highlights =
10338                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10339                    let ranges = write_highlights
10340                        .iter()
10341                        .flat_map(|(_, ranges)| ranges.iter())
10342                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10343                        .cloned()
10344                        .collect();
10345
10346                    this.highlight_text::<Rename>(
10347                        ranges,
10348                        HighlightStyle {
10349                            fade_out: Some(0.6),
10350                            ..Default::default()
10351                        },
10352                        cx,
10353                    );
10354                    let rename_focus_handle = rename_editor.focus_handle(cx);
10355                    cx.focus(&rename_focus_handle);
10356                    let block_id = this.insert_blocks(
10357                        [BlockProperties {
10358                            style: BlockStyle::Flex,
10359                            placement: BlockPlacement::Below(range.start),
10360                            height: 1,
10361                            render: Box::new({
10362                                let rename_editor = rename_editor.clone();
10363                                move |cx: &mut BlockContext| {
10364                                    let mut text_style = cx.editor_style.text.clone();
10365                                    if let Some(highlight_style) = old_highlight_id
10366                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10367                                    {
10368                                        text_style = text_style.highlight(highlight_style);
10369                                    }
10370                                    div()
10371                                        .pl(cx.anchor_x)
10372                                        .child(EditorElement::new(
10373                                            &rename_editor,
10374                                            EditorStyle {
10375                                                background: cx.theme().system().transparent,
10376                                                local_player: cx.editor_style.local_player,
10377                                                text: text_style,
10378                                                scrollbar_width: cx.editor_style.scrollbar_width,
10379                                                syntax: cx.editor_style.syntax.clone(),
10380                                                status: cx.editor_style.status.clone(),
10381                                                inlay_hints_style: HighlightStyle {
10382                                                    font_weight: Some(FontWeight::BOLD),
10383                                                    ..make_inlay_hints_style(cx)
10384                                                },
10385                                                suggestions_style: HighlightStyle {
10386                                                    color: Some(cx.theme().status().predictive),
10387                                                    ..HighlightStyle::default()
10388                                                },
10389                                                ..EditorStyle::default()
10390                                            },
10391                                        ))
10392                                        .into_any_element()
10393                                }
10394                            }),
10395                            priority: 0,
10396                        }],
10397                        Some(Autoscroll::fit()),
10398                        cx,
10399                    )[0];
10400                    this.pending_rename = Some(RenameState {
10401                        range,
10402                        old_name,
10403                        editor: rename_editor,
10404                        block_id,
10405                    });
10406                })?;
10407            }
10408
10409            Ok(())
10410        }))
10411    }
10412
10413    pub fn confirm_rename(
10414        &mut self,
10415        _: &ConfirmRename,
10416        cx: &mut ViewContext<Self>,
10417    ) -> Option<Task<Result<()>>> {
10418        let rename = self.take_rename(false, cx)?;
10419        let workspace = self.workspace()?.downgrade();
10420        let (buffer, start) = self
10421            .buffer
10422            .read(cx)
10423            .text_anchor_for_position(rename.range.start, cx)?;
10424        let (end_buffer, _) = self
10425            .buffer
10426            .read(cx)
10427            .text_anchor_for_position(rename.range.end, cx)?;
10428        if buffer != end_buffer {
10429            return None;
10430        }
10431
10432        let old_name = rename.old_name;
10433        let new_name = rename.editor.read(cx).text(cx);
10434
10435        let rename = self.semantics_provider.as_ref()?.perform_rename(
10436            &buffer,
10437            start,
10438            new_name.clone(),
10439            cx,
10440        )?;
10441
10442        Some(cx.spawn(|editor, mut cx| async move {
10443            let project_transaction = rename.await?;
10444            Self::open_project_transaction(
10445                &editor,
10446                workspace,
10447                project_transaction,
10448                format!("Rename: {}{}", old_name, new_name),
10449                cx.clone(),
10450            )
10451            .await?;
10452
10453            editor.update(&mut cx, |editor, cx| {
10454                editor.refresh_document_highlights(cx);
10455            })?;
10456            Ok(())
10457        }))
10458    }
10459
10460    fn take_rename(
10461        &mut self,
10462        moving_cursor: bool,
10463        cx: &mut ViewContext<Self>,
10464    ) -> Option<RenameState> {
10465        let rename = self.pending_rename.take()?;
10466        if rename.editor.focus_handle(cx).is_focused(cx) {
10467            cx.focus(&self.focus_handle);
10468        }
10469
10470        self.remove_blocks(
10471            [rename.block_id].into_iter().collect(),
10472            Some(Autoscroll::fit()),
10473            cx,
10474        );
10475        self.clear_highlights::<Rename>(cx);
10476        self.show_local_selections = true;
10477
10478        if moving_cursor {
10479            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10480                editor.selections.newest::<usize>(cx).head()
10481            });
10482
10483            // Update the selection to match the position of the selection inside
10484            // the rename editor.
10485            let snapshot = self.buffer.read(cx).read(cx);
10486            let rename_range = rename.range.to_offset(&snapshot);
10487            let cursor_in_editor = snapshot
10488                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10489                .min(rename_range.end);
10490            drop(snapshot);
10491
10492            self.change_selections(None, cx, |s| {
10493                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10494            });
10495        } else {
10496            self.refresh_document_highlights(cx);
10497        }
10498
10499        Some(rename)
10500    }
10501
10502    pub fn pending_rename(&self) -> Option<&RenameState> {
10503        self.pending_rename.as_ref()
10504    }
10505
10506    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10507        let project = match &self.project {
10508            Some(project) => project.clone(),
10509            None => return None,
10510        };
10511
10512        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10513    }
10514
10515    fn format_selections(
10516        &mut self,
10517        _: &FormatSelections,
10518        cx: &mut ViewContext<Self>,
10519    ) -> Option<Task<Result<()>>> {
10520        let project = match &self.project {
10521            Some(project) => project.clone(),
10522            None => return None,
10523        };
10524
10525        let selections = self
10526            .selections
10527            .all_adjusted(cx)
10528            .into_iter()
10529            .filter(|s| !s.is_empty())
10530            .collect_vec();
10531
10532        Some(self.perform_format(
10533            project,
10534            FormatTrigger::Manual,
10535            FormatTarget::Ranges(selections),
10536            cx,
10537        ))
10538    }
10539
10540    fn perform_format(
10541        &mut self,
10542        project: Model<Project>,
10543        trigger: FormatTrigger,
10544        target: FormatTarget,
10545        cx: &mut ViewContext<Self>,
10546    ) -> Task<Result<()>> {
10547        let buffer = self.buffer().clone();
10548        let mut buffers = buffer.read(cx).all_buffers();
10549        if trigger == FormatTrigger::Save {
10550            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10551        }
10552
10553        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10554        let format = project.update(cx, |project, cx| {
10555            project.format(buffers, true, trigger, target, cx)
10556        });
10557
10558        cx.spawn(|_, mut cx| async move {
10559            let transaction = futures::select_biased! {
10560                () = timeout => {
10561                    log::warn!("timed out waiting for formatting");
10562                    None
10563                }
10564                transaction = format.log_err().fuse() => transaction,
10565            };
10566
10567            buffer
10568                .update(&mut cx, |buffer, cx| {
10569                    if let Some(transaction) = transaction {
10570                        if !buffer.is_singleton() {
10571                            buffer.push_transaction(&transaction.0, cx);
10572                        }
10573                    }
10574
10575                    cx.notify();
10576                })
10577                .ok();
10578
10579            Ok(())
10580        })
10581    }
10582
10583    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10584        if let Some(project) = self.project.clone() {
10585            self.buffer.update(cx, |multi_buffer, cx| {
10586                project.update(cx, |project, cx| {
10587                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10588                });
10589            })
10590        }
10591    }
10592
10593    fn cancel_language_server_work(
10594        &mut self,
10595        _: &actions::CancelLanguageServerWork,
10596        cx: &mut ViewContext<Self>,
10597    ) {
10598        if let Some(project) = self.project.clone() {
10599            self.buffer.update(cx, |multi_buffer, cx| {
10600                project.update(cx, |project, cx| {
10601                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10602                });
10603            })
10604        }
10605    }
10606
10607    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10608        cx.show_character_palette();
10609    }
10610
10611    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10612        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10613            let buffer = self.buffer.read(cx).snapshot(cx);
10614            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10615            let is_valid = buffer
10616                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10617                .any(|entry| {
10618                    entry.diagnostic.is_primary
10619                        && !entry.range.is_empty()
10620                        && entry.range.start == primary_range_start
10621                        && entry.diagnostic.message == active_diagnostics.primary_message
10622                });
10623
10624            if is_valid != active_diagnostics.is_valid {
10625                active_diagnostics.is_valid = is_valid;
10626                let mut new_styles = HashMap::default();
10627                for (block_id, diagnostic) in &active_diagnostics.blocks {
10628                    new_styles.insert(
10629                        *block_id,
10630                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10631                    );
10632                }
10633                self.display_map.update(cx, |display_map, _cx| {
10634                    display_map.replace_blocks(new_styles)
10635                });
10636            }
10637        }
10638    }
10639
10640    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10641        self.dismiss_diagnostics(cx);
10642        let snapshot = self.snapshot(cx);
10643        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10644            let buffer = self.buffer.read(cx).snapshot(cx);
10645
10646            let mut primary_range = None;
10647            let mut primary_message = None;
10648            let mut group_end = Point::zero();
10649            let diagnostic_group = buffer
10650                .diagnostic_group::<MultiBufferPoint>(group_id)
10651                .filter_map(|entry| {
10652                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10653                        && (entry.range.start.row == entry.range.end.row
10654                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10655                    {
10656                        return None;
10657                    }
10658                    if entry.range.end > group_end {
10659                        group_end = entry.range.end;
10660                    }
10661                    if entry.diagnostic.is_primary {
10662                        primary_range = Some(entry.range.clone());
10663                        primary_message = Some(entry.diagnostic.message.clone());
10664                    }
10665                    Some(entry)
10666                })
10667                .collect::<Vec<_>>();
10668            let primary_range = primary_range?;
10669            let primary_message = primary_message?;
10670            let primary_range =
10671                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10672
10673            let blocks = display_map
10674                .insert_blocks(
10675                    diagnostic_group.iter().map(|entry| {
10676                        let diagnostic = entry.diagnostic.clone();
10677                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10678                        BlockProperties {
10679                            style: BlockStyle::Fixed,
10680                            placement: BlockPlacement::Below(
10681                                buffer.anchor_after(entry.range.start),
10682                            ),
10683                            height: message_height,
10684                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10685                            priority: 0,
10686                        }
10687                    }),
10688                    cx,
10689                )
10690                .into_iter()
10691                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10692                .collect();
10693
10694            Some(ActiveDiagnosticGroup {
10695                primary_range,
10696                primary_message,
10697                group_id,
10698                blocks,
10699                is_valid: true,
10700            })
10701        });
10702        self.active_diagnostics.is_some()
10703    }
10704
10705    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10706        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10707            self.display_map.update(cx, |display_map, cx| {
10708                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10709            });
10710            cx.notify();
10711        }
10712    }
10713
10714    pub fn set_selections_from_remote(
10715        &mut self,
10716        selections: Vec<Selection<Anchor>>,
10717        pending_selection: Option<Selection<Anchor>>,
10718        cx: &mut ViewContext<Self>,
10719    ) {
10720        let old_cursor_position = self.selections.newest_anchor().head();
10721        self.selections.change_with(cx, |s| {
10722            s.select_anchors(selections);
10723            if let Some(pending_selection) = pending_selection {
10724                s.set_pending(pending_selection, SelectMode::Character);
10725            } else {
10726                s.clear_pending();
10727            }
10728        });
10729        self.selections_did_change(false, &old_cursor_position, true, cx);
10730    }
10731
10732    fn push_to_selection_history(&mut self) {
10733        self.selection_history.push(SelectionHistoryEntry {
10734            selections: self.selections.disjoint_anchors(),
10735            select_next_state: self.select_next_state.clone(),
10736            select_prev_state: self.select_prev_state.clone(),
10737            add_selections_state: self.add_selections_state.clone(),
10738        });
10739    }
10740
10741    pub fn transact(
10742        &mut self,
10743        cx: &mut ViewContext<Self>,
10744        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10745    ) -> Option<TransactionId> {
10746        self.start_transaction_at(Instant::now(), cx);
10747        update(self, cx);
10748        self.end_transaction_at(Instant::now(), cx)
10749    }
10750
10751    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10752        self.end_selection(cx);
10753        if let Some(tx_id) = self
10754            .buffer
10755            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10756        {
10757            self.selection_history
10758                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10759            cx.emit(EditorEvent::TransactionBegun {
10760                transaction_id: tx_id,
10761            })
10762        }
10763    }
10764
10765    fn end_transaction_at(
10766        &mut self,
10767        now: Instant,
10768        cx: &mut ViewContext<Self>,
10769    ) -> Option<TransactionId> {
10770        if let Some(transaction_id) = self
10771            .buffer
10772            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10773        {
10774            if let Some((_, end_selections)) =
10775                self.selection_history.transaction_mut(transaction_id)
10776            {
10777                *end_selections = Some(self.selections.disjoint_anchors());
10778            } else {
10779                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10780            }
10781
10782            cx.emit(EditorEvent::Edited { transaction_id });
10783            Some(transaction_id)
10784        } else {
10785            None
10786        }
10787    }
10788
10789    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10790        let selection = self.selections.newest::<Point>(cx);
10791
10792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10793        let range = if selection.is_empty() {
10794            let point = selection.head().to_display_point(&display_map);
10795            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10796            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10797                .to_point(&display_map);
10798            start..end
10799        } else {
10800            selection.range()
10801        };
10802        if display_map.folds_in_range(range).next().is_some() {
10803            self.unfold_lines(&Default::default(), cx)
10804        } else {
10805            self.fold(&Default::default(), cx)
10806        }
10807    }
10808
10809    pub fn toggle_fold_recursive(
10810        &mut self,
10811        _: &actions::ToggleFoldRecursive,
10812        cx: &mut ViewContext<Self>,
10813    ) {
10814        let selection = self.selections.newest::<Point>(cx);
10815
10816        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10817        let range = if selection.is_empty() {
10818            let point = selection.head().to_display_point(&display_map);
10819            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10820            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10821                .to_point(&display_map);
10822            start..end
10823        } else {
10824            selection.range()
10825        };
10826        if display_map.folds_in_range(range).next().is_some() {
10827            self.unfold_recursive(&Default::default(), cx)
10828        } else {
10829            self.fold_recursive(&Default::default(), cx)
10830        }
10831    }
10832
10833    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10834        let mut fold_ranges = Vec::new();
10835        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10836        let selections = self.selections.all_adjusted(cx);
10837
10838        for selection in selections {
10839            let range = selection.range().sorted();
10840            let buffer_start_row = range.start.row;
10841
10842            if range.start.row != range.end.row {
10843                let mut found = false;
10844                let mut row = range.start.row;
10845                while row <= range.end.row {
10846                    if let Some((foldable_range, fold_text)) =
10847                        { display_map.foldable_range(MultiBufferRow(row)) }
10848                    {
10849                        found = true;
10850                        row = foldable_range.end.row + 1;
10851                        fold_ranges.push((foldable_range, fold_text));
10852                    } else {
10853                        row += 1
10854                    }
10855                }
10856                if found {
10857                    continue;
10858                }
10859            }
10860
10861            for row in (0..=range.start.row).rev() {
10862                if let Some((foldable_range, fold_text)) =
10863                    display_map.foldable_range(MultiBufferRow(row))
10864                {
10865                    if foldable_range.end.row >= buffer_start_row {
10866                        fold_ranges.push((foldable_range, fold_text));
10867                        if row <= range.start.row {
10868                            break;
10869                        }
10870                    }
10871                }
10872            }
10873        }
10874
10875        self.fold_ranges(fold_ranges, true, cx);
10876    }
10877
10878    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10879        let fold_at_level = fold_at.level;
10880        let snapshot = self.buffer.read(cx).snapshot(cx);
10881        let mut fold_ranges = Vec::new();
10882        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10883
10884        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10885            while start_row < end_row {
10886                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10887                    Some(foldable_range) => {
10888                        let nested_start_row = foldable_range.0.start.row + 1;
10889                        let nested_end_row = foldable_range.0.end.row;
10890
10891                        if current_level < fold_at_level {
10892                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10893                        } else if current_level == fold_at_level {
10894                            fold_ranges.push(foldable_range);
10895                        }
10896
10897                        start_row = nested_end_row + 1;
10898                    }
10899                    None => start_row += 1,
10900                }
10901            }
10902        }
10903
10904        self.fold_ranges(fold_ranges, true, cx);
10905    }
10906
10907    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10908        let mut fold_ranges = Vec::new();
10909        let snapshot = self.buffer.read(cx).snapshot(cx);
10910
10911        for row in 0..snapshot.max_buffer_row().0 {
10912            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10913                fold_ranges.push(foldable_range);
10914            }
10915        }
10916
10917        self.fold_ranges(fold_ranges, true, cx);
10918    }
10919
10920    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10921        let mut fold_ranges = Vec::new();
10922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10923        let selections = self.selections.all_adjusted(cx);
10924
10925        for selection in selections {
10926            let range = selection.range().sorted();
10927            let buffer_start_row = range.start.row;
10928
10929            if range.start.row != range.end.row {
10930                let mut found = false;
10931                for row in range.start.row..=range.end.row {
10932                    if let Some((foldable_range, fold_text)) =
10933                        { display_map.foldable_range(MultiBufferRow(row)) }
10934                    {
10935                        found = true;
10936                        fold_ranges.push((foldable_range, fold_text));
10937                    }
10938                }
10939                if found {
10940                    continue;
10941                }
10942            }
10943
10944            for row in (0..=range.start.row).rev() {
10945                if let Some((foldable_range, fold_text)) =
10946                    display_map.foldable_range(MultiBufferRow(row))
10947                {
10948                    if foldable_range.end.row >= buffer_start_row {
10949                        fold_ranges.push((foldable_range, fold_text));
10950                    } else {
10951                        break;
10952                    }
10953                }
10954            }
10955        }
10956
10957        self.fold_ranges(fold_ranges, true, cx);
10958    }
10959
10960    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10961        let buffer_row = fold_at.buffer_row;
10962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10963
10964        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10965            let autoscroll = self
10966                .selections
10967                .all::<Point>(cx)
10968                .iter()
10969                .any(|selection| fold_range.overlaps(&selection.range()));
10970
10971            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10972        }
10973    }
10974
10975    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10977        let buffer = &display_map.buffer_snapshot;
10978        let selections = self.selections.all::<Point>(cx);
10979        let ranges = selections
10980            .iter()
10981            .map(|s| {
10982                let range = s.display_range(&display_map).sorted();
10983                let mut start = range.start.to_point(&display_map);
10984                let mut end = range.end.to_point(&display_map);
10985                start.column = 0;
10986                end.column = buffer.line_len(MultiBufferRow(end.row));
10987                start..end
10988            })
10989            .collect::<Vec<_>>();
10990
10991        self.unfold_ranges(ranges, true, true, cx);
10992    }
10993
10994    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10995        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10996        let selections = self.selections.all::<Point>(cx);
10997        let ranges = selections
10998            .iter()
10999            .map(|s| {
11000                let mut range = s.display_range(&display_map).sorted();
11001                *range.start.column_mut() = 0;
11002                *range.end.column_mut() = display_map.line_len(range.end.row());
11003                let start = range.start.to_point(&display_map);
11004                let end = range.end.to_point(&display_map);
11005                start..end
11006            })
11007            .collect::<Vec<_>>();
11008
11009        self.unfold_ranges(ranges, true, true, cx);
11010    }
11011
11012    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11014
11015        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11016            ..Point::new(
11017                unfold_at.buffer_row.0,
11018                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11019            );
11020
11021        let autoscroll = self
11022            .selections
11023            .all::<Point>(cx)
11024            .iter()
11025            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11026
11027        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
11028    }
11029
11030    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11031        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11032        self.unfold_ranges(
11033            [Point::zero()..display_map.max_point().to_point(&display_map)],
11034            true,
11035            true,
11036            cx,
11037        );
11038    }
11039
11040    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11041        let selections = self.selections.all::<Point>(cx);
11042        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11043        let line_mode = self.selections.line_mode;
11044        let ranges = selections.into_iter().map(|s| {
11045            if line_mode {
11046                let start = Point::new(s.start.row, 0);
11047                let end = Point::new(
11048                    s.end.row,
11049                    display_map
11050                        .buffer_snapshot
11051                        .line_len(MultiBufferRow(s.end.row)),
11052                );
11053                (start..end, display_map.fold_placeholder.clone())
11054            } else {
11055                (s.start..s.end, display_map.fold_placeholder.clone())
11056            }
11057        });
11058        self.fold_ranges(ranges, true, cx);
11059    }
11060
11061    pub fn fold_ranges<T: ToOffset + Clone>(
11062        &mut self,
11063        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11064        auto_scroll: bool,
11065        cx: &mut ViewContext<Self>,
11066    ) {
11067        let mut fold_ranges = Vec::new();
11068        let mut buffers_affected = HashMap::default();
11069        let multi_buffer = self.buffer().read(cx);
11070        for (fold_range, fold_text) in ranges {
11071            if let Some((_, buffer, _)) =
11072                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11073            {
11074                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11075            };
11076            fold_ranges.push((fold_range, fold_text));
11077        }
11078
11079        let mut ranges = fold_ranges.into_iter().peekable();
11080        if ranges.peek().is_some() {
11081            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11082
11083            if auto_scroll {
11084                self.request_autoscroll(Autoscroll::fit(), cx);
11085            }
11086
11087            for buffer in buffers_affected.into_values() {
11088                self.sync_expanded_diff_hunks(buffer, cx);
11089            }
11090
11091            cx.notify();
11092
11093            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11094                // Clear diagnostics block when folding a range that contains it.
11095                let snapshot = self.snapshot(cx);
11096                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11097                    drop(snapshot);
11098                    self.active_diagnostics = Some(active_diagnostics);
11099                    self.dismiss_diagnostics(cx);
11100                } else {
11101                    self.active_diagnostics = Some(active_diagnostics);
11102                }
11103            }
11104
11105            self.scrollbar_marker_state.dirty = true;
11106        }
11107    }
11108
11109    pub fn unfold_ranges<T: ToOffset + Clone>(
11110        &mut self,
11111        ranges: impl IntoIterator<Item = Range<T>>,
11112        inclusive: bool,
11113        auto_scroll: bool,
11114        cx: &mut ViewContext<Self>,
11115    ) {
11116        let mut unfold_ranges = Vec::new();
11117        let mut buffers_affected = HashMap::default();
11118        let multi_buffer = self.buffer().read(cx);
11119        for range in ranges {
11120            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11121                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11122            };
11123            unfold_ranges.push(range);
11124        }
11125
11126        let mut ranges = unfold_ranges.into_iter().peekable();
11127        if ranges.peek().is_some() {
11128            self.display_map
11129                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11130            if auto_scroll {
11131                self.request_autoscroll(Autoscroll::fit(), cx);
11132            }
11133
11134            for buffer in buffers_affected.into_values() {
11135                self.sync_expanded_diff_hunks(buffer, cx);
11136            }
11137
11138            cx.notify();
11139            self.scrollbar_marker_state.dirty = true;
11140            self.active_indent_guides_state.dirty = true;
11141        }
11142    }
11143
11144    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11145        self.display_map.read(cx).fold_placeholder.clone()
11146    }
11147
11148    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11149        if hovered != self.gutter_hovered {
11150            self.gutter_hovered = hovered;
11151            cx.notify();
11152        }
11153    }
11154
11155    pub fn insert_blocks(
11156        &mut self,
11157        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11158        autoscroll: Option<Autoscroll>,
11159        cx: &mut ViewContext<Self>,
11160    ) -> Vec<CustomBlockId> {
11161        let blocks = self
11162            .display_map
11163            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11164        if let Some(autoscroll) = autoscroll {
11165            self.request_autoscroll(autoscroll, cx);
11166        }
11167        cx.notify();
11168        blocks
11169    }
11170
11171    pub fn resize_blocks(
11172        &mut self,
11173        heights: HashMap<CustomBlockId, u32>,
11174        autoscroll: Option<Autoscroll>,
11175        cx: &mut ViewContext<Self>,
11176    ) {
11177        self.display_map
11178            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11179        if let Some(autoscroll) = autoscroll {
11180            self.request_autoscroll(autoscroll, cx);
11181        }
11182        cx.notify();
11183    }
11184
11185    pub fn replace_blocks(
11186        &mut self,
11187        renderers: HashMap<CustomBlockId, RenderBlock>,
11188        autoscroll: Option<Autoscroll>,
11189        cx: &mut ViewContext<Self>,
11190    ) {
11191        self.display_map
11192            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11193        if let Some(autoscroll) = autoscroll {
11194            self.request_autoscroll(autoscroll, cx);
11195        }
11196        cx.notify();
11197    }
11198
11199    pub fn remove_blocks(
11200        &mut self,
11201        block_ids: HashSet<CustomBlockId>,
11202        autoscroll: Option<Autoscroll>,
11203        cx: &mut ViewContext<Self>,
11204    ) {
11205        self.display_map.update(cx, |display_map, cx| {
11206            display_map.remove_blocks(block_ids, cx)
11207        });
11208        if let Some(autoscroll) = autoscroll {
11209            self.request_autoscroll(autoscroll, cx);
11210        }
11211        cx.notify();
11212    }
11213
11214    pub fn row_for_block(
11215        &self,
11216        block_id: CustomBlockId,
11217        cx: &mut ViewContext<Self>,
11218    ) -> Option<DisplayRow> {
11219        self.display_map
11220            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11221    }
11222
11223    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11224        self.focused_block = Some(focused_block);
11225    }
11226
11227    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11228        self.focused_block.take()
11229    }
11230
11231    pub fn insert_creases(
11232        &mut self,
11233        creases: impl IntoIterator<Item = Crease>,
11234        cx: &mut ViewContext<Self>,
11235    ) -> Vec<CreaseId> {
11236        self.display_map
11237            .update(cx, |map, cx| map.insert_creases(creases, cx))
11238    }
11239
11240    pub fn remove_creases(
11241        &mut self,
11242        ids: impl IntoIterator<Item = CreaseId>,
11243        cx: &mut ViewContext<Self>,
11244    ) {
11245        self.display_map
11246            .update(cx, |map, cx| map.remove_creases(ids, cx));
11247    }
11248
11249    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11250        self.display_map
11251            .update(cx, |map, cx| map.snapshot(cx))
11252            .longest_row()
11253    }
11254
11255    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11256        self.display_map
11257            .update(cx, |map, cx| map.snapshot(cx))
11258            .max_point()
11259    }
11260
11261    pub fn text(&self, cx: &AppContext) -> String {
11262        self.buffer.read(cx).read(cx).text()
11263    }
11264
11265    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11266        let text = self.text(cx);
11267        let text = text.trim();
11268
11269        if text.is_empty() {
11270            return None;
11271        }
11272
11273        Some(text.to_string())
11274    }
11275
11276    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11277        self.transact(cx, |this, cx| {
11278            this.buffer
11279                .read(cx)
11280                .as_singleton()
11281                .expect("you can only call set_text on editors for singleton buffers")
11282                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11283        });
11284    }
11285
11286    pub fn display_text(&self, cx: &mut AppContext) -> String {
11287        self.display_map
11288            .update(cx, |map, cx| map.snapshot(cx))
11289            .text()
11290    }
11291
11292    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11293        let mut wrap_guides = smallvec::smallvec![];
11294
11295        if self.show_wrap_guides == Some(false) {
11296            return wrap_guides;
11297        }
11298
11299        let settings = self.buffer.read(cx).settings_at(0, cx);
11300        if settings.show_wrap_guides {
11301            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11302                wrap_guides.push((soft_wrap as usize, true));
11303            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11304                wrap_guides.push((soft_wrap as usize, true));
11305            }
11306            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11307        }
11308
11309        wrap_guides
11310    }
11311
11312    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11313        let settings = self.buffer.read(cx).settings_at(0, cx);
11314        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11315        match mode {
11316            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11317                SoftWrap::None
11318            }
11319            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11320            language_settings::SoftWrap::PreferredLineLength => {
11321                SoftWrap::Column(settings.preferred_line_length)
11322            }
11323            language_settings::SoftWrap::Bounded => {
11324                SoftWrap::Bounded(settings.preferred_line_length)
11325            }
11326        }
11327    }
11328
11329    pub fn set_soft_wrap_mode(
11330        &mut self,
11331        mode: language_settings::SoftWrap,
11332        cx: &mut ViewContext<Self>,
11333    ) {
11334        self.soft_wrap_mode_override = Some(mode);
11335        cx.notify();
11336    }
11337
11338    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11339        self.text_style_refinement = Some(style);
11340    }
11341
11342    /// called by the Element so we know what style we were most recently rendered with.
11343    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11344        let rem_size = cx.rem_size();
11345        self.display_map.update(cx, |map, cx| {
11346            map.set_font(
11347                style.text.font(),
11348                style.text.font_size.to_pixels(rem_size),
11349                cx,
11350            )
11351        });
11352        self.style = Some(style);
11353    }
11354
11355    pub fn style(&self) -> Option<&EditorStyle> {
11356        self.style.as_ref()
11357    }
11358
11359    // Called by the element. This method is not designed to be called outside of the editor
11360    // element's layout code because it does not notify when rewrapping is computed synchronously.
11361    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11362        self.display_map
11363            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11364    }
11365
11366    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11367        if self.soft_wrap_mode_override.is_some() {
11368            self.soft_wrap_mode_override.take();
11369        } else {
11370            let soft_wrap = match self.soft_wrap_mode(cx) {
11371                SoftWrap::GitDiff => return,
11372                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11373                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11374                    language_settings::SoftWrap::None
11375                }
11376            };
11377            self.soft_wrap_mode_override = Some(soft_wrap);
11378        }
11379        cx.notify();
11380    }
11381
11382    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11383        let Some(workspace) = self.workspace() else {
11384            return;
11385        };
11386        let fs = workspace.read(cx).app_state().fs.clone();
11387        let current_show = TabBarSettings::get_global(cx).show;
11388        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11389            setting.show = Some(!current_show);
11390        });
11391    }
11392
11393    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11394        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11395            self.buffer
11396                .read(cx)
11397                .settings_at(0, cx)
11398                .indent_guides
11399                .enabled
11400        });
11401        self.show_indent_guides = Some(!currently_enabled);
11402        cx.notify();
11403    }
11404
11405    fn should_show_indent_guides(&self) -> Option<bool> {
11406        self.show_indent_guides
11407    }
11408
11409    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11410        let mut editor_settings = EditorSettings::get_global(cx).clone();
11411        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11412        EditorSettings::override_global(editor_settings, cx);
11413    }
11414
11415    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11416        self.use_relative_line_numbers
11417            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11418    }
11419
11420    pub fn toggle_relative_line_numbers(
11421        &mut self,
11422        _: &ToggleRelativeLineNumbers,
11423        cx: &mut ViewContext<Self>,
11424    ) {
11425        let is_relative = self.should_use_relative_line_numbers(cx);
11426        self.set_relative_line_number(Some(!is_relative), cx)
11427    }
11428
11429    pub fn set_relative_line_number(
11430        &mut self,
11431        is_relative: Option<bool>,
11432        cx: &mut ViewContext<Self>,
11433    ) {
11434        self.use_relative_line_numbers = is_relative;
11435        cx.notify();
11436    }
11437
11438    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11439        self.show_gutter = show_gutter;
11440        cx.notify();
11441    }
11442
11443    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11444        self.show_line_numbers = Some(show_line_numbers);
11445        cx.notify();
11446    }
11447
11448    pub fn set_show_git_diff_gutter(
11449        &mut self,
11450        show_git_diff_gutter: bool,
11451        cx: &mut ViewContext<Self>,
11452    ) {
11453        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11454        cx.notify();
11455    }
11456
11457    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11458        self.show_code_actions = Some(show_code_actions);
11459        cx.notify();
11460    }
11461
11462    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11463        self.show_runnables = Some(show_runnables);
11464        cx.notify();
11465    }
11466
11467    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11468        if self.display_map.read(cx).masked != masked {
11469            self.display_map.update(cx, |map, _| map.masked = masked);
11470        }
11471        cx.notify()
11472    }
11473
11474    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11475        self.show_wrap_guides = Some(show_wrap_guides);
11476        cx.notify();
11477    }
11478
11479    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11480        self.show_indent_guides = Some(show_indent_guides);
11481        cx.notify();
11482    }
11483
11484    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11485        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11486            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11487                if let Some(dir) = file.abs_path(cx).parent() {
11488                    return Some(dir.to_owned());
11489                }
11490            }
11491
11492            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11493                return Some(project_path.path.to_path_buf());
11494            }
11495        }
11496
11497        None
11498    }
11499
11500    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11501        self.active_excerpt(cx)?
11502            .1
11503            .read(cx)
11504            .file()
11505            .and_then(|f| f.as_local())
11506    }
11507
11508    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11509        if let Some(target) = self.target_file(cx) {
11510            cx.reveal_path(&target.abs_path(cx));
11511        }
11512    }
11513
11514    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11515        if let Some(file) = self.target_file(cx) {
11516            if let Some(path) = file.abs_path(cx).to_str() {
11517                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11518            }
11519        }
11520    }
11521
11522    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11523        if let Some(file) = self.target_file(cx) {
11524            if let Some(path) = file.path().to_str() {
11525                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11526            }
11527        }
11528    }
11529
11530    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11531        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11532
11533        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11534            self.start_git_blame(true, cx);
11535        }
11536
11537        cx.notify();
11538    }
11539
11540    pub fn toggle_git_blame_inline(
11541        &mut self,
11542        _: &ToggleGitBlameInline,
11543        cx: &mut ViewContext<Self>,
11544    ) {
11545        self.toggle_git_blame_inline_internal(true, cx);
11546        cx.notify();
11547    }
11548
11549    pub fn git_blame_inline_enabled(&self) -> bool {
11550        self.git_blame_inline_enabled
11551    }
11552
11553    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11554        self.show_selection_menu = self
11555            .show_selection_menu
11556            .map(|show_selections_menu| !show_selections_menu)
11557            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11558
11559        cx.notify();
11560    }
11561
11562    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11563        self.show_selection_menu
11564            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11565    }
11566
11567    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11568        if let Some(project) = self.project.as_ref() {
11569            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11570                return;
11571            };
11572
11573            if buffer.read(cx).file().is_none() {
11574                return;
11575            }
11576
11577            let focused = self.focus_handle(cx).contains_focused(cx);
11578
11579            let project = project.clone();
11580            let blame =
11581                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11582            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11583            self.blame = Some(blame);
11584        }
11585    }
11586
11587    fn toggle_git_blame_inline_internal(
11588        &mut self,
11589        user_triggered: bool,
11590        cx: &mut ViewContext<Self>,
11591    ) {
11592        if self.git_blame_inline_enabled {
11593            self.git_blame_inline_enabled = false;
11594            self.show_git_blame_inline = false;
11595            self.show_git_blame_inline_delay_task.take();
11596        } else {
11597            self.git_blame_inline_enabled = true;
11598            self.start_git_blame_inline(user_triggered, cx);
11599        }
11600
11601        cx.notify();
11602    }
11603
11604    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11605        self.start_git_blame(user_triggered, cx);
11606
11607        if ProjectSettings::get_global(cx)
11608            .git
11609            .inline_blame_delay()
11610            .is_some()
11611        {
11612            self.start_inline_blame_timer(cx);
11613        } else {
11614            self.show_git_blame_inline = true
11615        }
11616    }
11617
11618    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11619        self.blame.as_ref()
11620    }
11621
11622    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11623        self.show_git_blame_gutter && self.has_blame_entries(cx)
11624    }
11625
11626    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11627        self.show_git_blame_inline
11628            && self.focus_handle.is_focused(cx)
11629            && !self.newest_selection_head_on_empty_line(cx)
11630            && self.has_blame_entries(cx)
11631    }
11632
11633    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11634        self.blame()
11635            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11636    }
11637
11638    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11639        let cursor_anchor = self.selections.newest_anchor().head();
11640
11641        let snapshot = self.buffer.read(cx).snapshot(cx);
11642        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11643
11644        snapshot.line_len(buffer_row) == 0
11645    }
11646
11647    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11648        let buffer_and_selection = maybe!({
11649            let selection = self.selections.newest::<Point>(cx);
11650            let selection_range = selection.range();
11651
11652            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11653                (buffer, selection_range.start.row..selection_range.end.row)
11654            } else {
11655                let buffer_ranges = self
11656                    .buffer()
11657                    .read(cx)
11658                    .range_to_buffer_ranges(selection_range, cx);
11659
11660                let (buffer, range, _) = if selection.reversed {
11661                    buffer_ranges.first()
11662                } else {
11663                    buffer_ranges.last()
11664                }?;
11665
11666                let snapshot = buffer.read(cx).snapshot();
11667                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11668                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11669                (buffer.clone(), selection)
11670            };
11671
11672            Some((buffer, selection))
11673        });
11674
11675        let Some((buffer, selection)) = buffer_and_selection else {
11676            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11677        };
11678
11679        let Some(project) = self.project.as_ref() else {
11680            return Task::ready(Err(anyhow!("editor does not have project")));
11681        };
11682
11683        project.update(cx, |project, cx| {
11684            project.get_permalink_to_line(&buffer, selection, cx)
11685        })
11686    }
11687
11688    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11689        let permalink_task = self.get_permalink_to_line(cx);
11690        let workspace = self.workspace();
11691
11692        cx.spawn(|_, mut cx| async move {
11693            match permalink_task.await {
11694                Ok(permalink) => {
11695                    cx.update(|cx| {
11696                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11697                    })
11698                    .ok();
11699                }
11700                Err(err) => {
11701                    let message = format!("Failed to copy permalink: {err}");
11702
11703                    Err::<(), anyhow::Error>(err).log_err();
11704
11705                    if let Some(workspace) = workspace {
11706                        workspace
11707                            .update(&mut cx, |workspace, cx| {
11708                                struct CopyPermalinkToLine;
11709
11710                                workspace.show_toast(
11711                                    Toast::new(
11712                                        NotificationId::unique::<CopyPermalinkToLine>(),
11713                                        message,
11714                                    ),
11715                                    cx,
11716                                )
11717                            })
11718                            .ok();
11719                    }
11720                }
11721            }
11722        })
11723        .detach();
11724    }
11725
11726    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11727        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11728        if let Some(file) = self.target_file(cx) {
11729            if let Some(path) = file.path().to_str() {
11730                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11731            }
11732        }
11733    }
11734
11735    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11736        let permalink_task = self.get_permalink_to_line(cx);
11737        let workspace = self.workspace();
11738
11739        cx.spawn(|_, mut cx| async move {
11740            match permalink_task.await {
11741                Ok(permalink) => {
11742                    cx.update(|cx| {
11743                        cx.open_url(permalink.as_ref());
11744                    })
11745                    .ok();
11746                }
11747                Err(err) => {
11748                    let message = format!("Failed to open permalink: {err}");
11749
11750                    Err::<(), anyhow::Error>(err).log_err();
11751
11752                    if let Some(workspace) = workspace {
11753                        workspace
11754                            .update(&mut cx, |workspace, cx| {
11755                                struct OpenPermalinkToLine;
11756
11757                                workspace.show_toast(
11758                                    Toast::new(
11759                                        NotificationId::unique::<OpenPermalinkToLine>(),
11760                                        message,
11761                                    ),
11762                                    cx,
11763                                )
11764                            })
11765                            .ok();
11766                    }
11767                }
11768            }
11769        })
11770        .detach();
11771    }
11772
11773    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11774    /// last highlight added will be used.
11775    ///
11776    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11777    pub fn highlight_rows<T: 'static>(
11778        &mut self,
11779        range: Range<Anchor>,
11780        color: Hsla,
11781        should_autoscroll: bool,
11782        cx: &mut ViewContext<Self>,
11783    ) {
11784        let snapshot = self.buffer().read(cx).snapshot(cx);
11785        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11786        let ix = row_highlights.binary_search_by(|highlight| {
11787            Ordering::Equal
11788                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11789                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11790        });
11791
11792        if let Err(mut ix) = ix {
11793            let index = post_inc(&mut self.highlight_order);
11794
11795            // If this range intersects with the preceding highlight, then merge it with
11796            // the preceding highlight. Otherwise insert a new highlight.
11797            let mut merged = false;
11798            if ix > 0 {
11799                let prev_highlight = &mut row_highlights[ix - 1];
11800                if prev_highlight
11801                    .range
11802                    .end
11803                    .cmp(&range.start, &snapshot)
11804                    .is_ge()
11805                {
11806                    ix -= 1;
11807                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11808                        prev_highlight.range.end = range.end;
11809                    }
11810                    merged = true;
11811                    prev_highlight.index = index;
11812                    prev_highlight.color = color;
11813                    prev_highlight.should_autoscroll = should_autoscroll;
11814                }
11815            }
11816
11817            if !merged {
11818                row_highlights.insert(
11819                    ix,
11820                    RowHighlight {
11821                        range: range.clone(),
11822                        index,
11823                        color,
11824                        should_autoscroll,
11825                    },
11826                );
11827            }
11828
11829            // If any of the following highlights intersect with this one, merge them.
11830            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11831                let highlight = &row_highlights[ix];
11832                if next_highlight
11833                    .range
11834                    .start
11835                    .cmp(&highlight.range.end, &snapshot)
11836                    .is_le()
11837                {
11838                    if next_highlight
11839                        .range
11840                        .end
11841                        .cmp(&highlight.range.end, &snapshot)
11842                        .is_gt()
11843                    {
11844                        row_highlights[ix].range.end = next_highlight.range.end;
11845                    }
11846                    row_highlights.remove(ix + 1);
11847                } else {
11848                    break;
11849                }
11850            }
11851        }
11852    }
11853
11854    /// Remove any highlighted row ranges of the given type that intersect the
11855    /// given ranges.
11856    pub fn remove_highlighted_rows<T: 'static>(
11857        &mut self,
11858        ranges_to_remove: Vec<Range<Anchor>>,
11859        cx: &mut ViewContext<Self>,
11860    ) {
11861        let snapshot = self.buffer().read(cx).snapshot(cx);
11862        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11863        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11864        row_highlights.retain(|highlight| {
11865            while let Some(range_to_remove) = ranges_to_remove.peek() {
11866                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11867                    Ordering::Less | Ordering::Equal => {
11868                        ranges_to_remove.next();
11869                    }
11870                    Ordering::Greater => {
11871                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11872                            Ordering::Less | Ordering::Equal => {
11873                                return false;
11874                            }
11875                            Ordering::Greater => break,
11876                        }
11877                    }
11878                }
11879            }
11880
11881            true
11882        })
11883    }
11884
11885    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11886    pub fn clear_row_highlights<T: 'static>(&mut self) {
11887        self.highlighted_rows.remove(&TypeId::of::<T>());
11888    }
11889
11890    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11891    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11892        self.highlighted_rows
11893            .get(&TypeId::of::<T>())
11894            .map_or(&[] as &[_], |vec| vec.as_slice())
11895            .iter()
11896            .map(|highlight| (highlight.range.clone(), highlight.color))
11897    }
11898
11899    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11900    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11901    /// Allows to ignore certain kinds of highlights.
11902    pub fn highlighted_display_rows(
11903        &mut self,
11904        cx: &mut WindowContext,
11905    ) -> BTreeMap<DisplayRow, Hsla> {
11906        let snapshot = self.snapshot(cx);
11907        let mut used_highlight_orders = HashMap::default();
11908        self.highlighted_rows
11909            .iter()
11910            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11911            .fold(
11912                BTreeMap::<DisplayRow, Hsla>::new(),
11913                |mut unique_rows, highlight| {
11914                    let start = highlight.range.start.to_display_point(&snapshot);
11915                    let end = highlight.range.end.to_display_point(&snapshot);
11916                    let start_row = start.row().0;
11917                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11918                        && end.column() == 0
11919                    {
11920                        end.row().0.saturating_sub(1)
11921                    } else {
11922                        end.row().0
11923                    };
11924                    for row in start_row..=end_row {
11925                        let used_index =
11926                            used_highlight_orders.entry(row).or_insert(highlight.index);
11927                        if highlight.index >= *used_index {
11928                            *used_index = highlight.index;
11929                            unique_rows.insert(DisplayRow(row), highlight.color);
11930                        }
11931                    }
11932                    unique_rows
11933                },
11934            )
11935    }
11936
11937    pub fn highlighted_display_row_for_autoscroll(
11938        &self,
11939        snapshot: &DisplaySnapshot,
11940    ) -> Option<DisplayRow> {
11941        self.highlighted_rows
11942            .values()
11943            .flat_map(|highlighted_rows| highlighted_rows.iter())
11944            .filter_map(|highlight| {
11945                if highlight.should_autoscroll {
11946                    Some(highlight.range.start.to_display_point(snapshot).row())
11947                } else {
11948                    None
11949                }
11950            })
11951            .min()
11952    }
11953
11954    pub fn set_search_within_ranges(
11955        &mut self,
11956        ranges: &[Range<Anchor>],
11957        cx: &mut ViewContext<Self>,
11958    ) {
11959        self.highlight_background::<SearchWithinRange>(
11960            ranges,
11961            |colors| colors.editor_document_highlight_read_background,
11962            cx,
11963        )
11964    }
11965
11966    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11967        self.breadcrumb_header = Some(new_header);
11968    }
11969
11970    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11971        self.clear_background_highlights::<SearchWithinRange>(cx);
11972    }
11973
11974    pub fn highlight_background<T: 'static>(
11975        &mut self,
11976        ranges: &[Range<Anchor>],
11977        color_fetcher: fn(&ThemeColors) -> Hsla,
11978        cx: &mut ViewContext<Self>,
11979    ) {
11980        self.background_highlights
11981            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11982        self.scrollbar_marker_state.dirty = true;
11983        cx.notify();
11984    }
11985
11986    pub fn clear_background_highlights<T: 'static>(
11987        &mut self,
11988        cx: &mut ViewContext<Self>,
11989    ) -> Option<BackgroundHighlight> {
11990        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11991        if !text_highlights.1.is_empty() {
11992            self.scrollbar_marker_state.dirty = true;
11993            cx.notify();
11994        }
11995        Some(text_highlights)
11996    }
11997
11998    pub fn highlight_gutter<T: 'static>(
11999        &mut self,
12000        ranges: &[Range<Anchor>],
12001        color_fetcher: fn(&AppContext) -> Hsla,
12002        cx: &mut ViewContext<Self>,
12003    ) {
12004        self.gutter_highlights
12005            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12006        cx.notify();
12007    }
12008
12009    pub fn clear_gutter_highlights<T: 'static>(
12010        &mut self,
12011        cx: &mut ViewContext<Self>,
12012    ) -> Option<GutterHighlight> {
12013        cx.notify();
12014        self.gutter_highlights.remove(&TypeId::of::<T>())
12015    }
12016
12017    #[cfg(feature = "test-support")]
12018    pub fn all_text_background_highlights(
12019        &mut self,
12020        cx: &mut ViewContext<Self>,
12021    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12022        let snapshot = self.snapshot(cx);
12023        let buffer = &snapshot.buffer_snapshot;
12024        let start = buffer.anchor_before(0);
12025        let end = buffer.anchor_after(buffer.len());
12026        let theme = cx.theme().colors();
12027        self.background_highlights_in_range(start..end, &snapshot, theme)
12028    }
12029
12030    #[cfg(feature = "test-support")]
12031    pub fn search_background_highlights(
12032        &mut self,
12033        cx: &mut ViewContext<Self>,
12034    ) -> Vec<Range<Point>> {
12035        let snapshot = self.buffer().read(cx).snapshot(cx);
12036
12037        let highlights = self
12038            .background_highlights
12039            .get(&TypeId::of::<items::BufferSearchHighlights>());
12040
12041        if let Some((_color, ranges)) = highlights {
12042            ranges
12043                .iter()
12044                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12045                .collect_vec()
12046        } else {
12047            vec![]
12048        }
12049    }
12050
12051    fn document_highlights_for_position<'a>(
12052        &'a self,
12053        position: Anchor,
12054        buffer: &'a MultiBufferSnapshot,
12055    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12056        let read_highlights = self
12057            .background_highlights
12058            .get(&TypeId::of::<DocumentHighlightRead>())
12059            .map(|h| &h.1);
12060        let write_highlights = self
12061            .background_highlights
12062            .get(&TypeId::of::<DocumentHighlightWrite>())
12063            .map(|h| &h.1);
12064        let left_position = position.bias_left(buffer);
12065        let right_position = position.bias_right(buffer);
12066        read_highlights
12067            .into_iter()
12068            .chain(write_highlights)
12069            .flat_map(move |ranges| {
12070                let start_ix = match ranges.binary_search_by(|probe| {
12071                    let cmp = probe.end.cmp(&left_position, buffer);
12072                    if cmp.is_ge() {
12073                        Ordering::Greater
12074                    } else {
12075                        Ordering::Less
12076                    }
12077                }) {
12078                    Ok(i) | Err(i) => i,
12079                };
12080
12081                ranges[start_ix..]
12082                    .iter()
12083                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12084            })
12085    }
12086
12087    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12088        self.background_highlights
12089            .get(&TypeId::of::<T>())
12090            .map_or(false, |(_, highlights)| !highlights.is_empty())
12091    }
12092
12093    pub fn background_highlights_in_range(
12094        &self,
12095        search_range: Range<Anchor>,
12096        display_snapshot: &DisplaySnapshot,
12097        theme: &ThemeColors,
12098    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12099        let mut results = Vec::new();
12100        for (color_fetcher, ranges) in self.background_highlights.values() {
12101            let color = color_fetcher(theme);
12102            let start_ix = match ranges.binary_search_by(|probe| {
12103                let cmp = probe
12104                    .end
12105                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12106                if cmp.is_gt() {
12107                    Ordering::Greater
12108                } else {
12109                    Ordering::Less
12110                }
12111            }) {
12112                Ok(i) | Err(i) => i,
12113            };
12114            for range in &ranges[start_ix..] {
12115                if range
12116                    .start
12117                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12118                    .is_ge()
12119                {
12120                    break;
12121                }
12122
12123                let start = range.start.to_display_point(display_snapshot);
12124                let end = range.end.to_display_point(display_snapshot);
12125                results.push((start..end, color))
12126            }
12127        }
12128        results
12129    }
12130
12131    pub fn background_highlight_row_ranges<T: 'static>(
12132        &self,
12133        search_range: Range<Anchor>,
12134        display_snapshot: &DisplaySnapshot,
12135        count: usize,
12136    ) -> Vec<RangeInclusive<DisplayPoint>> {
12137        let mut results = Vec::new();
12138        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12139            return vec![];
12140        };
12141
12142        let start_ix = match ranges.binary_search_by(|probe| {
12143            let cmp = probe
12144                .end
12145                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12146            if cmp.is_gt() {
12147                Ordering::Greater
12148            } else {
12149                Ordering::Less
12150            }
12151        }) {
12152            Ok(i) | Err(i) => i,
12153        };
12154        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12155            if let (Some(start_display), Some(end_display)) = (start, end) {
12156                results.push(
12157                    start_display.to_display_point(display_snapshot)
12158                        ..=end_display.to_display_point(display_snapshot),
12159                );
12160            }
12161        };
12162        let mut start_row: Option<Point> = None;
12163        let mut end_row: Option<Point> = None;
12164        if ranges.len() > count {
12165            return Vec::new();
12166        }
12167        for range in &ranges[start_ix..] {
12168            if range
12169                .start
12170                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12171                .is_ge()
12172            {
12173                break;
12174            }
12175            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12176            if let Some(current_row) = &end_row {
12177                if end.row == current_row.row {
12178                    continue;
12179                }
12180            }
12181            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12182            if start_row.is_none() {
12183                assert_eq!(end_row, None);
12184                start_row = Some(start);
12185                end_row = Some(end);
12186                continue;
12187            }
12188            if let Some(current_end) = end_row.as_mut() {
12189                if start.row > current_end.row + 1 {
12190                    push_region(start_row, end_row);
12191                    start_row = Some(start);
12192                    end_row = Some(end);
12193                } else {
12194                    // Merge two hunks.
12195                    *current_end = end;
12196                }
12197            } else {
12198                unreachable!();
12199            }
12200        }
12201        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12202        push_region(start_row, end_row);
12203        results
12204    }
12205
12206    pub fn gutter_highlights_in_range(
12207        &self,
12208        search_range: Range<Anchor>,
12209        display_snapshot: &DisplaySnapshot,
12210        cx: &AppContext,
12211    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12212        let mut results = Vec::new();
12213        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12214            let color = color_fetcher(cx);
12215            let start_ix = match ranges.binary_search_by(|probe| {
12216                let cmp = probe
12217                    .end
12218                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12219                if cmp.is_gt() {
12220                    Ordering::Greater
12221                } else {
12222                    Ordering::Less
12223                }
12224            }) {
12225                Ok(i) | Err(i) => i,
12226            };
12227            for range in &ranges[start_ix..] {
12228                if range
12229                    .start
12230                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12231                    .is_ge()
12232                {
12233                    break;
12234                }
12235
12236                let start = range.start.to_display_point(display_snapshot);
12237                let end = range.end.to_display_point(display_snapshot);
12238                results.push((start..end, color))
12239            }
12240        }
12241        results
12242    }
12243
12244    /// Get the text ranges corresponding to the redaction query
12245    pub fn redacted_ranges(
12246        &self,
12247        search_range: Range<Anchor>,
12248        display_snapshot: &DisplaySnapshot,
12249        cx: &WindowContext,
12250    ) -> Vec<Range<DisplayPoint>> {
12251        display_snapshot
12252            .buffer_snapshot
12253            .redacted_ranges(search_range, |file| {
12254                if let Some(file) = file {
12255                    file.is_private()
12256                        && EditorSettings::get(
12257                            Some(SettingsLocation {
12258                                worktree_id: file.worktree_id(cx),
12259                                path: file.path().as_ref(),
12260                            }),
12261                            cx,
12262                        )
12263                        .redact_private_values
12264                } else {
12265                    false
12266                }
12267            })
12268            .map(|range| {
12269                range.start.to_display_point(display_snapshot)
12270                    ..range.end.to_display_point(display_snapshot)
12271            })
12272            .collect()
12273    }
12274
12275    pub fn highlight_text<T: 'static>(
12276        &mut self,
12277        ranges: Vec<Range<Anchor>>,
12278        style: HighlightStyle,
12279        cx: &mut ViewContext<Self>,
12280    ) {
12281        self.display_map.update(cx, |map, _| {
12282            map.highlight_text(TypeId::of::<T>(), ranges, style)
12283        });
12284        cx.notify();
12285    }
12286
12287    pub(crate) fn highlight_inlays<T: 'static>(
12288        &mut self,
12289        highlights: Vec<InlayHighlight>,
12290        style: HighlightStyle,
12291        cx: &mut ViewContext<Self>,
12292    ) {
12293        self.display_map.update(cx, |map, _| {
12294            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12295        });
12296        cx.notify();
12297    }
12298
12299    pub fn text_highlights<'a, T: 'static>(
12300        &'a self,
12301        cx: &'a AppContext,
12302    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12303        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12304    }
12305
12306    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12307        let cleared = self
12308            .display_map
12309            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12310        if cleared {
12311            cx.notify();
12312        }
12313    }
12314
12315    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12316        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12317            && self.focus_handle.is_focused(cx)
12318    }
12319
12320    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12321        self.show_cursor_when_unfocused = is_enabled;
12322        cx.notify();
12323    }
12324
12325    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12326        cx.notify();
12327    }
12328
12329    fn on_buffer_event(
12330        &mut self,
12331        multibuffer: Model<MultiBuffer>,
12332        event: &multi_buffer::Event,
12333        cx: &mut ViewContext<Self>,
12334    ) {
12335        match event {
12336            multi_buffer::Event::Edited {
12337                singleton_buffer_edited,
12338            } => {
12339                self.scrollbar_marker_state.dirty = true;
12340                self.active_indent_guides_state.dirty = true;
12341                self.refresh_active_diagnostics(cx);
12342                self.refresh_code_actions(cx);
12343                if self.has_active_inline_completion(cx) {
12344                    self.update_visible_inline_completion(cx);
12345                }
12346                cx.emit(EditorEvent::BufferEdited);
12347                cx.emit(SearchEvent::MatchesInvalidated);
12348                if *singleton_buffer_edited {
12349                    if let Some(project) = &self.project {
12350                        let project = project.read(cx);
12351                        #[allow(clippy::mutable_key_type)]
12352                        let languages_affected = multibuffer
12353                            .read(cx)
12354                            .all_buffers()
12355                            .into_iter()
12356                            .filter_map(|buffer| {
12357                                let buffer = buffer.read(cx);
12358                                let language = buffer.language()?;
12359                                if project.is_local()
12360                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12361                                {
12362                                    None
12363                                } else {
12364                                    Some(language)
12365                                }
12366                            })
12367                            .cloned()
12368                            .collect::<HashSet<_>>();
12369                        if !languages_affected.is_empty() {
12370                            self.refresh_inlay_hints(
12371                                InlayHintRefreshReason::BufferEdited(languages_affected),
12372                                cx,
12373                            );
12374                        }
12375                    }
12376                }
12377
12378                let Some(project) = &self.project else { return };
12379                let (telemetry, is_via_ssh) = {
12380                    let project = project.read(cx);
12381                    let telemetry = project.client().telemetry().clone();
12382                    let is_via_ssh = project.is_via_ssh();
12383                    (telemetry, is_via_ssh)
12384                };
12385                refresh_linked_ranges(self, cx);
12386                telemetry.log_edit_event("editor", is_via_ssh);
12387            }
12388            multi_buffer::Event::ExcerptsAdded {
12389                buffer,
12390                predecessor,
12391                excerpts,
12392            } => {
12393                self.tasks_update_task = Some(self.refresh_runnables(cx));
12394                cx.emit(EditorEvent::ExcerptsAdded {
12395                    buffer: buffer.clone(),
12396                    predecessor: *predecessor,
12397                    excerpts: excerpts.clone(),
12398                });
12399                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12400            }
12401            multi_buffer::Event::ExcerptsRemoved { ids } => {
12402                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12403                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12404            }
12405            multi_buffer::Event::ExcerptsEdited { ids } => {
12406                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12407            }
12408            multi_buffer::Event::ExcerptsExpanded { ids } => {
12409                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12410            }
12411            multi_buffer::Event::Reparsed(buffer_id) => {
12412                self.tasks_update_task = Some(self.refresh_runnables(cx));
12413
12414                cx.emit(EditorEvent::Reparsed(*buffer_id));
12415            }
12416            multi_buffer::Event::LanguageChanged(buffer_id) => {
12417                linked_editing_ranges::refresh_linked_ranges(self, cx);
12418                cx.emit(EditorEvent::Reparsed(*buffer_id));
12419                cx.notify();
12420            }
12421            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12422            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12423            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12424                cx.emit(EditorEvent::TitleChanged)
12425            }
12426            multi_buffer::Event::DiffBaseChanged => {
12427                self.scrollbar_marker_state.dirty = true;
12428                cx.emit(EditorEvent::DiffBaseChanged);
12429                cx.notify();
12430            }
12431            multi_buffer::Event::DiffUpdated { buffer } => {
12432                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12433                cx.notify();
12434            }
12435            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12436            multi_buffer::Event::DiagnosticsUpdated => {
12437                self.refresh_active_diagnostics(cx);
12438                self.scrollbar_marker_state.dirty = true;
12439                cx.notify();
12440            }
12441            _ => {}
12442        };
12443    }
12444
12445    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12446        cx.notify();
12447    }
12448
12449    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12450        self.tasks_update_task = Some(self.refresh_runnables(cx));
12451        self.refresh_inline_completion(true, false, cx);
12452        self.refresh_inlay_hints(
12453            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12454                self.selections.newest_anchor().head(),
12455                &self.buffer.read(cx).snapshot(cx),
12456                cx,
12457            )),
12458            cx,
12459        );
12460
12461        let old_cursor_shape = self.cursor_shape;
12462
12463        {
12464            let editor_settings = EditorSettings::get_global(cx);
12465            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12466            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12467            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12468        }
12469
12470        if old_cursor_shape != self.cursor_shape {
12471            cx.emit(EditorEvent::CursorShapeChanged);
12472        }
12473
12474        let project_settings = ProjectSettings::get_global(cx);
12475        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12476
12477        if self.mode == EditorMode::Full {
12478            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12479            if self.git_blame_inline_enabled != inline_blame_enabled {
12480                self.toggle_git_blame_inline_internal(false, cx);
12481            }
12482        }
12483
12484        cx.notify();
12485    }
12486
12487    pub fn set_searchable(&mut self, searchable: bool) {
12488        self.searchable = searchable;
12489    }
12490
12491    pub fn searchable(&self) -> bool {
12492        self.searchable
12493    }
12494
12495    fn open_proposed_changes_editor(
12496        &mut self,
12497        _: &OpenProposedChangesEditor,
12498        cx: &mut ViewContext<Self>,
12499    ) {
12500        let Some(workspace) = self.workspace() else {
12501            cx.propagate();
12502            return;
12503        };
12504
12505        let selections = self.selections.all::<usize>(cx);
12506        let buffer = self.buffer.read(cx);
12507        let mut new_selections_by_buffer = HashMap::default();
12508        for selection in selections {
12509            for (buffer, range, _) in
12510                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12511            {
12512                let mut range = range.to_point(buffer.read(cx));
12513                range.start.column = 0;
12514                range.end.column = buffer.read(cx).line_len(range.end.row);
12515                new_selections_by_buffer
12516                    .entry(buffer)
12517                    .or_insert(Vec::new())
12518                    .push(range)
12519            }
12520        }
12521
12522        let proposed_changes_buffers = new_selections_by_buffer
12523            .into_iter()
12524            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12525            .collect::<Vec<_>>();
12526        let proposed_changes_editor = cx.new_view(|cx| {
12527            ProposedChangesEditor::new(
12528                "Proposed changes",
12529                proposed_changes_buffers,
12530                self.project.clone(),
12531                cx,
12532            )
12533        });
12534
12535        cx.window_context().defer(move |cx| {
12536            workspace.update(cx, |workspace, cx| {
12537                workspace.active_pane().update(cx, |pane, cx| {
12538                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12539                });
12540            });
12541        });
12542    }
12543
12544    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12545        self.open_excerpts_common(true, cx)
12546    }
12547
12548    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12549        self.open_excerpts_common(false, cx)
12550    }
12551
12552    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12553        let selections = self.selections.all::<usize>(cx);
12554        let buffer = self.buffer.read(cx);
12555        if buffer.is_singleton() {
12556            cx.propagate();
12557            return;
12558        }
12559
12560        let Some(workspace) = self.workspace() else {
12561            cx.propagate();
12562            return;
12563        };
12564
12565        let mut new_selections_by_buffer = HashMap::default();
12566        for selection in selections {
12567            for (mut buffer_handle, mut range, _) in
12568                buffer.range_to_buffer_ranges(selection.range(), cx)
12569            {
12570                // When editing branch buffers, jump to the corresponding location
12571                // in their base buffer.
12572                let buffer = buffer_handle.read(cx);
12573                if let Some(base_buffer) = buffer.diff_base_buffer() {
12574                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12575                    buffer_handle = base_buffer;
12576                }
12577
12578                if selection.reversed {
12579                    mem::swap(&mut range.start, &mut range.end);
12580                }
12581                new_selections_by_buffer
12582                    .entry(buffer_handle)
12583                    .or_insert(Vec::new())
12584                    .push(range)
12585            }
12586        }
12587
12588        // We defer the pane interaction because we ourselves are a workspace item
12589        // and activating a new item causes the pane to call a method on us reentrantly,
12590        // which panics if we're on the stack.
12591        cx.window_context().defer(move |cx| {
12592            workspace.update(cx, |workspace, cx| {
12593                let pane = if split {
12594                    workspace.adjacent_pane(cx)
12595                } else {
12596                    workspace.active_pane().clone()
12597                };
12598
12599                for (buffer, ranges) in new_selections_by_buffer {
12600                    let editor =
12601                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12602                    editor.update(cx, |editor, cx| {
12603                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12604                            s.select_ranges(ranges);
12605                        });
12606                    });
12607                }
12608            })
12609        });
12610    }
12611
12612    fn jump(
12613        &mut self,
12614        path: ProjectPath,
12615        position: Point,
12616        anchor: language::Anchor,
12617        offset_from_top: u32,
12618        cx: &mut ViewContext<Self>,
12619    ) {
12620        let workspace = self.workspace();
12621        cx.spawn(|_, mut cx| async move {
12622            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12623            let editor = workspace.update(&mut cx, |workspace, cx| {
12624                // Reset the preview item id before opening the new item
12625                workspace.active_pane().update(cx, |pane, cx| {
12626                    pane.set_preview_item_id(None, cx);
12627                });
12628                workspace.open_path_preview(path, None, true, true, cx)
12629            })?;
12630            let editor = editor
12631                .await?
12632                .downcast::<Editor>()
12633                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12634                .downgrade();
12635            editor.update(&mut cx, |editor, cx| {
12636                let buffer = editor
12637                    .buffer()
12638                    .read(cx)
12639                    .as_singleton()
12640                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12641                let buffer = buffer.read(cx);
12642                let cursor = if buffer.can_resolve(&anchor) {
12643                    language::ToPoint::to_point(&anchor, buffer)
12644                } else {
12645                    buffer.clip_point(position, Bias::Left)
12646                };
12647
12648                let nav_history = editor.nav_history.take();
12649                editor.change_selections(
12650                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12651                    cx,
12652                    |s| {
12653                        s.select_ranges([cursor..cursor]);
12654                    },
12655                );
12656                editor.nav_history = nav_history;
12657
12658                anyhow::Ok(())
12659            })??;
12660
12661            anyhow::Ok(())
12662        })
12663        .detach_and_log_err(cx);
12664    }
12665
12666    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12667        let snapshot = self.buffer.read(cx).read(cx);
12668        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12669        Some(
12670            ranges
12671                .iter()
12672                .map(move |range| {
12673                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12674                })
12675                .collect(),
12676        )
12677    }
12678
12679    fn selection_replacement_ranges(
12680        &self,
12681        range: Range<OffsetUtf16>,
12682        cx: &mut AppContext,
12683    ) -> Vec<Range<OffsetUtf16>> {
12684        let selections = self.selections.all::<OffsetUtf16>(cx);
12685        let newest_selection = selections
12686            .iter()
12687            .max_by_key(|selection| selection.id)
12688            .unwrap();
12689        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12690        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12691        let snapshot = self.buffer.read(cx).read(cx);
12692        selections
12693            .into_iter()
12694            .map(|mut selection| {
12695                selection.start.0 =
12696                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12697                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12698                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12699                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12700            })
12701            .collect()
12702    }
12703
12704    fn report_editor_event(
12705        &self,
12706        operation: &'static str,
12707        file_extension: Option<String>,
12708        cx: &AppContext,
12709    ) {
12710        if cfg!(any(test, feature = "test-support")) {
12711            return;
12712        }
12713
12714        let Some(project) = &self.project else { return };
12715
12716        // If None, we are in a file without an extension
12717        let file = self
12718            .buffer
12719            .read(cx)
12720            .as_singleton()
12721            .and_then(|b| b.read(cx).file());
12722        let file_extension = file_extension.or(file
12723            .as_ref()
12724            .and_then(|file| Path::new(file.file_name(cx)).extension())
12725            .and_then(|e| e.to_str())
12726            .map(|a| a.to_string()));
12727
12728        let vim_mode = cx
12729            .global::<SettingsStore>()
12730            .raw_user_settings()
12731            .get("vim_mode")
12732            == Some(&serde_json::Value::Bool(true));
12733
12734        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12735            == language::language_settings::InlineCompletionProvider::Copilot;
12736        let copilot_enabled_for_language = self
12737            .buffer
12738            .read(cx)
12739            .settings_at(0, cx)
12740            .show_inline_completions;
12741
12742        let project = project.read(cx);
12743        let telemetry = project.client().telemetry().clone();
12744        telemetry.report_editor_event(
12745            file_extension,
12746            vim_mode,
12747            operation,
12748            copilot_enabled,
12749            copilot_enabled_for_language,
12750            project.is_via_ssh(),
12751        )
12752    }
12753
12754    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12755    /// with each line being an array of {text, highlight} objects.
12756    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12757        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12758            return;
12759        };
12760
12761        #[derive(Serialize)]
12762        struct Chunk<'a> {
12763            text: String,
12764            highlight: Option<&'a str>,
12765        }
12766
12767        let snapshot = buffer.read(cx).snapshot();
12768        let range = self
12769            .selected_text_range(false, cx)
12770            .and_then(|selection| {
12771                if selection.range.is_empty() {
12772                    None
12773                } else {
12774                    Some(selection.range)
12775                }
12776            })
12777            .unwrap_or_else(|| 0..snapshot.len());
12778
12779        let chunks = snapshot.chunks(range, true);
12780        let mut lines = Vec::new();
12781        let mut line: VecDeque<Chunk> = VecDeque::new();
12782
12783        let Some(style) = self.style.as_ref() else {
12784            return;
12785        };
12786
12787        for chunk in chunks {
12788            let highlight = chunk
12789                .syntax_highlight_id
12790                .and_then(|id| id.name(&style.syntax));
12791            let mut chunk_lines = chunk.text.split('\n').peekable();
12792            while let Some(text) = chunk_lines.next() {
12793                let mut merged_with_last_token = false;
12794                if let Some(last_token) = line.back_mut() {
12795                    if last_token.highlight == highlight {
12796                        last_token.text.push_str(text);
12797                        merged_with_last_token = true;
12798                    }
12799                }
12800
12801                if !merged_with_last_token {
12802                    line.push_back(Chunk {
12803                        text: text.into(),
12804                        highlight,
12805                    });
12806                }
12807
12808                if chunk_lines.peek().is_some() {
12809                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12810                        line.pop_front();
12811                    }
12812                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12813                        line.pop_back();
12814                    }
12815
12816                    lines.push(mem::take(&mut line));
12817                }
12818            }
12819        }
12820
12821        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12822            return;
12823        };
12824        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12825    }
12826
12827    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12828        &self.inlay_hint_cache
12829    }
12830
12831    pub fn replay_insert_event(
12832        &mut self,
12833        text: &str,
12834        relative_utf16_range: Option<Range<isize>>,
12835        cx: &mut ViewContext<Self>,
12836    ) {
12837        if !self.input_enabled {
12838            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12839            return;
12840        }
12841        if let Some(relative_utf16_range) = relative_utf16_range {
12842            let selections = self.selections.all::<OffsetUtf16>(cx);
12843            self.change_selections(None, cx, |s| {
12844                let new_ranges = selections.into_iter().map(|range| {
12845                    let start = OffsetUtf16(
12846                        range
12847                            .head()
12848                            .0
12849                            .saturating_add_signed(relative_utf16_range.start),
12850                    );
12851                    let end = OffsetUtf16(
12852                        range
12853                            .head()
12854                            .0
12855                            .saturating_add_signed(relative_utf16_range.end),
12856                    );
12857                    start..end
12858                });
12859                s.select_ranges(new_ranges);
12860            });
12861        }
12862
12863        self.handle_input(text, cx);
12864    }
12865
12866    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12867        let Some(provider) = self.semantics_provider.as_ref() else {
12868            return false;
12869        };
12870
12871        let mut supports = false;
12872        self.buffer().read(cx).for_each_buffer(|buffer| {
12873            supports |= provider.supports_inlay_hints(buffer, cx);
12874        });
12875        supports
12876    }
12877
12878    pub fn focus(&self, cx: &mut WindowContext) {
12879        cx.focus(&self.focus_handle)
12880    }
12881
12882    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12883        self.focus_handle.is_focused(cx)
12884    }
12885
12886    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12887        cx.emit(EditorEvent::Focused);
12888
12889        if let Some(descendant) = self
12890            .last_focused_descendant
12891            .take()
12892            .and_then(|descendant| descendant.upgrade())
12893        {
12894            cx.focus(&descendant);
12895        } else {
12896            if let Some(blame) = self.blame.as_ref() {
12897                blame.update(cx, GitBlame::focus)
12898            }
12899
12900            self.blink_manager.update(cx, BlinkManager::enable);
12901            self.show_cursor_names(cx);
12902            self.buffer.update(cx, |buffer, cx| {
12903                buffer.finalize_last_transaction(cx);
12904                if self.leader_peer_id.is_none() {
12905                    buffer.set_active_selections(
12906                        &self.selections.disjoint_anchors(),
12907                        self.selections.line_mode,
12908                        self.cursor_shape,
12909                        cx,
12910                    );
12911                }
12912            });
12913        }
12914    }
12915
12916    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12917        cx.emit(EditorEvent::FocusedIn)
12918    }
12919
12920    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12921        if event.blurred != self.focus_handle {
12922            self.last_focused_descendant = Some(event.blurred);
12923        }
12924    }
12925
12926    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12927        self.blink_manager.update(cx, BlinkManager::disable);
12928        self.buffer
12929            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12930
12931        if let Some(blame) = self.blame.as_ref() {
12932            blame.update(cx, GitBlame::blur)
12933        }
12934        if !self.hover_state.focused(cx) {
12935            hide_hover(self, cx);
12936        }
12937
12938        self.hide_context_menu(cx);
12939        cx.emit(EditorEvent::Blurred);
12940        cx.notify();
12941    }
12942
12943    pub fn register_action<A: Action>(
12944        &mut self,
12945        listener: impl Fn(&A, &mut WindowContext) + 'static,
12946    ) -> Subscription {
12947        let id = self.next_editor_action_id.post_inc();
12948        let listener = Arc::new(listener);
12949        self.editor_actions.borrow_mut().insert(
12950            id,
12951            Box::new(move |cx| {
12952                let cx = cx.window_context();
12953                let listener = listener.clone();
12954                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12955                    let action = action.downcast_ref().unwrap();
12956                    if phase == DispatchPhase::Bubble {
12957                        listener(action, cx)
12958                    }
12959                })
12960            }),
12961        );
12962
12963        let editor_actions = self.editor_actions.clone();
12964        Subscription::new(move || {
12965            editor_actions.borrow_mut().remove(&id);
12966        })
12967    }
12968
12969    pub fn file_header_size(&self) -> u32 {
12970        FILE_HEADER_HEIGHT
12971    }
12972
12973    pub fn revert(
12974        &mut self,
12975        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12976        cx: &mut ViewContext<Self>,
12977    ) {
12978        self.buffer().update(cx, |multi_buffer, cx| {
12979            for (buffer_id, changes) in revert_changes {
12980                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12981                    buffer.update(cx, |buffer, cx| {
12982                        buffer.edit(
12983                            changes.into_iter().map(|(range, text)| {
12984                                (range, text.to_string().map(Arc::<str>::from))
12985                            }),
12986                            None,
12987                            cx,
12988                        );
12989                    });
12990                }
12991            }
12992        });
12993        self.change_selections(None, cx, |selections| selections.refresh());
12994    }
12995
12996    pub fn to_pixel_point(
12997        &mut self,
12998        source: multi_buffer::Anchor,
12999        editor_snapshot: &EditorSnapshot,
13000        cx: &mut ViewContext<Self>,
13001    ) -> Option<gpui::Point<Pixels>> {
13002        let source_point = source.to_display_point(editor_snapshot);
13003        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13004    }
13005
13006    pub fn display_to_pixel_point(
13007        &mut self,
13008        source: DisplayPoint,
13009        editor_snapshot: &EditorSnapshot,
13010        cx: &mut ViewContext<Self>,
13011    ) -> Option<gpui::Point<Pixels>> {
13012        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13013        let text_layout_details = self.text_layout_details(cx);
13014        let scroll_top = text_layout_details
13015            .scroll_anchor
13016            .scroll_position(editor_snapshot)
13017            .y;
13018
13019        if source.row().as_f32() < scroll_top.floor() {
13020            return None;
13021        }
13022        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13023        let source_y = line_height * (source.row().as_f32() - scroll_top);
13024        Some(gpui::Point::new(source_x, source_y))
13025    }
13026
13027    pub fn has_active_completions_menu(&self) -> bool {
13028        self.context_menu.read().as_ref().map_or(false, |menu| {
13029            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13030        })
13031    }
13032
13033    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13034        self.addons
13035            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13036    }
13037
13038    pub fn unregister_addon<T: Addon>(&mut self) {
13039        self.addons.remove(&std::any::TypeId::of::<T>());
13040    }
13041
13042    pub fn addon<T: Addon>(&self) -> Option<&T> {
13043        let type_id = std::any::TypeId::of::<T>();
13044        self.addons
13045            .get(&type_id)
13046            .and_then(|item| item.to_any().downcast_ref::<T>())
13047    }
13048}
13049
13050fn hunks_for_selections(
13051    multi_buffer_snapshot: &MultiBufferSnapshot,
13052    selections: &[Selection<Anchor>],
13053) -> Vec<MultiBufferDiffHunk> {
13054    let buffer_rows_for_selections = selections.iter().map(|selection| {
13055        let head = selection.head();
13056        let tail = selection.tail();
13057        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13058        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13059        if start > end {
13060            end..start
13061        } else {
13062            start..end
13063        }
13064    });
13065
13066    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13067}
13068
13069pub fn hunks_for_rows(
13070    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13071    multi_buffer_snapshot: &MultiBufferSnapshot,
13072) -> Vec<MultiBufferDiffHunk> {
13073    let mut hunks = Vec::new();
13074    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13075        HashMap::default();
13076    for selected_multi_buffer_rows in rows {
13077        let query_rows =
13078            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13079        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13080            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13081            // when the caret is just above or just below the deleted hunk.
13082            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13083            let related_to_selection = if allow_adjacent {
13084                hunk.row_range.overlaps(&query_rows)
13085                    || hunk.row_range.start == query_rows.end
13086                    || hunk.row_range.end == query_rows.start
13087            } else {
13088                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13089                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13090                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13091                    || selected_multi_buffer_rows.end == hunk.row_range.start
13092            };
13093            if related_to_selection {
13094                if !processed_buffer_rows
13095                    .entry(hunk.buffer_id)
13096                    .or_default()
13097                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13098                {
13099                    continue;
13100                }
13101                hunks.push(hunk);
13102            }
13103        }
13104    }
13105
13106    hunks
13107}
13108
13109pub trait CollaborationHub {
13110    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13111    fn user_participant_indices<'a>(
13112        &self,
13113        cx: &'a AppContext,
13114    ) -> &'a HashMap<u64, ParticipantIndex>;
13115    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13116}
13117
13118impl CollaborationHub for Model<Project> {
13119    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13120        self.read(cx).collaborators()
13121    }
13122
13123    fn user_participant_indices<'a>(
13124        &self,
13125        cx: &'a AppContext,
13126    ) -> &'a HashMap<u64, ParticipantIndex> {
13127        self.read(cx).user_store().read(cx).participant_indices()
13128    }
13129
13130    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13131        let this = self.read(cx);
13132        let user_ids = this.collaborators().values().map(|c| c.user_id);
13133        this.user_store().read_with(cx, |user_store, cx| {
13134            user_store.participant_names(user_ids, cx)
13135        })
13136    }
13137}
13138
13139pub trait SemanticsProvider {
13140    fn hover(
13141        &self,
13142        buffer: &Model<Buffer>,
13143        position: text::Anchor,
13144        cx: &mut AppContext,
13145    ) -> Option<Task<Vec<project::Hover>>>;
13146
13147    fn inlay_hints(
13148        &self,
13149        buffer_handle: Model<Buffer>,
13150        range: Range<text::Anchor>,
13151        cx: &mut AppContext,
13152    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13153
13154    fn resolve_inlay_hint(
13155        &self,
13156        hint: InlayHint,
13157        buffer_handle: Model<Buffer>,
13158        server_id: LanguageServerId,
13159        cx: &mut AppContext,
13160    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13161
13162    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13163
13164    fn document_highlights(
13165        &self,
13166        buffer: &Model<Buffer>,
13167        position: text::Anchor,
13168        cx: &mut AppContext,
13169    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13170
13171    fn definitions(
13172        &self,
13173        buffer: &Model<Buffer>,
13174        position: text::Anchor,
13175        kind: GotoDefinitionKind,
13176        cx: &mut AppContext,
13177    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13178
13179    fn range_for_rename(
13180        &self,
13181        buffer: &Model<Buffer>,
13182        position: text::Anchor,
13183        cx: &mut AppContext,
13184    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13185
13186    fn perform_rename(
13187        &self,
13188        buffer: &Model<Buffer>,
13189        position: text::Anchor,
13190        new_name: String,
13191        cx: &mut AppContext,
13192    ) -> Option<Task<Result<ProjectTransaction>>>;
13193}
13194
13195pub trait CompletionProvider {
13196    fn completions(
13197        &self,
13198        buffer: &Model<Buffer>,
13199        buffer_position: text::Anchor,
13200        trigger: CompletionContext,
13201        cx: &mut ViewContext<Editor>,
13202    ) -> Task<Result<Vec<Completion>>>;
13203
13204    fn resolve_completions(
13205        &self,
13206        buffer: Model<Buffer>,
13207        completion_indices: Vec<usize>,
13208        completions: Arc<RwLock<Box<[Completion]>>>,
13209        cx: &mut ViewContext<Editor>,
13210    ) -> Task<Result<bool>>;
13211
13212    fn apply_additional_edits_for_completion(
13213        &self,
13214        buffer: Model<Buffer>,
13215        completion: Completion,
13216        push_to_history: bool,
13217        cx: &mut ViewContext<Editor>,
13218    ) -> Task<Result<Option<language::Transaction>>>;
13219
13220    fn is_completion_trigger(
13221        &self,
13222        buffer: &Model<Buffer>,
13223        position: language::Anchor,
13224        text: &str,
13225        trigger_in_words: bool,
13226        cx: &mut ViewContext<Editor>,
13227    ) -> bool;
13228
13229    fn sort_completions(&self) -> bool {
13230        true
13231    }
13232}
13233
13234pub trait CodeActionProvider {
13235    fn code_actions(
13236        &self,
13237        buffer: &Model<Buffer>,
13238        range: Range<text::Anchor>,
13239        cx: &mut WindowContext,
13240    ) -> Task<Result<Vec<CodeAction>>>;
13241
13242    fn apply_code_action(
13243        &self,
13244        buffer_handle: Model<Buffer>,
13245        action: CodeAction,
13246        excerpt_id: ExcerptId,
13247        push_to_history: bool,
13248        cx: &mut WindowContext,
13249    ) -> Task<Result<ProjectTransaction>>;
13250}
13251
13252impl CodeActionProvider for Model<Project> {
13253    fn code_actions(
13254        &self,
13255        buffer: &Model<Buffer>,
13256        range: Range<text::Anchor>,
13257        cx: &mut WindowContext,
13258    ) -> Task<Result<Vec<CodeAction>>> {
13259        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13260    }
13261
13262    fn apply_code_action(
13263        &self,
13264        buffer_handle: Model<Buffer>,
13265        action: CodeAction,
13266        _excerpt_id: ExcerptId,
13267        push_to_history: bool,
13268        cx: &mut WindowContext,
13269    ) -> Task<Result<ProjectTransaction>> {
13270        self.update(cx, |project, cx| {
13271            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13272        })
13273    }
13274}
13275
13276fn snippet_completions(
13277    project: &Project,
13278    buffer: &Model<Buffer>,
13279    buffer_position: text::Anchor,
13280    cx: &mut AppContext,
13281) -> Vec<Completion> {
13282    let language = buffer.read(cx).language_at(buffer_position);
13283    let language_name = language.as_ref().map(|language| language.lsp_id());
13284    let snippet_store = project.snippets().read(cx);
13285    let snippets = snippet_store.snippets_for(language_name, cx);
13286
13287    if snippets.is_empty() {
13288        return vec![];
13289    }
13290    let snapshot = buffer.read(cx).text_snapshot();
13291    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13292
13293    let scope = language.map(|language| language.default_scope());
13294    let classifier = CharClassifier::new(scope).for_completion(true);
13295    let mut last_word = chars
13296        .take_while(|c| classifier.is_word(*c))
13297        .collect::<String>();
13298    last_word = last_word.chars().rev().collect();
13299    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13300    let to_lsp = |point: &text::Anchor| {
13301        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13302        point_to_lsp(end)
13303    };
13304    let lsp_end = to_lsp(&buffer_position);
13305    snippets
13306        .into_iter()
13307        .filter_map(|snippet| {
13308            let matching_prefix = snippet
13309                .prefix
13310                .iter()
13311                .find(|prefix| prefix.starts_with(&last_word))?;
13312            let start = as_offset - last_word.len();
13313            let start = snapshot.anchor_before(start);
13314            let range = start..buffer_position;
13315            let lsp_start = to_lsp(&start);
13316            let lsp_range = lsp::Range {
13317                start: lsp_start,
13318                end: lsp_end,
13319            };
13320            Some(Completion {
13321                old_range: range,
13322                new_text: snippet.body.clone(),
13323                label: CodeLabel {
13324                    text: matching_prefix.clone(),
13325                    runs: vec![],
13326                    filter_range: 0..matching_prefix.len(),
13327                },
13328                server_id: LanguageServerId(usize::MAX),
13329                documentation: snippet.description.clone().map(Documentation::SingleLine),
13330                lsp_completion: lsp::CompletionItem {
13331                    label: snippet.prefix.first().unwrap().clone(),
13332                    kind: Some(CompletionItemKind::SNIPPET),
13333                    label_details: snippet.description.as_ref().map(|description| {
13334                        lsp::CompletionItemLabelDetails {
13335                            detail: Some(description.clone()),
13336                            description: None,
13337                        }
13338                    }),
13339                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13340                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13341                        lsp::InsertReplaceEdit {
13342                            new_text: snippet.body.clone(),
13343                            insert: lsp_range,
13344                            replace: lsp_range,
13345                        },
13346                    )),
13347                    filter_text: Some(snippet.body.clone()),
13348                    sort_text: Some(char::MAX.to_string()),
13349                    ..Default::default()
13350                },
13351                confirm: None,
13352            })
13353        })
13354        .collect()
13355}
13356
13357impl CompletionProvider for Model<Project> {
13358    fn completions(
13359        &self,
13360        buffer: &Model<Buffer>,
13361        buffer_position: text::Anchor,
13362        options: CompletionContext,
13363        cx: &mut ViewContext<Editor>,
13364    ) -> Task<Result<Vec<Completion>>> {
13365        self.update(cx, |project, cx| {
13366            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13367            let project_completions = project.completions(buffer, buffer_position, options, cx);
13368            cx.background_executor().spawn(async move {
13369                let mut completions = project_completions.await?;
13370                //let snippets = snippets.into_iter().;
13371                completions.extend(snippets);
13372                Ok(completions)
13373            })
13374        })
13375    }
13376
13377    fn resolve_completions(
13378        &self,
13379        buffer: Model<Buffer>,
13380        completion_indices: Vec<usize>,
13381        completions: Arc<RwLock<Box<[Completion]>>>,
13382        cx: &mut ViewContext<Editor>,
13383    ) -> Task<Result<bool>> {
13384        self.update(cx, |project, cx| {
13385            project.resolve_completions(buffer, completion_indices, completions, cx)
13386        })
13387    }
13388
13389    fn apply_additional_edits_for_completion(
13390        &self,
13391        buffer: Model<Buffer>,
13392        completion: Completion,
13393        push_to_history: bool,
13394        cx: &mut ViewContext<Editor>,
13395    ) -> Task<Result<Option<language::Transaction>>> {
13396        self.update(cx, |project, cx| {
13397            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13398        })
13399    }
13400
13401    fn is_completion_trigger(
13402        &self,
13403        buffer: &Model<Buffer>,
13404        position: language::Anchor,
13405        text: &str,
13406        trigger_in_words: bool,
13407        cx: &mut ViewContext<Editor>,
13408    ) -> bool {
13409        if !EditorSettings::get_global(cx).show_completions_on_input {
13410            return false;
13411        }
13412
13413        let mut chars = text.chars();
13414        let char = if let Some(char) = chars.next() {
13415            char
13416        } else {
13417            return false;
13418        };
13419        if chars.next().is_some() {
13420            return false;
13421        }
13422
13423        let buffer = buffer.read(cx);
13424        let classifier = buffer
13425            .snapshot()
13426            .char_classifier_at(position)
13427            .for_completion(true);
13428        if trigger_in_words && classifier.is_word(char) {
13429            return true;
13430        }
13431
13432        buffer
13433            .completion_triggers()
13434            .iter()
13435            .any(|string| string == text)
13436    }
13437}
13438
13439impl SemanticsProvider for Model<Project> {
13440    fn hover(
13441        &self,
13442        buffer: &Model<Buffer>,
13443        position: text::Anchor,
13444        cx: &mut AppContext,
13445    ) -> Option<Task<Vec<project::Hover>>> {
13446        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13447    }
13448
13449    fn document_highlights(
13450        &self,
13451        buffer: &Model<Buffer>,
13452        position: text::Anchor,
13453        cx: &mut AppContext,
13454    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13455        Some(self.update(cx, |project, cx| {
13456            project.document_highlights(buffer, position, cx)
13457        }))
13458    }
13459
13460    fn definitions(
13461        &self,
13462        buffer: &Model<Buffer>,
13463        position: text::Anchor,
13464        kind: GotoDefinitionKind,
13465        cx: &mut AppContext,
13466    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13467        Some(self.update(cx, |project, cx| match kind {
13468            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13469            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13470            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13471            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13472        }))
13473    }
13474
13475    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13476        // TODO: make this work for remote projects
13477        self.read(cx)
13478            .language_servers_for_buffer(buffer.read(cx), cx)
13479            .any(
13480                |(_, server)| match server.capabilities().inlay_hint_provider {
13481                    Some(lsp::OneOf::Left(enabled)) => enabled,
13482                    Some(lsp::OneOf::Right(_)) => true,
13483                    None => false,
13484                },
13485            )
13486    }
13487
13488    fn inlay_hints(
13489        &self,
13490        buffer_handle: Model<Buffer>,
13491        range: Range<text::Anchor>,
13492        cx: &mut AppContext,
13493    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13494        Some(self.update(cx, |project, cx| {
13495            project.inlay_hints(buffer_handle, range, cx)
13496        }))
13497    }
13498
13499    fn resolve_inlay_hint(
13500        &self,
13501        hint: InlayHint,
13502        buffer_handle: Model<Buffer>,
13503        server_id: LanguageServerId,
13504        cx: &mut AppContext,
13505    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13506        Some(self.update(cx, |project, cx| {
13507            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13508        }))
13509    }
13510
13511    fn range_for_rename(
13512        &self,
13513        buffer: &Model<Buffer>,
13514        position: text::Anchor,
13515        cx: &mut AppContext,
13516    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13517        Some(self.update(cx, |project, cx| {
13518            project.prepare_rename(buffer.clone(), position, cx)
13519        }))
13520    }
13521
13522    fn perform_rename(
13523        &self,
13524        buffer: &Model<Buffer>,
13525        position: text::Anchor,
13526        new_name: String,
13527        cx: &mut AppContext,
13528    ) -> Option<Task<Result<ProjectTransaction>>> {
13529        Some(self.update(cx, |project, cx| {
13530            project.perform_rename(buffer.clone(), position, new_name, cx)
13531        }))
13532    }
13533}
13534
13535fn inlay_hint_settings(
13536    location: Anchor,
13537    snapshot: &MultiBufferSnapshot,
13538    cx: &mut ViewContext<'_, Editor>,
13539) -> InlayHintSettings {
13540    let file = snapshot.file_at(location);
13541    let language = snapshot.language_at(location).map(|l| l.name());
13542    language_settings(language, file, cx).inlay_hints
13543}
13544
13545fn consume_contiguous_rows(
13546    contiguous_row_selections: &mut Vec<Selection<Point>>,
13547    selection: &Selection<Point>,
13548    display_map: &DisplaySnapshot,
13549    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13550) -> (MultiBufferRow, MultiBufferRow) {
13551    contiguous_row_selections.push(selection.clone());
13552    let start_row = MultiBufferRow(selection.start.row);
13553    let mut end_row = ending_row(selection, display_map);
13554
13555    while let Some(next_selection) = selections.peek() {
13556        if next_selection.start.row <= end_row.0 {
13557            end_row = ending_row(next_selection, display_map);
13558            contiguous_row_selections.push(selections.next().unwrap().clone());
13559        } else {
13560            break;
13561        }
13562    }
13563    (start_row, end_row)
13564}
13565
13566fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13567    if next_selection.end.column > 0 || next_selection.is_empty() {
13568        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13569    } else {
13570        MultiBufferRow(next_selection.end.row)
13571    }
13572}
13573
13574impl EditorSnapshot {
13575    pub fn remote_selections_in_range<'a>(
13576        &'a self,
13577        range: &'a Range<Anchor>,
13578        collaboration_hub: &dyn CollaborationHub,
13579        cx: &'a AppContext,
13580    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13581        let participant_names = collaboration_hub.user_names(cx);
13582        let participant_indices = collaboration_hub.user_participant_indices(cx);
13583        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13584        let collaborators_by_replica_id = collaborators_by_peer_id
13585            .iter()
13586            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13587            .collect::<HashMap<_, _>>();
13588        self.buffer_snapshot
13589            .selections_in_range(range, false)
13590            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13591                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13592                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13593                let user_name = participant_names.get(&collaborator.user_id).cloned();
13594                Some(RemoteSelection {
13595                    replica_id,
13596                    selection,
13597                    cursor_shape,
13598                    line_mode,
13599                    participant_index,
13600                    peer_id: collaborator.peer_id,
13601                    user_name,
13602                })
13603            })
13604    }
13605
13606    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13607        self.display_snapshot.buffer_snapshot.language_at(position)
13608    }
13609
13610    pub fn is_focused(&self) -> bool {
13611        self.is_focused
13612    }
13613
13614    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13615        self.placeholder_text.as_ref()
13616    }
13617
13618    pub fn scroll_position(&self) -> gpui::Point<f32> {
13619        self.scroll_anchor.scroll_position(&self.display_snapshot)
13620    }
13621
13622    fn gutter_dimensions(
13623        &self,
13624        font_id: FontId,
13625        font_size: Pixels,
13626        em_width: Pixels,
13627        em_advance: Pixels,
13628        max_line_number_width: Pixels,
13629        cx: &AppContext,
13630    ) -> GutterDimensions {
13631        if !self.show_gutter {
13632            return GutterDimensions::default();
13633        }
13634        let descent = cx.text_system().descent(font_id, font_size);
13635
13636        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13637            matches!(
13638                ProjectSettings::get_global(cx).git.git_gutter,
13639                Some(GitGutterSetting::TrackedFiles)
13640            )
13641        });
13642        let gutter_settings = EditorSettings::get_global(cx).gutter;
13643        let show_line_numbers = self
13644            .show_line_numbers
13645            .unwrap_or(gutter_settings.line_numbers);
13646        let line_gutter_width = if show_line_numbers {
13647            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13648            let min_width_for_number_on_gutter = em_advance * 4.0;
13649            max_line_number_width.max(min_width_for_number_on_gutter)
13650        } else {
13651            0.0.into()
13652        };
13653
13654        let show_code_actions = self
13655            .show_code_actions
13656            .unwrap_or(gutter_settings.code_actions);
13657
13658        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13659
13660        let git_blame_entries_width =
13661            self.git_blame_gutter_max_author_length
13662                .map(|max_author_length| {
13663                    // Length of the author name, but also space for the commit hash,
13664                    // the spacing and the timestamp.
13665                    let max_char_count = max_author_length
13666                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13667                        + 7 // length of commit sha
13668                        + 14 // length of max relative timestamp ("60 minutes ago")
13669                        + 4; // gaps and margins
13670
13671                    em_advance * max_char_count
13672                });
13673
13674        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13675        left_padding += if show_code_actions || show_runnables {
13676            em_width * 3.0
13677        } else if show_git_gutter && show_line_numbers {
13678            em_width * 2.0
13679        } else if show_git_gutter || show_line_numbers {
13680            em_width
13681        } else {
13682            px(0.)
13683        };
13684
13685        let right_padding = if gutter_settings.folds && show_line_numbers {
13686            em_width * 4.0
13687        } else if gutter_settings.folds {
13688            em_width * 3.0
13689        } else if show_line_numbers {
13690            em_width
13691        } else {
13692            px(0.)
13693        };
13694
13695        GutterDimensions {
13696            left_padding,
13697            right_padding,
13698            width: line_gutter_width + left_padding + right_padding,
13699            margin: -descent,
13700            git_blame_entries_width,
13701        }
13702    }
13703
13704    pub fn render_fold_toggle(
13705        &self,
13706        buffer_row: MultiBufferRow,
13707        row_contains_cursor: bool,
13708        editor: View<Editor>,
13709        cx: &mut WindowContext,
13710    ) -> Option<AnyElement> {
13711        let folded = self.is_line_folded(buffer_row);
13712
13713        if let Some(crease) = self
13714            .crease_snapshot
13715            .query_row(buffer_row, &self.buffer_snapshot)
13716        {
13717            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13718                if folded {
13719                    editor.update(cx, |editor, cx| {
13720                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13721                    });
13722                } else {
13723                    editor.update(cx, |editor, cx| {
13724                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13725                    });
13726                }
13727            });
13728
13729            Some((crease.render_toggle)(
13730                buffer_row,
13731                folded,
13732                toggle_callback,
13733                cx,
13734            ))
13735        } else if folded
13736            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13737        {
13738            Some(
13739                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13740                    .selected(folded)
13741                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13742                        if folded {
13743                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13744                        } else {
13745                            this.fold_at(&FoldAt { buffer_row }, cx);
13746                        }
13747                    }))
13748                    .into_any_element(),
13749            )
13750        } else {
13751            None
13752        }
13753    }
13754
13755    pub fn render_crease_trailer(
13756        &self,
13757        buffer_row: MultiBufferRow,
13758        cx: &mut WindowContext,
13759    ) -> Option<AnyElement> {
13760        let folded = self.is_line_folded(buffer_row);
13761        let crease = self
13762            .crease_snapshot
13763            .query_row(buffer_row, &self.buffer_snapshot)?;
13764        Some((crease.render_trailer)(buffer_row, folded, cx))
13765    }
13766}
13767
13768impl Deref for EditorSnapshot {
13769    type Target = DisplaySnapshot;
13770
13771    fn deref(&self) -> &Self::Target {
13772        &self.display_snapshot
13773    }
13774}
13775
13776#[derive(Clone, Debug, PartialEq, Eq)]
13777pub enum EditorEvent {
13778    InputIgnored {
13779        text: Arc<str>,
13780    },
13781    InputHandled {
13782        utf16_range_to_replace: Option<Range<isize>>,
13783        text: Arc<str>,
13784    },
13785    ExcerptsAdded {
13786        buffer: Model<Buffer>,
13787        predecessor: ExcerptId,
13788        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13789    },
13790    ExcerptsRemoved {
13791        ids: Vec<ExcerptId>,
13792    },
13793    ExcerptsEdited {
13794        ids: Vec<ExcerptId>,
13795    },
13796    ExcerptsExpanded {
13797        ids: Vec<ExcerptId>,
13798    },
13799    BufferEdited,
13800    Edited {
13801        transaction_id: clock::Lamport,
13802    },
13803    Reparsed(BufferId),
13804    Focused,
13805    FocusedIn,
13806    Blurred,
13807    DirtyChanged,
13808    Saved,
13809    TitleChanged,
13810    DiffBaseChanged,
13811    SelectionsChanged {
13812        local: bool,
13813    },
13814    ScrollPositionChanged {
13815        local: bool,
13816        autoscroll: bool,
13817    },
13818    Closed,
13819    TransactionUndone {
13820        transaction_id: clock::Lamport,
13821    },
13822    TransactionBegun {
13823        transaction_id: clock::Lamport,
13824    },
13825    Reloaded,
13826    CursorShapeChanged,
13827}
13828
13829impl EventEmitter<EditorEvent> for Editor {}
13830
13831impl FocusableView for Editor {
13832    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13833        self.focus_handle.clone()
13834    }
13835}
13836
13837impl Render for Editor {
13838    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13839        let settings = ThemeSettings::get_global(cx);
13840
13841        let mut text_style = match self.mode {
13842            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13843                color: cx.theme().colors().editor_foreground,
13844                font_family: settings.ui_font.family.clone(),
13845                font_features: settings.ui_font.features.clone(),
13846                font_fallbacks: settings.ui_font.fallbacks.clone(),
13847                font_size: rems(0.875).into(),
13848                font_weight: settings.ui_font.weight,
13849                line_height: relative(settings.buffer_line_height.value()),
13850                ..Default::default()
13851            },
13852            EditorMode::Full => TextStyle {
13853                color: cx.theme().colors().editor_foreground,
13854                font_family: settings.buffer_font.family.clone(),
13855                font_features: settings.buffer_font.features.clone(),
13856                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13857                font_size: settings.buffer_font_size(cx).into(),
13858                font_weight: settings.buffer_font.weight,
13859                line_height: relative(settings.buffer_line_height.value()),
13860                ..Default::default()
13861            },
13862        };
13863        if let Some(text_style_refinement) = &self.text_style_refinement {
13864            text_style.refine(text_style_refinement)
13865        }
13866
13867        let background = match self.mode {
13868            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13869            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13870            EditorMode::Full => cx.theme().colors().editor_background,
13871        };
13872
13873        EditorElement::new(
13874            cx.view(),
13875            EditorStyle {
13876                background,
13877                local_player: cx.theme().players().local(),
13878                text: text_style,
13879                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13880                syntax: cx.theme().syntax().clone(),
13881                status: cx.theme().status().clone(),
13882                inlay_hints_style: make_inlay_hints_style(cx),
13883                suggestions_style: HighlightStyle {
13884                    color: Some(cx.theme().status().predictive),
13885                    ..HighlightStyle::default()
13886                },
13887                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13888            },
13889        )
13890    }
13891}
13892
13893impl ViewInputHandler for Editor {
13894    fn text_for_range(
13895        &mut self,
13896        range_utf16: Range<usize>,
13897        cx: &mut ViewContext<Self>,
13898    ) -> Option<String> {
13899        Some(
13900            self.buffer
13901                .read(cx)
13902                .read(cx)
13903                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13904                .collect(),
13905        )
13906    }
13907
13908    fn selected_text_range(
13909        &mut self,
13910        ignore_disabled_input: bool,
13911        cx: &mut ViewContext<Self>,
13912    ) -> Option<UTF16Selection> {
13913        // Prevent the IME menu from appearing when holding down an alphabetic key
13914        // while input is disabled.
13915        if !ignore_disabled_input && !self.input_enabled {
13916            return None;
13917        }
13918
13919        let selection = self.selections.newest::<OffsetUtf16>(cx);
13920        let range = selection.range();
13921
13922        Some(UTF16Selection {
13923            range: range.start.0..range.end.0,
13924            reversed: selection.reversed,
13925        })
13926    }
13927
13928    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13929        let snapshot = self.buffer.read(cx).read(cx);
13930        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13931        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13932    }
13933
13934    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13935        self.clear_highlights::<InputComposition>(cx);
13936        self.ime_transaction.take();
13937    }
13938
13939    fn replace_text_in_range(
13940        &mut self,
13941        range_utf16: Option<Range<usize>>,
13942        text: &str,
13943        cx: &mut ViewContext<Self>,
13944    ) {
13945        if !self.input_enabled {
13946            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13947            return;
13948        }
13949
13950        self.transact(cx, |this, cx| {
13951            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13952                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13953                Some(this.selection_replacement_ranges(range_utf16, cx))
13954            } else {
13955                this.marked_text_ranges(cx)
13956            };
13957
13958            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13959                let newest_selection_id = this.selections.newest_anchor().id;
13960                this.selections
13961                    .all::<OffsetUtf16>(cx)
13962                    .iter()
13963                    .zip(ranges_to_replace.iter())
13964                    .find_map(|(selection, range)| {
13965                        if selection.id == newest_selection_id {
13966                            Some(
13967                                (range.start.0 as isize - selection.head().0 as isize)
13968                                    ..(range.end.0 as isize - selection.head().0 as isize),
13969                            )
13970                        } else {
13971                            None
13972                        }
13973                    })
13974            });
13975
13976            cx.emit(EditorEvent::InputHandled {
13977                utf16_range_to_replace: range_to_replace,
13978                text: text.into(),
13979            });
13980
13981            if let Some(new_selected_ranges) = new_selected_ranges {
13982                this.change_selections(None, cx, |selections| {
13983                    selections.select_ranges(new_selected_ranges)
13984                });
13985                this.backspace(&Default::default(), cx);
13986            }
13987
13988            this.handle_input(text, cx);
13989        });
13990
13991        if let Some(transaction) = self.ime_transaction {
13992            self.buffer.update(cx, |buffer, cx| {
13993                buffer.group_until_transaction(transaction, cx);
13994            });
13995        }
13996
13997        self.unmark_text(cx);
13998    }
13999
14000    fn replace_and_mark_text_in_range(
14001        &mut self,
14002        range_utf16: Option<Range<usize>>,
14003        text: &str,
14004        new_selected_range_utf16: Option<Range<usize>>,
14005        cx: &mut ViewContext<Self>,
14006    ) {
14007        if !self.input_enabled {
14008            return;
14009        }
14010
14011        let transaction = self.transact(cx, |this, cx| {
14012            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14013                let snapshot = this.buffer.read(cx).read(cx);
14014                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14015                    for marked_range in &mut marked_ranges {
14016                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14017                        marked_range.start.0 += relative_range_utf16.start;
14018                        marked_range.start =
14019                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14020                        marked_range.end =
14021                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14022                    }
14023                }
14024                Some(marked_ranges)
14025            } else if let Some(range_utf16) = range_utf16 {
14026                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14027                Some(this.selection_replacement_ranges(range_utf16, cx))
14028            } else {
14029                None
14030            };
14031
14032            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14033                let newest_selection_id = this.selections.newest_anchor().id;
14034                this.selections
14035                    .all::<OffsetUtf16>(cx)
14036                    .iter()
14037                    .zip(ranges_to_replace.iter())
14038                    .find_map(|(selection, range)| {
14039                        if selection.id == newest_selection_id {
14040                            Some(
14041                                (range.start.0 as isize - selection.head().0 as isize)
14042                                    ..(range.end.0 as isize - selection.head().0 as isize),
14043                            )
14044                        } else {
14045                            None
14046                        }
14047                    })
14048            });
14049
14050            cx.emit(EditorEvent::InputHandled {
14051                utf16_range_to_replace: range_to_replace,
14052                text: text.into(),
14053            });
14054
14055            if let Some(ranges) = ranges_to_replace {
14056                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14057            }
14058
14059            let marked_ranges = {
14060                let snapshot = this.buffer.read(cx).read(cx);
14061                this.selections
14062                    .disjoint_anchors()
14063                    .iter()
14064                    .map(|selection| {
14065                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14066                    })
14067                    .collect::<Vec<_>>()
14068            };
14069
14070            if text.is_empty() {
14071                this.unmark_text(cx);
14072            } else {
14073                this.highlight_text::<InputComposition>(
14074                    marked_ranges.clone(),
14075                    HighlightStyle {
14076                        underline: Some(UnderlineStyle {
14077                            thickness: px(1.),
14078                            color: None,
14079                            wavy: false,
14080                        }),
14081                        ..Default::default()
14082                    },
14083                    cx,
14084                );
14085            }
14086
14087            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14088            let use_autoclose = this.use_autoclose;
14089            let use_auto_surround = this.use_auto_surround;
14090            this.set_use_autoclose(false);
14091            this.set_use_auto_surround(false);
14092            this.handle_input(text, cx);
14093            this.set_use_autoclose(use_autoclose);
14094            this.set_use_auto_surround(use_auto_surround);
14095
14096            if let Some(new_selected_range) = new_selected_range_utf16 {
14097                let snapshot = this.buffer.read(cx).read(cx);
14098                let new_selected_ranges = marked_ranges
14099                    .into_iter()
14100                    .map(|marked_range| {
14101                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14102                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14103                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14104                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14105                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14106                    })
14107                    .collect::<Vec<_>>();
14108
14109                drop(snapshot);
14110                this.change_selections(None, cx, |selections| {
14111                    selections.select_ranges(new_selected_ranges)
14112                });
14113            }
14114        });
14115
14116        self.ime_transaction = self.ime_transaction.or(transaction);
14117        if let Some(transaction) = self.ime_transaction {
14118            self.buffer.update(cx, |buffer, cx| {
14119                buffer.group_until_transaction(transaction, cx);
14120            });
14121        }
14122
14123        if self.text_highlights::<InputComposition>(cx).is_none() {
14124            self.ime_transaction.take();
14125        }
14126    }
14127
14128    fn bounds_for_range(
14129        &mut self,
14130        range_utf16: Range<usize>,
14131        element_bounds: gpui::Bounds<Pixels>,
14132        cx: &mut ViewContext<Self>,
14133    ) -> Option<gpui::Bounds<Pixels>> {
14134        let text_layout_details = self.text_layout_details(cx);
14135        let style = &text_layout_details.editor_style;
14136        let font_id = cx.text_system().resolve_font(&style.text.font());
14137        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14138        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14139
14140        let em_width = cx
14141            .text_system()
14142            .typographic_bounds(font_id, font_size, 'm')
14143            .unwrap()
14144            .size
14145            .width;
14146
14147        let snapshot = self.snapshot(cx);
14148        let scroll_position = snapshot.scroll_position();
14149        let scroll_left = scroll_position.x * em_width;
14150
14151        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14152        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14153            + self.gutter_dimensions.width;
14154        let y = line_height * (start.row().as_f32() - scroll_position.y);
14155
14156        Some(Bounds {
14157            origin: element_bounds.origin + point(x, y),
14158            size: size(em_width, line_height),
14159        })
14160    }
14161}
14162
14163trait SelectionExt {
14164    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14165    fn spanned_rows(
14166        &self,
14167        include_end_if_at_line_start: bool,
14168        map: &DisplaySnapshot,
14169    ) -> Range<MultiBufferRow>;
14170}
14171
14172impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14173    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14174        let start = self
14175            .start
14176            .to_point(&map.buffer_snapshot)
14177            .to_display_point(map);
14178        let end = self
14179            .end
14180            .to_point(&map.buffer_snapshot)
14181            .to_display_point(map);
14182        if self.reversed {
14183            end..start
14184        } else {
14185            start..end
14186        }
14187    }
14188
14189    fn spanned_rows(
14190        &self,
14191        include_end_if_at_line_start: bool,
14192        map: &DisplaySnapshot,
14193    ) -> Range<MultiBufferRow> {
14194        let start = self.start.to_point(&map.buffer_snapshot);
14195        let mut end = self.end.to_point(&map.buffer_snapshot);
14196        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14197            end.row -= 1;
14198        }
14199
14200        let buffer_start = map.prev_line_boundary(start).0;
14201        let buffer_end = map.next_line_boundary(end).0;
14202        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14203    }
14204}
14205
14206impl<T: InvalidationRegion> InvalidationStack<T> {
14207    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14208    where
14209        S: Clone + ToOffset,
14210    {
14211        while let Some(region) = self.last() {
14212            let all_selections_inside_invalidation_ranges =
14213                if selections.len() == region.ranges().len() {
14214                    selections
14215                        .iter()
14216                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14217                        .all(|(selection, invalidation_range)| {
14218                            let head = selection.head().to_offset(buffer);
14219                            invalidation_range.start <= head && invalidation_range.end >= head
14220                        })
14221                } else {
14222                    false
14223                };
14224
14225            if all_selections_inside_invalidation_ranges {
14226                break;
14227            } else {
14228                self.pop();
14229            }
14230        }
14231    }
14232}
14233
14234impl<T> Default for InvalidationStack<T> {
14235    fn default() -> Self {
14236        Self(Default::default())
14237    }
14238}
14239
14240impl<T> Deref for InvalidationStack<T> {
14241    type Target = Vec<T>;
14242
14243    fn deref(&self) -> &Self::Target {
14244        &self.0
14245    }
14246}
14247
14248impl<T> DerefMut for InvalidationStack<T> {
14249    fn deref_mut(&mut self) -> &mut Self::Target {
14250        &mut self.0
14251    }
14252}
14253
14254impl InvalidationRegion for SnippetState {
14255    fn ranges(&self) -> &[Range<Anchor>] {
14256        &self.ranges[self.active_index]
14257    }
14258}
14259
14260pub fn diagnostic_block_renderer(
14261    diagnostic: Diagnostic,
14262    max_message_rows: Option<u8>,
14263    allow_closing: bool,
14264    _is_valid: bool,
14265) -> RenderBlock {
14266    let (text_without_backticks, code_ranges) =
14267        highlight_diagnostic_message(&diagnostic, max_message_rows);
14268
14269    Box::new(move |cx: &mut BlockContext| {
14270        let group_id: SharedString = cx.block_id.to_string().into();
14271
14272        let mut text_style = cx.text_style().clone();
14273        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14274        let theme_settings = ThemeSettings::get_global(cx);
14275        text_style.font_family = theme_settings.buffer_font.family.clone();
14276        text_style.font_style = theme_settings.buffer_font.style;
14277        text_style.font_features = theme_settings.buffer_font.features.clone();
14278        text_style.font_weight = theme_settings.buffer_font.weight;
14279
14280        let multi_line_diagnostic = diagnostic.message.contains('\n');
14281
14282        let buttons = |diagnostic: &Diagnostic| {
14283            if multi_line_diagnostic {
14284                v_flex()
14285            } else {
14286                h_flex()
14287            }
14288            .when(allow_closing, |div| {
14289                div.children(diagnostic.is_primary.then(|| {
14290                    IconButton::new("close-block", IconName::XCircle)
14291                        .icon_color(Color::Muted)
14292                        .size(ButtonSize::Compact)
14293                        .style(ButtonStyle::Transparent)
14294                        .visible_on_hover(group_id.clone())
14295                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14296                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14297                }))
14298            })
14299            .child(
14300                IconButton::new("copy-block", IconName::Copy)
14301                    .icon_color(Color::Muted)
14302                    .size(ButtonSize::Compact)
14303                    .style(ButtonStyle::Transparent)
14304                    .visible_on_hover(group_id.clone())
14305                    .on_click({
14306                        let message = diagnostic.message.clone();
14307                        move |_click, cx| {
14308                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14309                        }
14310                    })
14311                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14312            )
14313        };
14314
14315        let icon_size = buttons(&diagnostic)
14316            .into_any_element()
14317            .layout_as_root(AvailableSpace::min_size(), cx);
14318
14319        h_flex()
14320            .id(cx.block_id)
14321            .group(group_id.clone())
14322            .relative()
14323            .size_full()
14324            .pl(cx.gutter_dimensions.width)
14325            .w(cx.max_width - cx.gutter_dimensions.full_width())
14326            .child(
14327                div()
14328                    .flex()
14329                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14330                    .flex_shrink(),
14331            )
14332            .child(buttons(&diagnostic))
14333            .child(div().flex().flex_shrink_0().child(
14334                StyledText::new(text_without_backticks.clone()).with_highlights(
14335                    &text_style,
14336                    code_ranges.iter().map(|range| {
14337                        (
14338                            range.clone(),
14339                            HighlightStyle {
14340                                font_weight: Some(FontWeight::BOLD),
14341                                ..Default::default()
14342                            },
14343                        )
14344                    }),
14345                ),
14346            ))
14347            .into_any_element()
14348    })
14349}
14350
14351pub fn highlight_diagnostic_message(
14352    diagnostic: &Diagnostic,
14353    mut max_message_rows: Option<u8>,
14354) -> (SharedString, Vec<Range<usize>>) {
14355    let mut text_without_backticks = String::new();
14356    let mut code_ranges = Vec::new();
14357
14358    if let Some(source) = &diagnostic.source {
14359        text_without_backticks.push_str(source);
14360        code_ranges.push(0..source.len());
14361        text_without_backticks.push_str(": ");
14362    }
14363
14364    let mut prev_offset = 0;
14365    let mut in_code_block = false;
14366    let has_row_limit = max_message_rows.is_some();
14367    let mut newline_indices = diagnostic
14368        .message
14369        .match_indices('\n')
14370        .filter(|_| has_row_limit)
14371        .map(|(ix, _)| ix)
14372        .fuse()
14373        .peekable();
14374
14375    for (quote_ix, _) in diagnostic
14376        .message
14377        .match_indices('`')
14378        .chain([(diagnostic.message.len(), "")])
14379    {
14380        let mut first_newline_ix = None;
14381        let mut last_newline_ix = None;
14382        while let Some(newline_ix) = newline_indices.peek() {
14383            if *newline_ix < quote_ix {
14384                if first_newline_ix.is_none() {
14385                    first_newline_ix = Some(*newline_ix);
14386                }
14387                last_newline_ix = Some(*newline_ix);
14388
14389                if let Some(rows_left) = &mut max_message_rows {
14390                    if *rows_left == 0 {
14391                        break;
14392                    } else {
14393                        *rows_left -= 1;
14394                    }
14395                }
14396                let _ = newline_indices.next();
14397            } else {
14398                break;
14399            }
14400        }
14401        let prev_len = text_without_backticks.len();
14402        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14403        text_without_backticks.push_str(new_text);
14404        if in_code_block {
14405            code_ranges.push(prev_len..text_without_backticks.len());
14406        }
14407        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14408        in_code_block = !in_code_block;
14409        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14410            text_without_backticks.push_str("...");
14411            break;
14412        }
14413    }
14414
14415    (text_without_backticks.into(), code_ranges)
14416}
14417
14418fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14419    match severity {
14420        DiagnosticSeverity::ERROR => colors.error,
14421        DiagnosticSeverity::WARNING => colors.warning,
14422        DiagnosticSeverity::INFORMATION => colors.info,
14423        DiagnosticSeverity::HINT => colors.info,
14424        _ => colors.ignored,
14425    }
14426}
14427
14428pub fn styled_runs_for_code_label<'a>(
14429    label: &'a CodeLabel,
14430    syntax_theme: &'a theme::SyntaxTheme,
14431) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14432    let fade_out = HighlightStyle {
14433        fade_out: Some(0.35),
14434        ..Default::default()
14435    };
14436
14437    let mut prev_end = label.filter_range.end;
14438    label
14439        .runs
14440        .iter()
14441        .enumerate()
14442        .flat_map(move |(ix, (range, highlight_id))| {
14443            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14444                style
14445            } else {
14446                return Default::default();
14447            };
14448            let mut muted_style = style;
14449            muted_style.highlight(fade_out);
14450
14451            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14452            if range.start >= label.filter_range.end {
14453                if range.start > prev_end {
14454                    runs.push((prev_end..range.start, fade_out));
14455                }
14456                runs.push((range.clone(), muted_style));
14457            } else if range.end <= label.filter_range.end {
14458                runs.push((range.clone(), style));
14459            } else {
14460                runs.push((range.start..label.filter_range.end, style));
14461                runs.push((label.filter_range.end..range.end, muted_style));
14462            }
14463            prev_end = cmp::max(prev_end, range.end);
14464
14465            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14466                runs.push((prev_end..label.text.len(), fade_out));
14467            }
14468
14469            runs
14470        })
14471}
14472
14473pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14474    let mut prev_index = 0;
14475    let mut prev_codepoint: Option<char> = None;
14476    text.char_indices()
14477        .chain([(text.len(), '\0')])
14478        .filter_map(move |(index, codepoint)| {
14479            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14480            let is_boundary = index == text.len()
14481                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14482                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14483            if is_boundary {
14484                let chunk = &text[prev_index..index];
14485                prev_index = index;
14486                Some(chunk)
14487            } else {
14488                None
14489            }
14490        })
14491}
14492
14493pub trait RangeToAnchorExt: Sized {
14494    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14495
14496    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14497        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14498        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14499    }
14500}
14501
14502impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14503    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14504        let start_offset = self.start.to_offset(snapshot);
14505        let end_offset = self.end.to_offset(snapshot);
14506        if start_offset == end_offset {
14507            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14508        } else {
14509            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14510        }
14511    }
14512}
14513
14514pub trait RowExt {
14515    fn as_f32(&self) -> f32;
14516
14517    fn next_row(&self) -> Self;
14518
14519    fn previous_row(&self) -> Self;
14520
14521    fn minus(&self, other: Self) -> u32;
14522}
14523
14524impl RowExt for DisplayRow {
14525    fn as_f32(&self) -> f32 {
14526        self.0 as f32
14527    }
14528
14529    fn next_row(&self) -> Self {
14530        Self(self.0 + 1)
14531    }
14532
14533    fn previous_row(&self) -> Self {
14534        Self(self.0.saturating_sub(1))
14535    }
14536
14537    fn minus(&self, other: Self) -> u32 {
14538        self.0 - other.0
14539    }
14540}
14541
14542impl RowExt for MultiBufferRow {
14543    fn as_f32(&self) -> f32 {
14544        self.0 as f32
14545    }
14546
14547    fn next_row(&self) -> Self {
14548        Self(self.0 + 1)
14549    }
14550
14551    fn previous_row(&self) -> Self {
14552        Self(self.0.saturating_sub(1))
14553    }
14554
14555    fn minus(&self, other: Self) -> u32 {
14556        self.0 - other.0
14557    }
14558}
14559
14560trait RowRangeExt {
14561    type Row;
14562
14563    fn len(&self) -> usize;
14564
14565    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14566}
14567
14568impl RowRangeExt for Range<MultiBufferRow> {
14569    type Row = MultiBufferRow;
14570
14571    fn len(&self) -> usize {
14572        (self.end.0 - self.start.0) as usize
14573    }
14574
14575    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14576        (self.start.0..self.end.0).map(MultiBufferRow)
14577    }
14578}
14579
14580impl RowRangeExt for Range<DisplayRow> {
14581    type Row = DisplayRow;
14582
14583    fn len(&self) -> usize {
14584        (self.end.0 - self.start.0) as usize
14585    }
14586
14587    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14588        (self.start.0..self.end.0).map(DisplayRow)
14589    }
14590}
14591
14592fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14593    if hunk.diff_base_byte_range.is_empty() {
14594        DiffHunkStatus::Added
14595    } else if hunk.row_range.is_empty() {
14596        DiffHunkStatus::Removed
14597    } else {
14598        DiffHunkStatus::Modified
14599    }
14600}
14601
14602/// If select range has more than one line, we
14603/// just point the cursor to range.start.
14604fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14605    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14606        range
14607    } else {
14608        range.start..range.start
14609    }
14610}