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 our fuzzy-finder score first and for the weak
 1357                // matches, we prefer language-server sort_text first.
 1358                //
 1359                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1360                // Rest of the matches(weak) can be sorted as language-server expects.
 1361
 1362                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1363                enum MatchScore<'a> {
 1364                    Strong {
 1365                        score: Reverse<OrderedFloat<f64>>,
 1366                        sort_text: Option<&'a str>,
 1367                        sort_key: (usize, &'a str),
 1368                    },
 1369                    Weak {
 1370                        sort_text: Option<&'a str>,
 1371                        score: Reverse<OrderedFloat<f64>>,
 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                        score,
 1384                        sort_text,
 1385                        sort_key,
 1386                    }
 1387                } else {
 1388                    MatchScore::Weak {
 1389                        sort_text,
 1390                        score,
 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            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7012
 7013            // Since not all lines in the selection may be at the same indent
 7014            // level, choose the indent size that is the most common between all
 7015            // of the lines.
 7016            //
 7017            // If there is a tie, we use the deepest indent.
 7018            let (indent_size, indent_end) = {
 7019                let mut indent_size_occurrences = HashMap::default();
 7020                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7021
 7022                for row in start_row..=end_row {
 7023                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7024                    rows_by_indent_size.entry(indent).or_default().push(row);
 7025                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7026                }
 7027
 7028                let indent_size = indent_size_occurrences
 7029                    .into_iter()
 7030                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7031                    .map(|(indent, _)| indent)
 7032                    .unwrap_or_default();
 7033                let row = rows_by_indent_size[&indent_size][0];
 7034                let indent_end = Point::new(row, indent_size.len);
 7035
 7036                (indent_size, indent_end)
 7037            };
 7038
 7039            let mut line_prefix = indent_size.chars().collect::<String>();
 7040
 7041            if let Some(comment_prefix) =
 7042                buffer
 7043                    .language_scope_at(selection.head())
 7044                    .and_then(|language| {
 7045                        language
 7046                            .line_comment_prefixes()
 7047                            .iter()
 7048                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7049                            .cloned()
 7050                    })
 7051            {
 7052                line_prefix.push_str(&comment_prefix);
 7053                should_rewrap = true;
 7054            }
 7055
 7056            if !should_rewrap {
 7057                continue;
 7058            }
 7059
 7060            if selection.is_empty() {
 7061                'expand_upwards: while start_row > 0 {
 7062                    let prev_row = start_row - 1;
 7063                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7064                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7065                    {
 7066                        start_row = prev_row;
 7067                    } else {
 7068                        break 'expand_upwards;
 7069                    }
 7070                }
 7071
 7072                'expand_downwards: while end_row < buffer.max_point().row {
 7073                    let next_row = end_row + 1;
 7074                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7075                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7076                    {
 7077                        end_row = next_row;
 7078                    } else {
 7079                        break 'expand_downwards;
 7080                    }
 7081                }
 7082            }
 7083
 7084            let start = Point::new(start_row, 0);
 7085            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7086            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7087            let Some(lines_without_prefixes) = selection_text
 7088                .lines()
 7089                .map(|line| {
 7090                    line.strip_prefix(&line_prefix)
 7091                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7092                        .ok_or_else(|| {
 7093                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7094                        })
 7095                })
 7096                .collect::<Result<Vec<_>, _>>()
 7097                .log_err()
 7098            else {
 7099                continue;
 7100            };
 7101
 7102            let wrap_column = buffer
 7103                .settings_at(Point::new(start_row, 0), cx)
 7104                .preferred_line_length as usize;
 7105            let wrapped_text = wrap_with_prefix(
 7106                line_prefix,
 7107                lines_without_prefixes.join(" "),
 7108                wrap_column,
 7109                tab_size,
 7110            );
 7111
 7112            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7113            let mut offset = start.to_offset(&buffer);
 7114            let mut moved_since_edit = true;
 7115
 7116            for change in diff.iter_all_changes() {
 7117                let value = change.value();
 7118                match change.tag() {
 7119                    ChangeTag::Equal => {
 7120                        offset += value.len();
 7121                        moved_since_edit = true;
 7122                    }
 7123                    ChangeTag::Delete => {
 7124                        let start = buffer.anchor_after(offset);
 7125                        let end = buffer.anchor_before(offset + value.len());
 7126
 7127                        if moved_since_edit {
 7128                            edits.push((start..end, String::new()));
 7129                        } else {
 7130                            edits.last_mut().unwrap().0.end = end;
 7131                        }
 7132
 7133                        offset += value.len();
 7134                        moved_since_edit = false;
 7135                    }
 7136                    ChangeTag::Insert => {
 7137                        if moved_since_edit {
 7138                            let anchor = buffer.anchor_after(offset);
 7139                            edits.push((anchor..anchor, value.to_string()));
 7140                        } else {
 7141                            edits.last_mut().unwrap().1.push_str(value);
 7142                        }
 7143
 7144                        moved_since_edit = false;
 7145                    }
 7146                }
 7147            }
 7148
 7149            rewrapped_row_ranges.push(start_row..=end_row);
 7150        }
 7151
 7152        self.buffer
 7153            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7154    }
 7155
 7156    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7157        let mut text = String::new();
 7158        let buffer = self.buffer.read(cx).snapshot(cx);
 7159        let mut selections = self.selections.all::<Point>(cx);
 7160        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7161        {
 7162            let max_point = buffer.max_point();
 7163            let mut is_first = true;
 7164            for selection in &mut selections {
 7165                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7166                if is_entire_line {
 7167                    selection.start = Point::new(selection.start.row, 0);
 7168                    if !selection.is_empty() && selection.end.column == 0 {
 7169                        selection.end = cmp::min(max_point, selection.end);
 7170                    } else {
 7171                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7172                    }
 7173                    selection.goal = SelectionGoal::None;
 7174                }
 7175                if is_first {
 7176                    is_first = false;
 7177                } else {
 7178                    text += "\n";
 7179                }
 7180                let mut len = 0;
 7181                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7182                    text.push_str(chunk);
 7183                    len += chunk.len();
 7184                }
 7185                clipboard_selections.push(ClipboardSelection {
 7186                    len,
 7187                    is_entire_line,
 7188                    first_line_indent: buffer
 7189                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7190                        .len,
 7191                });
 7192            }
 7193        }
 7194
 7195        self.transact(cx, |this, cx| {
 7196            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7197                s.select(selections);
 7198            });
 7199            this.insert("", cx);
 7200            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7201                text,
 7202                clipboard_selections,
 7203            ));
 7204        });
 7205    }
 7206
 7207    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7208        let selections = self.selections.all::<Point>(cx);
 7209        let buffer = self.buffer.read(cx).read(cx);
 7210        let mut text = String::new();
 7211
 7212        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7213        {
 7214            let max_point = buffer.max_point();
 7215            let mut is_first = true;
 7216            for selection in selections.iter() {
 7217                let mut start = selection.start;
 7218                let mut end = selection.end;
 7219                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7220                if is_entire_line {
 7221                    start = Point::new(start.row, 0);
 7222                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7223                }
 7224                if is_first {
 7225                    is_first = false;
 7226                } else {
 7227                    text += "\n";
 7228                }
 7229                let mut len = 0;
 7230                for chunk in buffer.text_for_range(start..end) {
 7231                    text.push_str(chunk);
 7232                    len += chunk.len();
 7233                }
 7234                clipboard_selections.push(ClipboardSelection {
 7235                    len,
 7236                    is_entire_line,
 7237                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7238                });
 7239            }
 7240        }
 7241
 7242        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7243            text,
 7244            clipboard_selections,
 7245        ));
 7246    }
 7247
 7248    pub fn do_paste(
 7249        &mut self,
 7250        text: &String,
 7251        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7252        handle_entire_lines: bool,
 7253        cx: &mut ViewContext<Self>,
 7254    ) {
 7255        if self.read_only(cx) {
 7256            return;
 7257        }
 7258
 7259        let clipboard_text = Cow::Borrowed(text);
 7260
 7261        self.transact(cx, |this, cx| {
 7262            if let Some(mut clipboard_selections) = clipboard_selections {
 7263                let old_selections = this.selections.all::<usize>(cx);
 7264                let all_selections_were_entire_line =
 7265                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7266                let first_selection_indent_column =
 7267                    clipboard_selections.first().map(|s| s.first_line_indent);
 7268                if clipboard_selections.len() != old_selections.len() {
 7269                    clipboard_selections.drain(..);
 7270                }
 7271                let cursor_offset = this.selections.last::<usize>(cx).head();
 7272                let mut auto_indent_on_paste = true;
 7273
 7274                this.buffer.update(cx, |buffer, cx| {
 7275                    let snapshot = buffer.read(cx);
 7276                    auto_indent_on_paste =
 7277                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7278
 7279                    let mut start_offset = 0;
 7280                    let mut edits = Vec::new();
 7281                    let mut original_indent_columns = Vec::new();
 7282                    for (ix, selection) in old_selections.iter().enumerate() {
 7283                        let to_insert;
 7284                        let entire_line;
 7285                        let original_indent_column;
 7286                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7287                            let end_offset = start_offset + clipboard_selection.len;
 7288                            to_insert = &clipboard_text[start_offset..end_offset];
 7289                            entire_line = clipboard_selection.is_entire_line;
 7290                            start_offset = end_offset + 1;
 7291                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7292                        } else {
 7293                            to_insert = clipboard_text.as_str();
 7294                            entire_line = all_selections_were_entire_line;
 7295                            original_indent_column = first_selection_indent_column
 7296                        }
 7297
 7298                        // If the corresponding selection was empty when this slice of the
 7299                        // clipboard text was written, then the entire line containing the
 7300                        // selection was copied. If this selection is also currently empty,
 7301                        // then paste the line before the current line of the buffer.
 7302                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7303                            let column = selection.start.to_point(&snapshot).column as usize;
 7304                            let line_start = selection.start - column;
 7305                            line_start..line_start
 7306                        } else {
 7307                            selection.range()
 7308                        };
 7309
 7310                        edits.push((range, to_insert));
 7311                        original_indent_columns.extend(original_indent_column);
 7312                    }
 7313                    drop(snapshot);
 7314
 7315                    buffer.edit(
 7316                        edits,
 7317                        if auto_indent_on_paste {
 7318                            Some(AutoindentMode::Block {
 7319                                original_indent_columns,
 7320                            })
 7321                        } else {
 7322                            None
 7323                        },
 7324                        cx,
 7325                    );
 7326                });
 7327
 7328                let selections = this.selections.all::<usize>(cx);
 7329                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7330            } else {
 7331                this.insert(&clipboard_text, cx);
 7332            }
 7333        });
 7334    }
 7335
 7336    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7337        if let Some(item) = cx.read_from_clipboard() {
 7338            let entries = item.entries();
 7339
 7340            match entries.first() {
 7341                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7342                // of all the pasted entries.
 7343                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7344                    .do_paste(
 7345                        clipboard_string.text(),
 7346                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7347                        true,
 7348                        cx,
 7349                    ),
 7350                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7351            }
 7352        }
 7353    }
 7354
 7355    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7356        if self.read_only(cx) {
 7357            return;
 7358        }
 7359
 7360        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7361            if let Some((selections, _)) =
 7362                self.selection_history.transaction(transaction_id).cloned()
 7363            {
 7364                self.change_selections(None, cx, |s| {
 7365                    s.select_anchors(selections.to_vec());
 7366                });
 7367            }
 7368            self.request_autoscroll(Autoscroll::fit(), cx);
 7369            self.unmark_text(cx);
 7370            self.refresh_inline_completion(true, false, cx);
 7371            cx.emit(EditorEvent::Edited { transaction_id });
 7372            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7373        }
 7374    }
 7375
 7376    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7377        if self.read_only(cx) {
 7378            return;
 7379        }
 7380
 7381        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7382            if let Some((_, Some(selections))) =
 7383                self.selection_history.transaction(transaction_id).cloned()
 7384            {
 7385                self.change_selections(None, cx, |s| {
 7386                    s.select_anchors(selections.to_vec());
 7387                });
 7388            }
 7389            self.request_autoscroll(Autoscroll::fit(), cx);
 7390            self.unmark_text(cx);
 7391            self.refresh_inline_completion(true, false, cx);
 7392            cx.emit(EditorEvent::Edited { transaction_id });
 7393        }
 7394    }
 7395
 7396    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7397        self.buffer
 7398            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7399    }
 7400
 7401    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7402        self.buffer
 7403            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7404    }
 7405
 7406    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7407        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7408            let line_mode = s.line_mode;
 7409            s.move_with(|map, selection| {
 7410                let cursor = if selection.is_empty() && !line_mode {
 7411                    movement::left(map, selection.start)
 7412                } else {
 7413                    selection.start
 7414                };
 7415                selection.collapse_to(cursor, SelectionGoal::None);
 7416            });
 7417        })
 7418    }
 7419
 7420    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7421        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7422            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7423        })
 7424    }
 7425
 7426    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7427        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7428            let line_mode = s.line_mode;
 7429            s.move_with(|map, selection| {
 7430                let cursor = if selection.is_empty() && !line_mode {
 7431                    movement::right(map, selection.end)
 7432                } else {
 7433                    selection.end
 7434                };
 7435                selection.collapse_to(cursor, SelectionGoal::None)
 7436            });
 7437        })
 7438    }
 7439
 7440    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7441        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7442            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7443        })
 7444    }
 7445
 7446    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7447        if self.take_rename(true, cx).is_some() {
 7448            return;
 7449        }
 7450
 7451        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7452            cx.propagate();
 7453            return;
 7454        }
 7455
 7456        let text_layout_details = &self.text_layout_details(cx);
 7457        let selection_count = self.selections.count();
 7458        let first_selection = self.selections.first_anchor();
 7459
 7460        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7461            let line_mode = s.line_mode;
 7462            s.move_with(|map, selection| {
 7463                if !selection.is_empty() && !line_mode {
 7464                    selection.goal = SelectionGoal::None;
 7465                }
 7466                let (cursor, goal) = movement::up(
 7467                    map,
 7468                    selection.start,
 7469                    selection.goal,
 7470                    false,
 7471                    text_layout_details,
 7472                );
 7473                selection.collapse_to(cursor, goal);
 7474            });
 7475        });
 7476
 7477        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7478        {
 7479            cx.propagate();
 7480        }
 7481    }
 7482
 7483    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7484        if self.take_rename(true, cx).is_some() {
 7485            return;
 7486        }
 7487
 7488        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7489            cx.propagate();
 7490            return;
 7491        }
 7492
 7493        let text_layout_details = &self.text_layout_details(cx);
 7494
 7495        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7496            let line_mode = s.line_mode;
 7497            s.move_with(|map, selection| {
 7498                if !selection.is_empty() && !line_mode {
 7499                    selection.goal = SelectionGoal::None;
 7500                }
 7501                let (cursor, goal) = movement::up_by_rows(
 7502                    map,
 7503                    selection.start,
 7504                    action.lines,
 7505                    selection.goal,
 7506                    false,
 7507                    text_layout_details,
 7508                );
 7509                selection.collapse_to(cursor, goal);
 7510            });
 7511        })
 7512    }
 7513
 7514    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7515        if self.take_rename(true, cx).is_some() {
 7516            return;
 7517        }
 7518
 7519        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7520            cx.propagate();
 7521            return;
 7522        }
 7523
 7524        let text_layout_details = &self.text_layout_details(cx);
 7525
 7526        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7527            let line_mode = s.line_mode;
 7528            s.move_with(|map, selection| {
 7529                if !selection.is_empty() && !line_mode {
 7530                    selection.goal = SelectionGoal::None;
 7531                }
 7532                let (cursor, goal) = movement::down_by_rows(
 7533                    map,
 7534                    selection.start,
 7535                    action.lines,
 7536                    selection.goal,
 7537                    false,
 7538                    text_layout_details,
 7539                );
 7540                selection.collapse_to(cursor, goal);
 7541            });
 7542        })
 7543    }
 7544
 7545    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7546        let text_layout_details = &self.text_layout_details(cx);
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            s.move_heads_with(|map, head, goal| {
 7549                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7550            })
 7551        })
 7552    }
 7553
 7554    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7555        let text_layout_details = &self.text_layout_details(cx);
 7556        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7557            s.move_heads_with(|map, head, goal| {
 7558                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7559            })
 7560        })
 7561    }
 7562
 7563    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7564        let Some(row_count) = self.visible_row_count() else {
 7565            return;
 7566        };
 7567
 7568        let text_layout_details = &self.text_layout_details(cx);
 7569
 7570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7571            s.move_heads_with(|map, head, goal| {
 7572                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7573            })
 7574        })
 7575    }
 7576
 7577    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7578        if self.take_rename(true, cx).is_some() {
 7579            return;
 7580        }
 7581
 7582        if self
 7583            .context_menu
 7584            .write()
 7585            .as_mut()
 7586            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7587            .unwrap_or(false)
 7588        {
 7589            return;
 7590        }
 7591
 7592        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7593            cx.propagate();
 7594            return;
 7595        }
 7596
 7597        let Some(row_count) = self.visible_row_count() else {
 7598            return;
 7599        };
 7600
 7601        let autoscroll = if action.center_cursor {
 7602            Autoscroll::center()
 7603        } else {
 7604            Autoscroll::fit()
 7605        };
 7606
 7607        let text_layout_details = &self.text_layout_details(cx);
 7608
 7609        self.change_selections(Some(autoscroll), cx, |s| {
 7610            let line_mode = s.line_mode;
 7611            s.move_with(|map, selection| {
 7612                if !selection.is_empty() && !line_mode {
 7613                    selection.goal = SelectionGoal::None;
 7614                }
 7615                let (cursor, goal) = movement::up_by_rows(
 7616                    map,
 7617                    selection.end,
 7618                    row_count,
 7619                    selection.goal,
 7620                    false,
 7621                    text_layout_details,
 7622                );
 7623                selection.collapse_to(cursor, goal);
 7624            });
 7625        });
 7626    }
 7627
 7628    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7629        let text_layout_details = &self.text_layout_details(cx);
 7630        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7631            s.move_heads_with(|map, head, goal| {
 7632                movement::up(map, head, goal, false, text_layout_details)
 7633            })
 7634        })
 7635    }
 7636
 7637    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7638        self.take_rename(true, cx);
 7639
 7640        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7641            cx.propagate();
 7642            return;
 7643        }
 7644
 7645        let text_layout_details = &self.text_layout_details(cx);
 7646        let selection_count = self.selections.count();
 7647        let first_selection = self.selections.first_anchor();
 7648
 7649        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7650            let line_mode = s.line_mode;
 7651            s.move_with(|map, selection| {
 7652                if !selection.is_empty() && !line_mode {
 7653                    selection.goal = SelectionGoal::None;
 7654                }
 7655                let (cursor, goal) = movement::down(
 7656                    map,
 7657                    selection.end,
 7658                    selection.goal,
 7659                    false,
 7660                    text_layout_details,
 7661                );
 7662                selection.collapse_to(cursor, goal);
 7663            });
 7664        });
 7665
 7666        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7667        {
 7668            cx.propagate();
 7669        }
 7670    }
 7671
 7672    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7673        let Some(row_count) = self.visible_row_count() else {
 7674            return;
 7675        };
 7676
 7677        let text_layout_details = &self.text_layout_details(cx);
 7678
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            s.move_heads_with(|map, head, goal| {
 7681                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7682            })
 7683        })
 7684    }
 7685
 7686    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7687        if self.take_rename(true, cx).is_some() {
 7688            return;
 7689        }
 7690
 7691        if self
 7692            .context_menu
 7693            .write()
 7694            .as_mut()
 7695            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7696            .unwrap_or(false)
 7697        {
 7698            return;
 7699        }
 7700
 7701        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7702            cx.propagate();
 7703            return;
 7704        }
 7705
 7706        let Some(row_count) = self.visible_row_count() else {
 7707            return;
 7708        };
 7709
 7710        let autoscroll = if action.center_cursor {
 7711            Autoscroll::center()
 7712        } else {
 7713            Autoscroll::fit()
 7714        };
 7715
 7716        let text_layout_details = &self.text_layout_details(cx);
 7717        self.change_selections(Some(autoscroll), cx, |s| {
 7718            let line_mode = s.line_mode;
 7719            s.move_with(|map, selection| {
 7720                if !selection.is_empty() && !line_mode {
 7721                    selection.goal = SelectionGoal::None;
 7722                }
 7723                let (cursor, goal) = movement::down_by_rows(
 7724                    map,
 7725                    selection.end,
 7726                    row_count,
 7727                    selection.goal,
 7728                    false,
 7729                    text_layout_details,
 7730                );
 7731                selection.collapse_to(cursor, goal);
 7732            });
 7733        });
 7734    }
 7735
 7736    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7737        let text_layout_details = &self.text_layout_details(cx);
 7738        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7739            s.move_heads_with(|map, head, goal| {
 7740                movement::down(map, head, goal, false, text_layout_details)
 7741            })
 7742        });
 7743    }
 7744
 7745    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7746        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7747            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7748        }
 7749    }
 7750
 7751    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7752        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7753            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7754        }
 7755    }
 7756
 7757    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7758        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7759            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7760        }
 7761    }
 7762
 7763    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7764        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7765            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7766        }
 7767    }
 7768
 7769    pub fn move_to_previous_word_start(
 7770        &mut self,
 7771        _: &MoveToPreviousWordStart,
 7772        cx: &mut ViewContext<Self>,
 7773    ) {
 7774        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7775            s.move_cursors_with(|map, head, _| {
 7776                (
 7777                    movement::previous_word_start(map, head),
 7778                    SelectionGoal::None,
 7779                )
 7780            });
 7781        })
 7782    }
 7783
 7784    pub fn move_to_previous_subword_start(
 7785        &mut self,
 7786        _: &MoveToPreviousSubwordStart,
 7787        cx: &mut ViewContext<Self>,
 7788    ) {
 7789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7790            s.move_cursors_with(|map, head, _| {
 7791                (
 7792                    movement::previous_subword_start(map, head),
 7793                    SelectionGoal::None,
 7794                )
 7795            });
 7796        })
 7797    }
 7798
 7799    pub fn select_to_previous_word_start(
 7800        &mut self,
 7801        _: &SelectToPreviousWordStart,
 7802        cx: &mut ViewContext<Self>,
 7803    ) {
 7804        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7805            s.move_heads_with(|map, head, _| {
 7806                (
 7807                    movement::previous_word_start(map, head),
 7808                    SelectionGoal::None,
 7809                )
 7810            });
 7811        })
 7812    }
 7813
 7814    pub fn select_to_previous_subword_start(
 7815        &mut self,
 7816        _: &SelectToPreviousSubwordStart,
 7817        cx: &mut ViewContext<Self>,
 7818    ) {
 7819        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7820            s.move_heads_with(|map, head, _| {
 7821                (
 7822                    movement::previous_subword_start(map, head),
 7823                    SelectionGoal::None,
 7824                )
 7825            });
 7826        })
 7827    }
 7828
 7829    pub fn delete_to_previous_word_start(
 7830        &mut self,
 7831        action: &DeleteToPreviousWordStart,
 7832        cx: &mut ViewContext<Self>,
 7833    ) {
 7834        self.transact(cx, |this, cx| {
 7835            this.select_autoclose_pair(cx);
 7836            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7837                let line_mode = s.line_mode;
 7838                s.move_with(|map, selection| {
 7839                    if selection.is_empty() && !line_mode {
 7840                        let cursor = if action.ignore_newlines {
 7841                            movement::previous_word_start(map, selection.head())
 7842                        } else {
 7843                            movement::previous_word_start_or_newline(map, selection.head())
 7844                        };
 7845                        selection.set_head(cursor, SelectionGoal::None);
 7846                    }
 7847                });
 7848            });
 7849            this.insert("", cx);
 7850        });
 7851    }
 7852
 7853    pub fn delete_to_previous_subword_start(
 7854        &mut self,
 7855        _: &DeleteToPreviousSubwordStart,
 7856        cx: &mut ViewContext<Self>,
 7857    ) {
 7858        self.transact(cx, |this, cx| {
 7859            this.select_autoclose_pair(cx);
 7860            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7861                let line_mode = s.line_mode;
 7862                s.move_with(|map, selection| {
 7863                    if selection.is_empty() && !line_mode {
 7864                        let cursor = movement::previous_subword_start(map, selection.head());
 7865                        selection.set_head(cursor, SelectionGoal::None);
 7866                    }
 7867                });
 7868            });
 7869            this.insert("", cx);
 7870        });
 7871    }
 7872
 7873    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7874        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7875            s.move_cursors_with(|map, head, _| {
 7876                (movement::next_word_end(map, head), SelectionGoal::None)
 7877            });
 7878        })
 7879    }
 7880
 7881    pub fn move_to_next_subword_end(
 7882        &mut self,
 7883        _: &MoveToNextSubwordEnd,
 7884        cx: &mut ViewContext<Self>,
 7885    ) {
 7886        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7887            s.move_cursors_with(|map, head, _| {
 7888                (movement::next_subword_end(map, head), SelectionGoal::None)
 7889            });
 7890        })
 7891    }
 7892
 7893    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7894        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7895            s.move_heads_with(|map, head, _| {
 7896                (movement::next_word_end(map, head), SelectionGoal::None)
 7897            });
 7898        })
 7899    }
 7900
 7901    pub fn select_to_next_subword_end(
 7902        &mut self,
 7903        _: &SelectToNextSubwordEnd,
 7904        cx: &mut ViewContext<Self>,
 7905    ) {
 7906        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7907            s.move_heads_with(|map, head, _| {
 7908                (movement::next_subword_end(map, head), SelectionGoal::None)
 7909            });
 7910        })
 7911    }
 7912
 7913    pub fn delete_to_next_word_end(
 7914        &mut self,
 7915        action: &DeleteToNextWordEnd,
 7916        cx: &mut ViewContext<Self>,
 7917    ) {
 7918        self.transact(cx, |this, cx| {
 7919            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7920                let line_mode = s.line_mode;
 7921                s.move_with(|map, selection| {
 7922                    if selection.is_empty() && !line_mode {
 7923                        let cursor = if action.ignore_newlines {
 7924                            movement::next_word_end(map, selection.head())
 7925                        } else {
 7926                            movement::next_word_end_or_newline(map, selection.head())
 7927                        };
 7928                        selection.set_head(cursor, SelectionGoal::None);
 7929                    }
 7930                });
 7931            });
 7932            this.insert("", cx);
 7933        });
 7934    }
 7935
 7936    pub fn delete_to_next_subword_end(
 7937        &mut self,
 7938        _: &DeleteToNextSubwordEnd,
 7939        cx: &mut ViewContext<Self>,
 7940    ) {
 7941        self.transact(cx, |this, cx| {
 7942            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7943                s.move_with(|map, selection| {
 7944                    if selection.is_empty() {
 7945                        let cursor = movement::next_subword_end(map, selection.head());
 7946                        selection.set_head(cursor, SelectionGoal::None);
 7947                    }
 7948                });
 7949            });
 7950            this.insert("", cx);
 7951        });
 7952    }
 7953
 7954    pub fn move_to_beginning_of_line(
 7955        &mut self,
 7956        action: &MoveToBeginningOfLine,
 7957        cx: &mut ViewContext<Self>,
 7958    ) {
 7959        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7960            s.move_cursors_with(|map, head, _| {
 7961                (
 7962                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7963                    SelectionGoal::None,
 7964                )
 7965            });
 7966        })
 7967    }
 7968
 7969    pub fn select_to_beginning_of_line(
 7970        &mut self,
 7971        action: &SelectToBeginningOfLine,
 7972        cx: &mut ViewContext<Self>,
 7973    ) {
 7974        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7975            s.move_heads_with(|map, head, _| {
 7976                (
 7977                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7978                    SelectionGoal::None,
 7979                )
 7980            });
 7981        });
 7982    }
 7983
 7984    pub fn delete_to_beginning_of_line(
 7985        &mut self,
 7986        _: &DeleteToBeginningOfLine,
 7987        cx: &mut ViewContext<Self>,
 7988    ) {
 7989        self.transact(cx, |this, cx| {
 7990            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7991                s.move_with(|_, selection| {
 7992                    selection.reversed = true;
 7993                });
 7994            });
 7995
 7996            this.select_to_beginning_of_line(
 7997                &SelectToBeginningOfLine {
 7998                    stop_at_soft_wraps: false,
 7999                },
 8000                cx,
 8001            );
 8002            this.backspace(&Backspace, cx);
 8003        });
 8004    }
 8005
 8006    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8007        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8008            s.move_cursors_with(|map, head, _| {
 8009                (
 8010                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8011                    SelectionGoal::None,
 8012                )
 8013            });
 8014        })
 8015    }
 8016
 8017    pub fn select_to_end_of_line(
 8018        &mut self,
 8019        action: &SelectToEndOfLine,
 8020        cx: &mut ViewContext<Self>,
 8021    ) {
 8022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8023            s.move_heads_with(|map, head, _| {
 8024                (
 8025                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8026                    SelectionGoal::None,
 8027                )
 8028            });
 8029        })
 8030    }
 8031
 8032    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8033        self.transact(cx, |this, cx| {
 8034            this.select_to_end_of_line(
 8035                &SelectToEndOfLine {
 8036                    stop_at_soft_wraps: false,
 8037                },
 8038                cx,
 8039            );
 8040            this.delete(&Delete, cx);
 8041        });
 8042    }
 8043
 8044    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8045        self.transact(cx, |this, cx| {
 8046            this.select_to_end_of_line(
 8047                &SelectToEndOfLine {
 8048                    stop_at_soft_wraps: false,
 8049                },
 8050                cx,
 8051            );
 8052            this.cut(&Cut, cx);
 8053        });
 8054    }
 8055
 8056    pub fn move_to_start_of_paragraph(
 8057        &mut self,
 8058        _: &MoveToStartOfParagraph,
 8059        cx: &mut ViewContext<Self>,
 8060    ) {
 8061        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8062            cx.propagate();
 8063            return;
 8064        }
 8065
 8066        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8067            s.move_with(|map, selection| {
 8068                selection.collapse_to(
 8069                    movement::start_of_paragraph(map, selection.head(), 1),
 8070                    SelectionGoal::None,
 8071                )
 8072            });
 8073        })
 8074    }
 8075
 8076    pub fn move_to_end_of_paragraph(
 8077        &mut self,
 8078        _: &MoveToEndOfParagraph,
 8079        cx: &mut ViewContext<Self>,
 8080    ) {
 8081        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8082            cx.propagate();
 8083            return;
 8084        }
 8085
 8086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8087            s.move_with(|map, selection| {
 8088                selection.collapse_to(
 8089                    movement::end_of_paragraph(map, selection.head(), 1),
 8090                    SelectionGoal::None,
 8091                )
 8092            });
 8093        })
 8094    }
 8095
 8096    pub fn select_to_start_of_paragraph(
 8097        &mut self,
 8098        _: &SelectToStartOfParagraph,
 8099        cx: &mut ViewContext<Self>,
 8100    ) {
 8101        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8102            cx.propagate();
 8103            return;
 8104        }
 8105
 8106        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8107            s.move_heads_with(|map, head, _| {
 8108                (
 8109                    movement::start_of_paragraph(map, head, 1),
 8110                    SelectionGoal::None,
 8111                )
 8112            });
 8113        })
 8114    }
 8115
 8116    pub fn select_to_end_of_paragraph(
 8117        &mut self,
 8118        _: &SelectToEndOfParagraph,
 8119        cx: &mut ViewContext<Self>,
 8120    ) {
 8121        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8122            cx.propagate();
 8123            return;
 8124        }
 8125
 8126        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8127            s.move_heads_with(|map, head, _| {
 8128                (
 8129                    movement::end_of_paragraph(map, head, 1),
 8130                    SelectionGoal::None,
 8131                )
 8132            });
 8133        })
 8134    }
 8135
 8136    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8137        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8138            cx.propagate();
 8139            return;
 8140        }
 8141
 8142        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8143            s.select_ranges(vec![0..0]);
 8144        });
 8145    }
 8146
 8147    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8148        let mut selection = self.selections.last::<Point>(cx);
 8149        selection.set_head(Point::zero(), SelectionGoal::None);
 8150
 8151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8152            s.select(vec![selection]);
 8153        });
 8154    }
 8155
 8156    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8157        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8158            cx.propagate();
 8159            return;
 8160        }
 8161
 8162        let cursor = self.buffer.read(cx).read(cx).len();
 8163        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8164            s.select_ranges(vec![cursor..cursor])
 8165        });
 8166    }
 8167
 8168    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8169        self.nav_history = nav_history;
 8170    }
 8171
 8172    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8173        self.nav_history.as_ref()
 8174    }
 8175
 8176    fn push_to_nav_history(
 8177        &mut self,
 8178        cursor_anchor: Anchor,
 8179        new_position: Option<Point>,
 8180        cx: &mut ViewContext<Self>,
 8181    ) {
 8182        if let Some(nav_history) = self.nav_history.as_mut() {
 8183            let buffer = self.buffer.read(cx).read(cx);
 8184            let cursor_position = cursor_anchor.to_point(&buffer);
 8185            let scroll_state = self.scroll_manager.anchor();
 8186            let scroll_top_row = scroll_state.top_row(&buffer);
 8187            drop(buffer);
 8188
 8189            if let Some(new_position) = new_position {
 8190                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8191                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8192                    return;
 8193                }
 8194            }
 8195
 8196            nav_history.push(
 8197                Some(NavigationData {
 8198                    cursor_anchor,
 8199                    cursor_position,
 8200                    scroll_anchor: scroll_state,
 8201                    scroll_top_row,
 8202                }),
 8203                cx,
 8204            );
 8205        }
 8206    }
 8207
 8208    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8209        let buffer = self.buffer.read(cx).snapshot(cx);
 8210        let mut selection = self.selections.first::<usize>(cx);
 8211        selection.set_head(buffer.len(), SelectionGoal::None);
 8212        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8213            s.select(vec![selection]);
 8214        });
 8215    }
 8216
 8217    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8218        let end = self.buffer.read(cx).read(cx).len();
 8219        self.change_selections(None, cx, |s| {
 8220            s.select_ranges(vec![0..end]);
 8221        });
 8222    }
 8223
 8224    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8225        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8226        let mut selections = self.selections.all::<Point>(cx);
 8227        let max_point = display_map.buffer_snapshot.max_point();
 8228        for selection in &mut selections {
 8229            let rows = selection.spanned_rows(true, &display_map);
 8230            selection.start = Point::new(rows.start.0, 0);
 8231            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8232            selection.reversed = false;
 8233        }
 8234        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8235            s.select(selections);
 8236        });
 8237    }
 8238
 8239    pub fn split_selection_into_lines(
 8240        &mut self,
 8241        _: &SplitSelectionIntoLines,
 8242        cx: &mut ViewContext<Self>,
 8243    ) {
 8244        let mut to_unfold = Vec::new();
 8245        let mut new_selection_ranges = Vec::new();
 8246        {
 8247            let selections = self.selections.all::<Point>(cx);
 8248            let buffer = self.buffer.read(cx).read(cx);
 8249            for selection in selections {
 8250                for row in selection.start.row..selection.end.row {
 8251                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8252                    new_selection_ranges.push(cursor..cursor);
 8253                }
 8254                new_selection_ranges.push(selection.end..selection.end);
 8255                to_unfold.push(selection.start..selection.end);
 8256            }
 8257        }
 8258        self.unfold_ranges(to_unfold, true, true, cx);
 8259        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8260            s.select_ranges(new_selection_ranges);
 8261        });
 8262    }
 8263
 8264    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8265        self.add_selection(true, cx);
 8266    }
 8267
 8268    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8269        self.add_selection(false, cx);
 8270    }
 8271
 8272    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8273        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8274        let mut selections = self.selections.all::<Point>(cx);
 8275        let text_layout_details = self.text_layout_details(cx);
 8276        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8277            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8278            let range = oldest_selection.display_range(&display_map).sorted();
 8279
 8280            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8281            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8282            let positions = start_x.min(end_x)..start_x.max(end_x);
 8283
 8284            selections.clear();
 8285            let mut stack = Vec::new();
 8286            for row in range.start.row().0..=range.end.row().0 {
 8287                if let Some(selection) = self.selections.build_columnar_selection(
 8288                    &display_map,
 8289                    DisplayRow(row),
 8290                    &positions,
 8291                    oldest_selection.reversed,
 8292                    &text_layout_details,
 8293                ) {
 8294                    stack.push(selection.id);
 8295                    selections.push(selection);
 8296                }
 8297            }
 8298
 8299            if above {
 8300                stack.reverse();
 8301            }
 8302
 8303            AddSelectionsState { above, stack }
 8304        });
 8305
 8306        let last_added_selection = *state.stack.last().unwrap();
 8307        let mut new_selections = Vec::new();
 8308        if above == state.above {
 8309            let end_row = if above {
 8310                DisplayRow(0)
 8311            } else {
 8312                display_map.max_point().row()
 8313            };
 8314
 8315            'outer: for selection in selections {
 8316                if selection.id == last_added_selection {
 8317                    let range = selection.display_range(&display_map).sorted();
 8318                    debug_assert_eq!(range.start.row(), range.end.row());
 8319                    let mut row = range.start.row();
 8320                    let positions =
 8321                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8322                            px(start)..px(end)
 8323                        } else {
 8324                            let start_x =
 8325                                display_map.x_for_display_point(range.start, &text_layout_details);
 8326                            let end_x =
 8327                                display_map.x_for_display_point(range.end, &text_layout_details);
 8328                            start_x.min(end_x)..start_x.max(end_x)
 8329                        };
 8330
 8331                    while row != end_row {
 8332                        if above {
 8333                            row.0 -= 1;
 8334                        } else {
 8335                            row.0 += 1;
 8336                        }
 8337
 8338                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8339                            &display_map,
 8340                            row,
 8341                            &positions,
 8342                            selection.reversed,
 8343                            &text_layout_details,
 8344                        ) {
 8345                            state.stack.push(new_selection.id);
 8346                            if above {
 8347                                new_selections.push(new_selection);
 8348                                new_selections.push(selection);
 8349                            } else {
 8350                                new_selections.push(selection);
 8351                                new_selections.push(new_selection);
 8352                            }
 8353
 8354                            continue 'outer;
 8355                        }
 8356                    }
 8357                }
 8358
 8359                new_selections.push(selection);
 8360            }
 8361        } else {
 8362            new_selections = selections;
 8363            new_selections.retain(|s| s.id != last_added_selection);
 8364            state.stack.pop();
 8365        }
 8366
 8367        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8368            s.select(new_selections);
 8369        });
 8370        if state.stack.len() > 1 {
 8371            self.add_selections_state = Some(state);
 8372        }
 8373    }
 8374
 8375    pub fn select_next_match_internal(
 8376        &mut self,
 8377        display_map: &DisplaySnapshot,
 8378        replace_newest: bool,
 8379        autoscroll: Option<Autoscroll>,
 8380        cx: &mut ViewContext<Self>,
 8381    ) -> Result<()> {
 8382        fn select_next_match_ranges(
 8383            this: &mut Editor,
 8384            range: Range<usize>,
 8385            replace_newest: bool,
 8386            auto_scroll: Option<Autoscroll>,
 8387            cx: &mut ViewContext<Editor>,
 8388        ) {
 8389            this.unfold_ranges([range.clone()], false, true, cx);
 8390            this.change_selections(auto_scroll, cx, |s| {
 8391                if replace_newest {
 8392                    s.delete(s.newest_anchor().id);
 8393                }
 8394                s.insert_range(range.clone());
 8395            });
 8396        }
 8397
 8398        let buffer = &display_map.buffer_snapshot;
 8399        let mut selections = self.selections.all::<usize>(cx);
 8400        if let Some(mut select_next_state) = self.select_next_state.take() {
 8401            let query = &select_next_state.query;
 8402            if !select_next_state.done {
 8403                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8404                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8405                let mut next_selected_range = None;
 8406
 8407                let bytes_after_last_selection =
 8408                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8409                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8410                let query_matches = query
 8411                    .stream_find_iter(bytes_after_last_selection)
 8412                    .map(|result| (last_selection.end, result))
 8413                    .chain(
 8414                        query
 8415                            .stream_find_iter(bytes_before_first_selection)
 8416                            .map(|result| (0, result)),
 8417                    );
 8418
 8419                for (start_offset, query_match) in query_matches {
 8420                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8421                    let offset_range =
 8422                        start_offset + query_match.start()..start_offset + query_match.end();
 8423                    let display_range = offset_range.start.to_display_point(display_map)
 8424                        ..offset_range.end.to_display_point(display_map);
 8425
 8426                    if !select_next_state.wordwise
 8427                        || (!movement::is_inside_word(display_map, display_range.start)
 8428                            && !movement::is_inside_word(display_map, display_range.end))
 8429                    {
 8430                        // TODO: This is n^2, because we might check all the selections
 8431                        if !selections
 8432                            .iter()
 8433                            .any(|selection| selection.range().overlaps(&offset_range))
 8434                        {
 8435                            next_selected_range = Some(offset_range);
 8436                            break;
 8437                        }
 8438                    }
 8439                }
 8440
 8441                if let Some(next_selected_range) = next_selected_range {
 8442                    select_next_match_ranges(
 8443                        self,
 8444                        next_selected_range,
 8445                        replace_newest,
 8446                        autoscroll,
 8447                        cx,
 8448                    );
 8449                } else {
 8450                    select_next_state.done = true;
 8451                }
 8452            }
 8453
 8454            self.select_next_state = Some(select_next_state);
 8455        } else {
 8456            let mut only_carets = true;
 8457            let mut same_text_selected = true;
 8458            let mut selected_text = None;
 8459
 8460            let mut selections_iter = selections.iter().peekable();
 8461            while let Some(selection) = selections_iter.next() {
 8462                if selection.start != selection.end {
 8463                    only_carets = false;
 8464                }
 8465
 8466                if same_text_selected {
 8467                    if selected_text.is_none() {
 8468                        selected_text =
 8469                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8470                    }
 8471
 8472                    if let Some(next_selection) = selections_iter.peek() {
 8473                        if next_selection.range().len() == selection.range().len() {
 8474                            let next_selected_text = buffer
 8475                                .text_for_range(next_selection.range())
 8476                                .collect::<String>();
 8477                            if Some(next_selected_text) != selected_text {
 8478                                same_text_selected = false;
 8479                                selected_text = None;
 8480                            }
 8481                        } else {
 8482                            same_text_selected = false;
 8483                            selected_text = None;
 8484                        }
 8485                    }
 8486                }
 8487            }
 8488
 8489            if only_carets {
 8490                for selection in &mut selections {
 8491                    let word_range = movement::surrounding_word(
 8492                        display_map,
 8493                        selection.start.to_display_point(display_map),
 8494                    );
 8495                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8496                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8497                    selection.goal = SelectionGoal::None;
 8498                    selection.reversed = false;
 8499                    select_next_match_ranges(
 8500                        self,
 8501                        selection.start..selection.end,
 8502                        replace_newest,
 8503                        autoscroll,
 8504                        cx,
 8505                    );
 8506                }
 8507
 8508                if selections.len() == 1 {
 8509                    let selection = selections
 8510                        .last()
 8511                        .expect("ensured that there's only one selection");
 8512                    let query = buffer
 8513                        .text_for_range(selection.start..selection.end)
 8514                        .collect::<String>();
 8515                    let is_empty = query.is_empty();
 8516                    let select_state = SelectNextState {
 8517                        query: AhoCorasick::new(&[query])?,
 8518                        wordwise: true,
 8519                        done: is_empty,
 8520                    };
 8521                    self.select_next_state = Some(select_state);
 8522                } else {
 8523                    self.select_next_state = None;
 8524                }
 8525            } else if let Some(selected_text) = selected_text {
 8526                self.select_next_state = Some(SelectNextState {
 8527                    query: AhoCorasick::new(&[selected_text])?,
 8528                    wordwise: false,
 8529                    done: false,
 8530                });
 8531                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8532            }
 8533        }
 8534        Ok(())
 8535    }
 8536
 8537    pub fn select_all_matches(
 8538        &mut self,
 8539        _action: &SelectAllMatches,
 8540        cx: &mut ViewContext<Self>,
 8541    ) -> Result<()> {
 8542        self.push_to_selection_history();
 8543        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8544
 8545        self.select_next_match_internal(&display_map, false, None, cx)?;
 8546        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8547            return Ok(());
 8548        };
 8549        if select_next_state.done {
 8550            return Ok(());
 8551        }
 8552
 8553        let mut new_selections = self.selections.all::<usize>(cx);
 8554
 8555        let buffer = &display_map.buffer_snapshot;
 8556        let query_matches = select_next_state
 8557            .query
 8558            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8559
 8560        for query_match in query_matches {
 8561            let query_match = query_match.unwrap(); // can only fail due to I/O
 8562            let offset_range = query_match.start()..query_match.end();
 8563            let display_range = offset_range.start.to_display_point(&display_map)
 8564                ..offset_range.end.to_display_point(&display_map);
 8565
 8566            if !select_next_state.wordwise
 8567                || (!movement::is_inside_word(&display_map, display_range.start)
 8568                    && !movement::is_inside_word(&display_map, display_range.end))
 8569            {
 8570                self.selections.change_with(cx, |selections| {
 8571                    new_selections.push(Selection {
 8572                        id: selections.new_selection_id(),
 8573                        start: offset_range.start,
 8574                        end: offset_range.end,
 8575                        reversed: false,
 8576                        goal: SelectionGoal::None,
 8577                    });
 8578                });
 8579            }
 8580        }
 8581
 8582        new_selections.sort_by_key(|selection| selection.start);
 8583        let mut ix = 0;
 8584        while ix + 1 < new_selections.len() {
 8585            let current_selection = &new_selections[ix];
 8586            let next_selection = &new_selections[ix + 1];
 8587            if current_selection.range().overlaps(&next_selection.range()) {
 8588                if current_selection.id < next_selection.id {
 8589                    new_selections.remove(ix + 1);
 8590                } else {
 8591                    new_selections.remove(ix);
 8592                }
 8593            } else {
 8594                ix += 1;
 8595            }
 8596        }
 8597
 8598        select_next_state.done = true;
 8599        self.unfold_ranges(
 8600            new_selections.iter().map(|selection| selection.range()),
 8601            false,
 8602            false,
 8603            cx,
 8604        );
 8605        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8606            selections.select(new_selections)
 8607        });
 8608
 8609        Ok(())
 8610    }
 8611
 8612    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8613        self.push_to_selection_history();
 8614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8615        self.select_next_match_internal(
 8616            &display_map,
 8617            action.replace_newest,
 8618            Some(Autoscroll::newest()),
 8619            cx,
 8620        )?;
 8621        Ok(())
 8622    }
 8623
 8624    pub fn select_previous(
 8625        &mut self,
 8626        action: &SelectPrevious,
 8627        cx: &mut ViewContext<Self>,
 8628    ) -> Result<()> {
 8629        self.push_to_selection_history();
 8630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8631        let buffer = &display_map.buffer_snapshot;
 8632        let mut selections = self.selections.all::<usize>(cx);
 8633        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8634            let query = &select_prev_state.query;
 8635            if !select_prev_state.done {
 8636                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8637                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8638                let mut next_selected_range = None;
 8639                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8640                let bytes_before_last_selection =
 8641                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8642                let bytes_after_first_selection =
 8643                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8644                let query_matches = query
 8645                    .stream_find_iter(bytes_before_last_selection)
 8646                    .map(|result| (last_selection.start, result))
 8647                    .chain(
 8648                        query
 8649                            .stream_find_iter(bytes_after_first_selection)
 8650                            .map(|result| (buffer.len(), result)),
 8651                    );
 8652                for (end_offset, query_match) in query_matches {
 8653                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8654                    let offset_range =
 8655                        end_offset - query_match.end()..end_offset - query_match.start();
 8656                    let display_range = offset_range.start.to_display_point(&display_map)
 8657                        ..offset_range.end.to_display_point(&display_map);
 8658
 8659                    if !select_prev_state.wordwise
 8660                        || (!movement::is_inside_word(&display_map, display_range.start)
 8661                            && !movement::is_inside_word(&display_map, display_range.end))
 8662                    {
 8663                        next_selected_range = Some(offset_range);
 8664                        break;
 8665                    }
 8666                }
 8667
 8668                if let Some(next_selected_range) = next_selected_range {
 8669                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8670                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8671                        if action.replace_newest {
 8672                            s.delete(s.newest_anchor().id);
 8673                        }
 8674                        s.insert_range(next_selected_range);
 8675                    });
 8676                } else {
 8677                    select_prev_state.done = true;
 8678                }
 8679            }
 8680
 8681            self.select_prev_state = Some(select_prev_state);
 8682        } else {
 8683            let mut only_carets = true;
 8684            let mut same_text_selected = true;
 8685            let mut selected_text = None;
 8686
 8687            let mut selections_iter = selections.iter().peekable();
 8688            while let Some(selection) = selections_iter.next() {
 8689                if selection.start != selection.end {
 8690                    only_carets = false;
 8691                }
 8692
 8693                if same_text_selected {
 8694                    if selected_text.is_none() {
 8695                        selected_text =
 8696                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8697                    }
 8698
 8699                    if let Some(next_selection) = selections_iter.peek() {
 8700                        if next_selection.range().len() == selection.range().len() {
 8701                            let next_selected_text = buffer
 8702                                .text_for_range(next_selection.range())
 8703                                .collect::<String>();
 8704                            if Some(next_selected_text) != selected_text {
 8705                                same_text_selected = false;
 8706                                selected_text = None;
 8707                            }
 8708                        } else {
 8709                            same_text_selected = false;
 8710                            selected_text = None;
 8711                        }
 8712                    }
 8713                }
 8714            }
 8715
 8716            if only_carets {
 8717                for selection in &mut selections {
 8718                    let word_range = movement::surrounding_word(
 8719                        &display_map,
 8720                        selection.start.to_display_point(&display_map),
 8721                    );
 8722                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8723                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8724                    selection.goal = SelectionGoal::None;
 8725                    selection.reversed = false;
 8726                }
 8727                if selections.len() == 1 {
 8728                    let selection = selections
 8729                        .last()
 8730                        .expect("ensured that there's only one selection");
 8731                    let query = buffer
 8732                        .text_for_range(selection.start..selection.end)
 8733                        .collect::<String>();
 8734                    let is_empty = query.is_empty();
 8735                    let select_state = SelectNextState {
 8736                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8737                        wordwise: true,
 8738                        done: is_empty,
 8739                    };
 8740                    self.select_prev_state = Some(select_state);
 8741                } else {
 8742                    self.select_prev_state = None;
 8743                }
 8744
 8745                self.unfold_ranges(
 8746                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8747                    false,
 8748                    true,
 8749                    cx,
 8750                );
 8751                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8752                    s.select(selections);
 8753                });
 8754            } else if let Some(selected_text) = selected_text {
 8755                self.select_prev_state = Some(SelectNextState {
 8756                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8757                    wordwise: false,
 8758                    done: false,
 8759                });
 8760                self.select_previous(action, cx)?;
 8761            }
 8762        }
 8763        Ok(())
 8764    }
 8765
 8766    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8767        let text_layout_details = &self.text_layout_details(cx);
 8768        self.transact(cx, |this, cx| {
 8769            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8770            let mut edits = Vec::new();
 8771            let mut selection_edit_ranges = Vec::new();
 8772            let mut last_toggled_row = None;
 8773            let snapshot = this.buffer.read(cx).read(cx);
 8774            let empty_str: Arc<str> = Arc::default();
 8775            let mut suffixes_inserted = Vec::new();
 8776            let ignore_indent = action.ignore_indent;
 8777
 8778            fn comment_prefix_range(
 8779                snapshot: &MultiBufferSnapshot,
 8780                row: MultiBufferRow,
 8781                comment_prefix: &str,
 8782                comment_prefix_whitespace: &str,
 8783                ignore_indent: bool,
 8784            ) -> Range<Point> {
 8785                let indent_size = if ignore_indent {
 8786                    0
 8787                } else {
 8788                    snapshot.indent_size_for_line(row).len
 8789                };
 8790
 8791                let start = Point::new(row.0, indent_size);
 8792
 8793                let mut line_bytes = snapshot
 8794                    .bytes_in_range(start..snapshot.max_point())
 8795                    .flatten()
 8796                    .copied();
 8797
 8798                // If this line currently begins with the line comment prefix, then record
 8799                // the range containing the prefix.
 8800                if line_bytes
 8801                    .by_ref()
 8802                    .take(comment_prefix.len())
 8803                    .eq(comment_prefix.bytes())
 8804                {
 8805                    // Include any whitespace that matches the comment prefix.
 8806                    let matching_whitespace_len = line_bytes
 8807                        .zip(comment_prefix_whitespace.bytes())
 8808                        .take_while(|(a, b)| a == b)
 8809                        .count() as u32;
 8810                    let end = Point::new(
 8811                        start.row,
 8812                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8813                    );
 8814                    start..end
 8815                } else {
 8816                    start..start
 8817                }
 8818            }
 8819
 8820            fn comment_suffix_range(
 8821                snapshot: &MultiBufferSnapshot,
 8822                row: MultiBufferRow,
 8823                comment_suffix: &str,
 8824                comment_suffix_has_leading_space: bool,
 8825            ) -> Range<Point> {
 8826                let end = Point::new(row.0, snapshot.line_len(row));
 8827                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8828
 8829                let mut line_end_bytes = snapshot
 8830                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8831                    .flatten()
 8832                    .copied();
 8833
 8834                let leading_space_len = if suffix_start_column > 0
 8835                    && line_end_bytes.next() == Some(b' ')
 8836                    && comment_suffix_has_leading_space
 8837                {
 8838                    1
 8839                } else {
 8840                    0
 8841                };
 8842
 8843                // If this line currently begins with the line comment prefix, then record
 8844                // the range containing the prefix.
 8845                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8846                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8847                    start..end
 8848                } else {
 8849                    end..end
 8850                }
 8851            }
 8852
 8853            // TODO: Handle selections that cross excerpts
 8854            for selection in &mut selections {
 8855                let start_column = snapshot
 8856                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8857                    .len;
 8858                let language = if let Some(language) =
 8859                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8860                {
 8861                    language
 8862                } else {
 8863                    continue;
 8864                };
 8865
 8866                selection_edit_ranges.clear();
 8867
 8868                // If multiple selections contain a given row, avoid processing that
 8869                // row more than once.
 8870                let mut start_row = MultiBufferRow(selection.start.row);
 8871                if last_toggled_row == Some(start_row) {
 8872                    start_row = start_row.next_row();
 8873                }
 8874                let end_row =
 8875                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8876                        MultiBufferRow(selection.end.row - 1)
 8877                    } else {
 8878                        MultiBufferRow(selection.end.row)
 8879                    };
 8880                last_toggled_row = Some(end_row);
 8881
 8882                if start_row > end_row {
 8883                    continue;
 8884                }
 8885
 8886                // If the language has line comments, toggle those.
 8887                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8888
 8889                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8890                if ignore_indent {
 8891                    full_comment_prefixes = full_comment_prefixes
 8892                        .into_iter()
 8893                        .map(|s| Arc::from(s.trim_end()))
 8894                        .collect();
 8895                }
 8896
 8897                if !full_comment_prefixes.is_empty() {
 8898                    let first_prefix = full_comment_prefixes
 8899                        .first()
 8900                        .expect("prefixes is non-empty");
 8901                    let prefix_trimmed_lengths = full_comment_prefixes
 8902                        .iter()
 8903                        .map(|p| p.trim_end_matches(' ').len())
 8904                        .collect::<SmallVec<[usize; 4]>>();
 8905
 8906                    let mut all_selection_lines_are_comments = true;
 8907
 8908                    for row in start_row.0..=end_row.0 {
 8909                        let row = MultiBufferRow(row);
 8910                        if start_row < end_row && snapshot.is_line_blank(row) {
 8911                            continue;
 8912                        }
 8913
 8914                        let prefix_range = full_comment_prefixes
 8915                            .iter()
 8916                            .zip(prefix_trimmed_lengths.iter().copied())
 8917                            .map(|(prefix, trimmed_prefix_len)| {
 8918                                comment_prefix_range(
 8919                                    snapshot.deref(),
 8920                                    row,
 8921                                    &prefix[..trimmed_prefix_len],
 8922                                    &prefix[trimmed_prefix_len..],
 8923                                    ignore_indent,
 8924                                )
 8925                            })
 8926                            .max_by_key(|range| range.end.column - range.start.column)
 8927                            .expect("prefixes is non-empty");
 8928
 8929                        if prefix_range.is_empty() {
 8930                            all_selection_lines_are_comments = false;
 8931                        }
 8932
 8933                        selection_edit_ranges.push(prefix_range);
 8934                    }
 8935
 8936                    if all_selection_lines_are_comments {
 8937                        edits.extend(
 8938                            selection_edit_ranges
 8939                                .iter()
 8940                                .cloned()
 8941                                .map(|range| (range, empty_str.clone())),
 8942                        );
 8943                    } else {
 8944                        let min_column = selection_edit_ranges
 8945                            .iter()
 8946                            .map(|range| range.start.column)
 8947                            .min()
 8948                            .unwrap_or(0);
 8949                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8950                            let position = Point::new(range.start.row, min_column);
 8951                            (position..position, first_prefix.clone())
 8952                        }));
 8953                    }
 8954                } else if let Some((full_comment_prefix, comment_suffix)) =
 8955                    language.block_comment_delimiters()
 8956                {
 8957                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8958                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8959                    let prefix_range = comment_prefix_range(
 8960                        snapshot.deref(),
 8961                        start_row,
 8962                        comment_prefix,
 8963                        comment_prefix_whitespace,
 8964                        ignore_indent,
 8965                    );
 8966                    let suffix_range = comment_suffix_range(
 8967                        snapshot.deref(),
 8968                        end_row,
 8969                        comment_suffix.trim_start_matches(' '),
 8970                        comment_suffix.starts_with(' '),
 8971                    );
 8972
 8973                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8974                        edits.push((
 8975                            prefix_range.start..prefix_range.start,
 8976                            full_comment_prefix.clone(),
 8977                        ));
 8978                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8979                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8980                    } else {
 8981                        edits.push((prefix_range, empty_str.clone()));
 8982                        edits.push((suffix_range, empty_str.clone()));
 8983                    }
 8984                } else {
 8985                    continue;
 8986                }
 8987            }
 8988
 8989            drop(snapshot);
 8990            this.buffer.update(cx, |buffer, cx| {
 8991                buffer.edit(edits, None, cx);
 8992            });
 8993
 8994            // Adjust selections so that they end before any comment suffixes that
 8995            // were inserted.
 8996            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8997            let mut selections = this.selections.all::<Point>(cx);
 8998            let snapshot = this.buffer.read(cx).read(cx);
 8999            for selection in &mut selections {
 9000                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9001                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9002                        Ordering::Less => {
 9003                            suffixes_inserted.next();
 9004                            continue;
 9005                        }
 9006                        Ordering::Greater => break,
 9007                        Ordering::Equal => {
 9008                            if selection.end.column == snapshot.line_len(row) {
 9009                                if selection.is_empty() {
 9010                                    selection.start.column -= suffix_len as u32;
 9011                                }
 9012                                selection.end.column -= suffix_len as u32;
 9013                            }
 9014                            break;
 9015                        }
 9016                    }
 9017                }
 9018            }
 9019
 9020            drop(snapshot);
 9021            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9022
 9023            let selections = this.selections.all::<Point>(cx);
 9024            let selections_on_single_row = selections.windows(2).all(|selections| {
 9025                selections[0].start.row == selections[1].start.row
 9026                    && selections[0].end.row == selections[1].end.row
 9027                    && selections[0].start.row == selections[0].end.row
 9028            });
 9029            let selections_selecting = selections
 9030                .iter()
 9031                .any(|selection| selection.start != selection.end);
 9032            let advance_downwards = action.advance_downwards
 9033                && selections_on_single_row
 9034                && !selections_selecting
 9035                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9036
 9037            if advance_downwards {
 9038                let snapshot = this.buffer.read(cx).snapshot(cx);
 9039
 9040                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9041                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9042                        let mut point = display_point.to_point(display_snapshot);
 9043                        point.row += 1;
 9044                        point = snapshot.clip_point(point, Bias::Left);
 9045                        let display_point = point.to_display_point(display_snapshot);
 9046                        let goal = SelectionGoal::HorizontalPosition(
 9047                            display_snapshot
 9048                                .x_for_display_point(display_point, text_layout_details)
 9049                                .into(),
 9050                        );
 9051                        (display_point, goal)
 9052                    })
 9053                });
 9054            }
 9055        });
 9056    }
 9057
 9058    pub fn select_enclosing_symbol(
 9059        &mut self,
 9060        _: &SelectEnclosingSymbol,
 9061        cx: &mut ViewContext<Self>,
 9062    ) {
 9063        let buffer = self.buffer.read(cx).snapshot(cx);
 9064        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9065
 9066        fn update_selection(
 9067            selection: &Selection<usize>,
 9068            buffer_snap: &MultiBufferSnapshot,
 9069        ) -> Option<Selection<usize>> {
 9070            let cursor = selection.head();
 9071            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9072            for symbol in symbols.iter().rev() {
 9073                let start = symbol.range.start.to_offset(buffer_snap);
 9074                let end = symbol.range.end.to_offset(buffer_snap);
 9075                let new_range = start..end;
 9076                if start < selection.start || end > selection.end {
 9077                    return Some(Selection {
 9078                        id: selection.id,
 9079                        start: new_range.start,
 9080                        end: new_range.end,
 9081                        goal: SelectionGoal::None,
 9082                        reversed: selection.reversed,
 9083                    });
 9084                }
 9085            }
 9086            None
 9087        }
 9088
 9089        let mut selected_larger_symbol = false;
 9090        let new_selections = old_selections
 9091            .iter()
 9092            .map(|selection| match update_selection(selection, &buffer) {
 9093                Some(new_selection) => {
 9094                    if new_selection.range() != selection.range() {
 9095                        selected_larger_symbol = true;
 9096                    }
 9097                    new_selection
 9098                }
 9099                None => selection.clone(),
 9100            })
 9101            .collect::<Vec<_>>();
 9102
 9103        if selected_larger_symbol {
 9104            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9105                s.select(new_selections);
 9106            });
 9107        }
 9108    }
 9109
 9110    pub fn select_larger_syntax_node(
 9111        &mut self,
 9112        _: &SelectLargerSyntaxNode,
 9113        cx: &mut ViewContext<Self>,
 9114    ) {
 9115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9116        let buffer = self.buffer.read(cx).snapshot(cx);
 9117        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9118
 9119        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9120        let mut selected_larger_node = false;
 9121        let new_selections = old_selections
 9122            .iter()
 9123            .map(|selection| {
 9124                let old_range = selection.start..selection.end;
 9125                let mut new_range = old_range.clone();
 9126                while let Some(containing_range) =
 9127                    buffer.range_for_syntax_ancestor(new_range.clone())
 9128                {
 9129                    new_range = containing_range;
 9130                    if !display_map.intersects_fold(new_range.start)
 9131                        && !display_map.intersects_fold(new_range.end)
 9132                    {
 9133                        break;
 9134                    }
 9135                }
 9136
 9137                selected_larger_node |= new_range != old_range;
 9138                Selection {
 9139                    id: selection.id,
 9140                    start: new_range.start,
 9141                    end: new_range.end,
 9142                    goal: SelectionGoal::None,
 9143                    reversed: selection.reversed,
 9144                }
 9145            })
 9146            .collect::<Vec<_>>();
 9147
 9148        if selected_larger_node {
 9149            stack.push(old_selections);
 9150            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9151                s.select(new_selections);
 9152            });
 9153        }
 9154        self.select_larger_syntax_node_stack = stack;
 9155    }
 9156
 9157    pub fn select_smaller_syntax_node(
 9158        &mut self,
 9159        _: &SelectSmallerSyntaxNode,
 9160        cx: &mut ViewContext<Self>,
 9161    ) {
 9162        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9163        if let Some(selections) = stack.pop() {
 9164            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9165                s.select(selections.to_vec());
 9166            });
 9167        }
 9168        self.select_larger_syntax_node_stack = stack;
 9169    }
 9170
 9171    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9172        if !EditorSettings::get_global(cx).gutter.runnables {
 9173            self.clear_tasks();
 9174            return Task::ready(());
 9175        }
 9176        let project = self.project.clone();
 9177        cx.spawn(|this, mut cx| async move {
 9178            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9179                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9180            }) else {
 9181                return;
 9182            };
 9183
 9184            let Some(project) = project else {
 9185                return;
 9186            };
 9187
 9188            let hide_runnables = project
 9189                .update(&mut cx, |project, cx| {
 9190                    // Do not display any test indicators in non-dev server remote projects.
 9191                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9192                })
 9193                .unwrap_or(true);
 9194            if hide_runnables {
 9195                return;
 9196            }
 9197            let new_rows =
 9198                cx.background_executor()
 9199                    .spawn({
 9200                        let snapshot = display_snapshot.clone();
 9201                        async move {
 9202                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9203                        }
 9204                    })
 9205                    .await;
 9206            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9207
 9208            this.update(&mut cx, |this, _| {
 9209                this.clear_tasks();
 9210                for (key, value) in rows {
 9211                    this.insert_tasks(key, value);
 9212                }
 9213            })
 9214            .ok();
 9215        })
 9216    }
 9217    fn fetch_runnable_ranges(
 9218        snapshot: &DisplaySnapshot,
 9219        range: Range<Anchor>,
 9220    ) -> Vec<language::RunnableRange> {
 9221        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9222    }
 9223
 9224    fn runnable_rows(
 9225        project: Model<Project>,
 9226        snapshot: DisplaySnapshot,
 9227        runnable_ranges: Vec<RunnableRange>,
 9228        mut cx: AsyncWindowContext,
 9229    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9230        runnable_ranges
 9231            .into_iter()
 9232            .filter_map(|mut runnable| {
 9233                let tasks = cx
 9234                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9235                    .ok()?;
 9236                if tasks.is_empty() {
 9237                    return None;
 9238                }
 9239
 9240                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9241
 9242                let row = snapshot
 9243                    .buffer_snapshot
 9244                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9245                    .1
 9246                    .start
 9247                    .row;
 9248
 9249                let context_range =
 9250                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9251                Some((
 9252                    (runnable.buffer_id, row),
 9253                    RunnableTasks {
 9254                        templates: tasks,
 9255                        offset: MultiBufferOffset(runnable.run_range.start),
 9256                        context_range,
 9257                        column: point.column,
 9258                        extra_variables: runnable.extra_captures,
 9259                    },
 9260                ))
 9261            })
 9262            .collect()
 9263    }
 9264
 9265    fn templates_with_tags(
 9266        project: &Model<Project>,
 9267        runnable: &mut Runnable,
 9268        cx: &WindowContext<'_>,
 9269    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9270        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9271            let (worktree_id, file) = project
 9272                .buffer_for_id(runnable.buffer, cx)
 9273                .and_then(|buffer| buffer.read(cx).file())
 9274                .map(|file| (file.worktree_id(cx), file.clone()))
 9275                .unzip();
 9276
 9277            (
 9278                project.task_store().read(cx).task_inventory().cloned(),
 9279                worktree_id,
 9280                file,
 9281            )
 9282        });
 9283
 9284        let tags = mem::take(&mut runnable.tags);
 9285        let mut tags: Vec<_> = tags
 9286            .into_iter()
 9287            .flat_map(|tag| {
 9288                let tag = tag.0.clone();
 9289                inventory
 9290                    .as_ref()
 9291                    .into_iter()
 9292                    .flat_map(|inventory| {
 9293                        inventory.read(cx).list_tasks(
 9294                            file.clone(),
 9295                            Some(runnable.language.clone()),
 9296                            worktree_id,
 9297                            cx,
 9298                        )
 9299                    })
 9300                    .filter(move |(_, template)| {
 9301                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9302                    })
 9303            })
 9304            .sorted_by_key(|(kind, _)| kind.to_owned())
 9305            .collect();
 9306        if let Some((leading_tag_source, _)) = tags.first() {
 9307            // Strongest source wins; if we have worktree tag binding, prefer that to
 9308            // global and language bindings;
 9309            // if we have a global binding, prefer that to language binding.
 9310            let first_mismatch = tags
 9311                .iter()
 9312                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9313            if let Some(index) = first_mismatch {
 9314                tags.truncate(index);
 9315            }
 9316        }
 9317
 9318        tags
 9319    }
 9320
 9321    pub fn move_to_enclosing_bracket(
 9322        &mut self,
 9323        _: &MoveToEnclosingBracket,
 9324        cx: &mut ViewContext<Self>,
 9325    ) {
 9326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9327            s.move_offsets_with(|snapshot, selection| {
 9328                let Some(enclosing_bracket_ranges) =
 9329                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9330                else {
 9331                    return;
 9332                };
 9333
 9334                let mut best_length = usize::MAX;
 9335                let mut best_inside = false;
 9336                let mut best_in_bracket_range = false;
 9337                let mut best_destination = None;
 9338                for (open, close) in enclosing_bracket_ranges {
 9339                    let close = close.to_inclusive();
 9340                    let length = close.end() - open.start;
 9341                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9342                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9343                        || close.contains(&selection.head());
 9344
 9345                    // If best is next to a bracket and current isn't, skip
 9346                    if !in_bracket_range && best_in_bracket_range {
 9347                        continue;
 9348                    }
 9349
 9350                    // Prefer smaller lengths unless best is inside and current isn't
 9351                    if length > best_length && (best_inside || !inside) {
 9352                        continue;
 9353                    }
 9354
 9355                    best_length = length;
 9356                    best_inside = inside;
 9357                    best_in_bracket_range = in_bracket_range;
 9358                    best_destination = Some(
 9359                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9360                            if inside {
 9361                                open.end
 9362                            } else {
 9363                                open.start
 9364                            }
 9365                        } else if inside {
 9366                            *close.start()
 9367                        } else {
 9368                            *close.end()
 9369                        },
 9370                    );
 9371                }
 9372
 9373                if let Some(destination) = best_destination {
 9374                    selection.collapse_to(destination, SelectionGoal::None);
 9375                }
 9376            })
 9377        });
 9378    }
 9379
 9380    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9381        self.end_selection(cx);
 9382        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9383        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9384            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9385            self.select_next_state = entry.select_next_state;
 9386            self.select_prev_state = entry.select_prev_state;
 9387            self.add_selections_state = entry.add_selections_state;
 9388            self.request_autoscroll(Autoscroll::newest(), cx);
 9389        }
 9390        self.selection_history.mode = SelectionHistoryMode::Normal;
 9391    }
 9392
 9393    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9394        self.end_selection(cx);
 9395        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9396        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9397            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9398            self.select_next_state = entry.select_next_state;
 9399            self.select_prev_state = entry.select_prev_state;
 9400            self.add_selections_state = entry.add_selections_state;
 9401            self.request_autoscroll(Autoscroll::newest(), cx);
 9402        }
 9403        self.selection_history.mode = SelectionHistoryMode::Normal;
 9404    }
 9405
 9406    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9407        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9408    }
 9409
 9410    pub fn expand_excerpts_down(
 9411        &mut self,
 9412        action: &ExpandExcerptsDown,
 9413        cx: &mut ViewContext<Self>,
 9414    ) {
 9415        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9416    }
 9417
 9418    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9419        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9420    }
 9421
 9422    pub fn expand_excerpts_for_direction(
 9423        &mut self,
 9424        lines: u32,
 9425        direction: ExpandExcerptDirection,
 9426        cx: &mut ViewContext<Self>,
 9427    ) {
 9428        let selections = self.selections.disjoint_anchors();
 9429
 9430        let lines = if lines == 0 {
 9431            EditorSettings::get_global(cx).expand_excerpt_lines
 9432        } else {
 9433            lines
 9434        };
 9435
 9436        self.buffer.update(cx, |buffer, cx| {
 9437            buffer.expand_excerpts(
 9438                selections
 9439                    .iter()
 9440                    .map(|selection| selection.head().excerpt_id)
 9441                    .dedup(),
 9442                lines,
 9443                direction,
 9444                cx,
 9445            )
 9446        })
 9447    }
 9448
 9449    pub fn expand_excerpt(
 9450        &mut self,
 9451        excerpt: ExcerptId,
 9452        direction: ExpandExcerptDirection,
 9453        cx: &mut ViewContext<Self>,
 9454    ) {
 9455        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9456        self.buffer.update(cx, |buffer, cx| {
 9457            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9458        })
 9459    }
 9460
 9461    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9462        self.go_to_diagnostic_impl(Direction::Next, cx)
 9463    }
 9464
 9465    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9466        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9467    }
 9468
 9469    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9470        let buffer = self.buffer.read(cx).snapshot(cx);
 9471        let selection = self.selections.newest::<usize>(cx);
 9472
 9473        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9474        if direction == Direction::Next {
 9475            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9476                let (group_id, jump_to) = popover.activation_info();
 9477                if self.activate_diagnostics(group_id, cx) {
 9478                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9479                        let mut new_selection = s.newest_anchor().clone();
 9480                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9481                        s.select_anchors(vec![new_selection.clone()]);
 9482                    });
 9483                }
 9484                return;
 9485            }
 9486        }
 9487
 9488        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9489            active_diagnostics
 9490                .primary_range
 9491                .to_offset(&buffer)
 9492                .to_inclusive()
 9493        });
 9494        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9495            if active_primary_range.contains(&selection.head()) {
 9496                *active_primary_range.start()
 9497            } else {
 9498                selection.head()
 9499            }
 9500        } else {
 9501            selection.head()
 9502        };
 9503        let snapshot = self.snapshot(cx);
 9504        loop {
 9505            let diagnostics = if direction == Direction::Prev {
 9506                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9507            } else {
 9508                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9509            }
 9510            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9511            let group = diagnostics
 9512                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9513                // be sorted in a stable way
 9514                // skip until we are at current active diagnostic, if it exists
 9515                .skip_while(|entry| {
 9516                    (match direction {
 9517                        Direction::Prev => entry.range.start >= search_start,
 9518                        Direction::Next => entry.range.start <= search_start,
 9519                    }) && self
 9520                        .active_diagnostics
 9521                        .as_ref()
 9522                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9523                })
 9524                .find_map(|entry| {
 9525                    if entry.diagnostic.is_primary
 9526                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9527                        && !entry.range.is_empty()
 9528                        // if we match with the active diagnostic, skip it
 9529                        && Some(entry.diagnostic.group_id)
 9530                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9531                    {
 9532                        Some((entry.range, entry.diagnostic.group_id))
 9533                    } else {
 9534                        None
 9535                    }
 9536                });
 9537
 9538            if let Some((primary_range, group_id)) = group {
 9539                if self.activate_diagnostics(group_id, cx) {
 9540                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9541                        s.select(vec![Selection {
 9542                            id: selection.id,
 9543                            start: primary_range.start,
 9544                            end: primary_range.start,
 9545                            reversed: false,
 9546                            goal: SelectionGoal::None,
 9547                        }]);
 9548                    });
 9549                }
 9550                break;
 9551            } else {
 9552                // Cycle around to the start of the buffer, potentially moving back to the start of
 9553                // the currently active diagnostic.
 9554                active_primary_range.take();
 9555                if direction == Direction::Prev {
 9556                    if search_start == buffer.len() {
 9557                        break;
 9558                    } else {
 9559                        search_start = buffer.len();
 9560                    }
 9561                } else if search_start == 0 {
 9562                    break;
 9563                } else {
 9564                    search_start = 0;
 9565                }
 9566            }
 9567        }
 9568    }
 9569
 9570    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9571        let snapshot = self
 9572            .display_map
 9573            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9574        let selection = self.selections.newest::<Point>(cx);
 9575        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9576    }
 9577
 9578    fn go_to_hunk_after_position(
 9579        &mut self,
 9580        snapshot: &DisplaySnapshot,
 9581        position: Point,
 9582        cx: &mut ViewContext<'_, Editor>,
 9583    ) -> Option<MultiBufferDiffHunk> {
 9584        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9585            snapshot,
 9586            position,
 9587            false,
 9588            snapshot
 9589                .buffer_snapshot
 9590                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9591            cx,
 9592        ) {
 9593            return Some(hunk);
 9594        }
 9595
 9596        let wrapped_point = Point::zero();
 9597        self.go_to_next_hunk_in_direction(
 9598            snapshot,
 9599            wrapped_point,
 9600            true,
 9601            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9602                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9603            ),
 9604            cx,
 9605        )
 9606    }
 9607
 9608    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9609        let snapshot = self
 9610            .display_map
 9611            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9612        let selection = self.selections.newest::<Point>(cx);
 9613
 9614        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9615    }
 9616
 9617    fn go_to_hunk_before_position(
 9618        &mut self,
 9619        snapshot: &DisplaySnapshot,
 9620        position: Point,
 9621        cx: &mut ViewContext<'_, Editor>,
 9622    ) -> Option<MultiBufferDiffHunk> {
 9623        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9624            snapshot,
 9625            position,
 9626            false,
 9627            snapshot
 9628                .buffer_snapshot
 9629                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9630            cx,
 9631        ) {
 9632            return Some(hunk);
 9633        }
 9634
 9635        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9636        self.go_to_next_hunk_in_direction(
 9637            snapshot,
 9638            wrapped_point,
 9639            true,
 9640            snapshot
 9641                .buffer_snapshot
 9642                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9643            cx,
 9644        )
 9645    }
 9646
 9647    fn go_to_next_hunk_in_direction(
 9648        &mut self,
 9649        snapshot: &DisplaySnapshot,
 9650        initial_point: Point,
 9651        is_wrapped: bool,
 9652        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9653        cx: &mut ViewContext<Editor>,
 9654    ) -> Option<MultiBufferDiffHunk> {
 9655        let display_point = initial_point.to_display_point(snapshot);
 9656        let mut hunks = hunks
 9657            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9658            .filter(|(display_hunk, _)| {
 9659                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9660            })
 9661            .dedup();
 9662
 9663        if let Some((display_hunk, hunk)) = hunks.next() {
 9664            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9665                let row = display_hunk.start_display_row();
 9666                let point = DisplayPoint::new(row, 0);
 9667                s.select_display_ranges([point..point]);
 9668            });
 9669
 9670            Some(hunk)
 9671        } else {
 9672            None
 9673        }
 9674    }
 9675
 9676    pub fn go_to_definition(
 9677        &mut self,
 9678        _: &GoToDefinition,
 9679        cx: &mut ViewContext<Self>,
 9680    ) -> Task<Result<Navigated>> {
 9681        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9682        cx.spawn(|editor, mut cx| async move {
 9683            if definition.await? == Navigated::Yes {
 9684                return Ok(Navigated::Yes);
 9685            }
 9686            match editor.update(&mut cx, |editor, cx| {
 9687                editor.find_all_references(&FindAllReferences, cx)
 9688            })? {
 9689                Some(references) => references.await,
 9690                None => Ok(Navigated::No),
 9691            }
 9692        })
 9693    }
 9694
 9695    pub fn go_to_declaration(
 9696        &mut self,
 9697        _: &GoToDeclaration,
 9698        cx: &mut ViewContext<Self>,
 9699    ) -> Task<Result<Navigated>> {
 9700        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9701    }
 9702
 9703    pub fn go_to_declaration_split(
 9704        &mut self,
 9705        _: &GoToDeclaration,
 9706        cx: &mut ViewContext<Self>,
 9707    ) -> Task<Result<Navigated>> {
 9708        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9709    }
 9710
 9711    pub fn go_to_implementation(
 9712        &mut self,
 9713        _: &GoToImplementation,
 9714        cx: &mut ViewContext<Self>,
 9715    ) -> Task<Result<Navigated>> {
 9716        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9717    }
 9718
 9719    pub fn go_to_implementation_split(
 9720        &mut self,
 9721        _: &GoToImplementationSplit,
 9722        cx: &mut ViewContext<Self>,
 9723    ) -> Task<Result<Navigated>> {
 9724        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9725    }
 9726
 9727    pub fn go_to_type_definition(
 9728        &mut self,
 9729        _: &GoToTypeDefinition,
 9730        cx: &mut ViewContext<Self>,
 9731    ) -> Task<Result<Navigated>> {
 9732        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9733    }
 9734
 9735    pub fn go_to_definition_split(
 9736        &mut self,
 9737        _: &GoToDefinitionSplit,
 9738        cx: &mut ViewContext<Self>,
 9739    ) -> Task<Result<Navigated>> {
 9740        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9741    }
 9742
 9743    pub fn go_to_type_definition_split(
 9744        &mut self,
 9745        _: &GoToTypeDefinitionSplit,
 9746        cx: &mut ViewContext<Self>,
 9747    ) -> Task<Result<Navigated>> {
 9748        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9749    }
 9750
 9751    fn go_to_definition_of_kind(
 9752        &mut self,
 9753        kind: GotoDefinitionKind,
 9754        split: bool,
 9755        cx: &mut ViewContext<Self>,
 9756    ) -> Task<Result<Navigated>> {
 9757        let Some(provider) = self.semantics_provider.clone() else {
 9758            return Task::ready(Ok(Navigated::No));
 9759        };
 9760        let head = self.selections.newest::<usize>(cx).head();
 9761        let buffer = self.buffer.read(cx);
 9762        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9763            text_anchor
 9764        } else {
 9765            return Task::ready(Ok(Navigated::No));
 9766        };
 9767
 9768        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9769            return Task::ready(Ok(Navigated::No));
 9770        };
 9771
 9772        cx.spawn(|editor, mut cx| async move {
 9773            let definitions = definitions.await?;
 9774            let navigated = editor
 9775                .update(&mut cx, |editor, cx| {
 9776                    editor.navigate_to_hover_links(
 9777                        Some(kind),
 9778                        definitions
 9779                            .into_iter()
 9780                            .filter(|location| {
 9781                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9782                            })
 9783                            .map(HoverLink::Text)
 9784                            .collect::<Vec<_>>(),
 9785                        split,
 9786                        cx,
 9787                    )
 9788                })?
 9789                .await?;
 9790            anyhow::Ok(navigated)
 9791        })
 9792    }
 9793
 9794    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9795        let position = self.selections.newest_anchor().head();
 9796        let Some((buffer, buffer_position)) =
 9797            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9798        else {
 9799            return;
 9800        };
 9801
 9802        cx.spawn(|editor, mut cx| async move {
 9803            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9804                editor.update(&mut cx, |_, cx| {
 9805                    cx.open_url(&url);
 9806                })
 9807            } else {
 9808                Ok(())
 9809            }
 9810        })
 9811        .detach();
 9812    }
 9813
 9814    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9815        let Some(workspace) = self.workspace() else {
 9816            return;
 9817        };
 9818
 9819        let position = self.selections.newest_anchor().head();
 9820
 9821        let Some((buffer, buffer_position)) =
 9822            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9823        else {
 9824            return;
 9825        };
 9826
 9827        let project = self.project.clone();
 9828
 9829        cx.spawn(|_, mut cx| async move {
 9830            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9831
 9832            if let Some((_, path)) = result {
 9833                workspace
 9834                    .update(&mut cx, |workspace, cx| {
 9835                        workspace.open_resolved_path(path, cx)
 9836                    })?
 9837                    .await?;
 9838            }
 9839            anyhow::Ok(())
 9840        })
 9841        .detach();
 9842    }
 9843
 9844    pub(crate) fn navigate_to_hover_links(
 9845        &mut self,
 9846        kind: Option<GotoDefinitionKind>,
 9847        mut definitions: Vec<HoverLink>,
 9848        split: bool,
 9849        cx: &mut ViewContext<Editor>,
 9850    ) -> Task<Result<Navigated>> {
 9851        // If there is one definition, just open it directly
 9852        if definitions.len() == 1 {
 9853            let definition = definitions.pop().unwrap();
 9854
 9855            enum TargetTaskResult {
 9856                Location(Option<Location>),
 9857                AlreadyNavigated,
 9858            }
 9859
 9860            let target_task = match definition {
 9861                HoverLink::Text(link) => {
 9862                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9863                }
 9864                HoverLink::InlayHint(lsp_location, server_id) => {
 9865                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9866                    cx.background_executor().spawn(async move {
 9867                        let location = computation.await?;
 9868                        Ok(TargetTaskResult::Location(location))
 9869                    })
 9870                }
 9871                HoverLink::Url(url) => {
 9872                    cx.open_url(&url);
 9873                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9874                }
 9875                HoverLink::File(path) => {
 9876                    if let Some(workspace) = self.workspace() {
 9877                        cx.spawn(|_, mut cx| async move {
 9878                            workspace
 9879                                .update(&mut cx, |workspace, cx| {
 9880                                    workspace.open_resolved_path(path, cx)
 9881                                })?
 9882                                .await
 9883                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9884                        })
 9885                    } else {
 9886                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9887                    }
 9888                }
 9889            };
 9890            cx.spawn(|editor, mut cx| async move {
 9891                let target = match target_task.await.context("target resolution task")? {
 9892                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9893                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9894                    TargetTaskResult::Location(Some(target)) => target,
 9895                };
 9896
 9897                editor.update(&mut cx, |editor, cx| {
 9898                    let Some(workspace) = editor.workspace() else {
 9899                        return Navigated::No;
 9900                    };
 9901                    let pane = workspace.read(cx).active_pane().clone();
 9902
 9903                    let range = target.range.to_offset(target.buffer.read(cx));
 9904                    let range = editor.range_for_match(&range);
 9905
 9906                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9907                        let buffer = target.buffer.read(cx);
 9908                        let range = check_multiline_range(buffer, range);
 9909                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9910                            s.select_ranges([range]);
 9911                        });
 9912                    } else {
 9913                        cx.window_context().defer(move |cx| {
 9914                            let target_editor: View<Self> =
 9915                                workspace.update(cx, |workspace, cx| {
 9916                                    let pane = if split {
 9917                                        workspace.adjacent_pane(cx)
 9918                                    } else {
 9919                                        workspace.active_pane().clone()
 9920                                    };
 9921
 9922                                    workspace.open_project_item(
 9923                                        pane,
 9924                                        target.buffer.clone(),
 9925                                        true,
 9926                                        true,
 9927                                        cx,
 9928                                    )
 9929                                });
 9930                            target_editor.update(cx, |target_editor, cx| {
 9931                                // When selecting a definition in a different buffer, disable the nav history
 9932                                // to avoid creating a history entry at the previous cursor location.
 9933                                pane.update(cx, |pane, _| pane.disable_history());
 9934                                let buffer = target.buffer.read(cx);
 9935                                let range = check_multiline_range(buffer, range);
 9936                                target_editor.change_selections(
 9937                                    Some(Autoscroll::focused()),
 9938                                    cx,
 9939                                    |s| {
 9940                                        s.select_ranges([range]);
 9941                                    },
 9942                                );
 9943                                pane.update(cx, |pane, _| pane.enable_history());
 9944                            });
 9945                        });
 9946                    }
 9947                    Navigated::Yes
 9948                })
 9949            })
 9950        } else if !definitions.is_empty() {
 9951            cx.spawn(|editor, mut cx| async move {
 9952                let (title, location_tasks, workspace) = editor
 9953                    .update(&mut cx, |editor, cx| {
 9954                        let tab_kind = match kind {
 9955                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9956                            _ => "Definitions",
 9957                        };
 9958                        let title = definitions
 9959                            .iter()
 9960                            .find_map(|definition| match definition {
 9961                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9962                                    let buffer = origin.buffer.read(cx);
 9963                                    format!(
 9964                                        "{} for {}",
 9965                                        tab_kind,
 9966                                        buffer
 9967                                            .text_for_range(origin.range.clone())
 9968                                            .collect::<String>()
 9969                                    )
 9970                                }),
 9971                                HoverLink::InlayHint(_, _) => None,
 9972                                HoverLink::Url(_) => None,
 9973                                HoverLink::File(_) => None,
 9974                            })
 9975                            .unwrap_or(tab_kind.to_string());
 9976                        let location_tasks = definitions
 9977                            .into_iter()
 9978                            .map(|definition| match definition {
 9979                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9980                                HoverLink::InlayHint(lsp_location, server_id) => {
 9981                                    editor.compute_target_location(lsp_location, server_id, cx)
 9982                                }
 9983                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9984                                HoverLink::File(_) => Task::ready(Ok(None)),
 9985                            })
 9986                            .collect::<Vec<_>>();
 9987                        (title, location_tasks, editor.workspace().clone())
 9988                    })
 9989                    .context("location tasks preparation")?;
 9990
 9991                let locations = future::join_all(location_tasks)
 9992                    .await
 9993                    .into_iter()
 9994                    .filter_map(|location| location.transpose())
 9995                    .collect::<Result<_>>()
 9996                    .context("location tasks")?;
 9997
 9998                let Some(workspace) = workspace else {
 9999                    return Ok(Navigated::No);
10000                };
10001                let opened = workspace
10002                    .update(&mut cx, |workspace, cx| {
10003                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10004                    })
10005                    .ok();
10006
10007                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10008            })
10009        } else {
10010            Task::ready(Ok(Navigated::No))
10011        }
10012    }
10013
10014    fn compute_target_location(
10015        &self,
10016        lsp_location: lsp::Location,
10017        server_id: LanguageServerId,
10018        cx: &mut ViewContext<Self>,
10019    ) -> Task<anyhow::Result<Option<Location>>> {
10020        let Some(project) = self.project.clone() else {
10021            return Task::Ready(Some(Ok(None)));
10022        };
10023
10024        cx.spawn(move |editor, mut cx| async move {
10025            let location_task = editor.update(&mut cx, |_, cx| {
10026                project.update(cx, |project, cx| {
10027                    let language_server_name = project
10028                        .language_server_statuses(cx)
10029                        .find(|(id, _)| server_id == *id)
10030                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10031                    language_server_name.map(|language_server_name| {
10032                        project.open_local_buffer_via_lsp(
10033                            lsp_location.uri.clone(),
10034                            server_id,
10035                            language_server_name,
10036                            cx,
10037                        )
10038                    })
10039                })
10040            })?;
10041            let location = match location_task {
10042                Some(task) => Some({
10043                    let target_buffer_handle = task.await.context("open local buffer")?;
10044                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10045                        let target_start = target_buffer
10046                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10047                        let target_end = target_buffer
10048                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10049                        target_buffer.anchor_after(target_start)
10050                            ..target_buffer.anchor_before(target_end)
10051                    })?;
10052                    Location {
10053                        buffer: target_buffer_handle,
10054                        range,
10055                    }
10056                }),
10057                None => None,
10058            };
10059            Ok(location)
10060        })
10061    }
10062
10063    pub fn find_all_references(
10064        &mut self,
10065        _: &FindAllReferences,
10066        cx: &mut ViewContext<Self>,
10067    ) -> Option<Task<Result<Navigated>>> {
10068        let selection = self.selections.newest::<usize>(cx);
10069        let multi_buffer = self.buffer.read(cx);
10070        let head = selection.head();
10071
10072        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10073        let head_anchor = multi_buffer_snapshot.anchor_at(
10074            head,
10075            if head < selection.tail() {
10076                Bias::Right
10077            } else {
10078                Bias::Left
10079            },
10080        );
10081
10082        match self
10083            .find_all_references_task_sources
10084            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10085        {
10086            Ok(_) => {
10087                log::info!(
10088                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10089                );
10090                return None;
10091            }
10092            Err(i) => {
10093                self.find_all_references_task_sources.insert(i, head_anchor);
10094            }
10095        }
10096
10097        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10098        let workspace = self.workspace()?;
10099        let project = workspace.read(cx).project().clone();
10100        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10101        Some(cx.spawn(|editor, mut cx| async move {
10102            let _cleanup = defer({
10103                let mut cx = cx.clone();
10104                move || {
10105                    let _ = editor.update(&mut cx, |editor, _| {
10106                        if let Ok(i) =
10107                            editor
10108                                .find_all_references_task_sources
10109                                .binary_search_by(|anchor| {
10110                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10111                                })
10112                        {
10113                            editor.find_all_references_task_sources.remove(i);
10114                        }
10115                    });
10116                }
10117            });
10118
10119            let locations = references.await?;
10120            if locations.is_empty() {
10121                return anyhow::Ok(Navigated::No);
10122            }
10123
10124            workspace.update(&mut cx, |workspace, cx| {
10125                let title = locations
10126                    .first()
10127                    .as_ref()
10128                    .map(|location| {
10129                        let buffer = location.buffer.read(cx);
10130                        format!(
10131                            "References to `{}`",
10132                            buffer
10133                                .text_for_range(location.range.clone())
10134                                .collect::<String>()
10135                        )
10136                    })
10137                    .unwrap();
10138                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10139                Navigated::Yes
10140            })
10141        }))
10142    }
10143
10144    /// Opens a multibuffer with the given project locations in it
10145    pub fn open_locations_in_multibuffer(
10146        workspace: &mut Workspace,
10147        mut locations: Vec<Location>,
10148        title: String,
10149        split: bool,
10150        cx: &mut ViewContext<Workspace>,
10151    ) {
10152        // If there are multiple definitions, open them in a multibuffer
10153        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10154        let mut locations = locations.into_iter().peekable();
10155        let mut ranges_to_highlight = Vec::new();
10156        let capability = workspace.project().read(cx).capability();
10157
10158        let excerpt_buffer = cx.new_model(|cx| {
10159            let mut multibuffer = MultiBuffer::new(capability);
10160            while let Some(location) = locations.next() {
10161                let buffer = location.buffer.read(cx);
10162                let mut ranges_for_buffer = Vec::new();
10163                let range = location.range.to_offset(buffer);
10164                ranges_for_buffer.push(range.clone());
10165
10166                while let Some(next_location) = locations.peek() {
10167                    if next_location.buffer == location.buffer {
10168                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10169                        locations.next();
10170                    } else {
10171                        break;
10172                    }
10173                }
10174
10175                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10176                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10177                    location.buffer.clone(),
10178                    ranges_for_buffer,
10179                    DEFAULT_MULTIBUFFER_CONTEXT,
10180                    cx,
10181                ))
10182            }
10183
10184            multibuffer.with_title(title)
10185        });
10186
10187        let editor = cx.new_view(|cx| {
10188            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10189        });
10190        editor.update(cx, |editor, cx| {
10191            if let Some(first_range) = ranges_to_highlight.first() {
10192                editor.change_selections(None, cx, |selections| {
10193                    selections.clear_disjoint();
10194                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10195                });
10196            }
10197            editor.highlight_background::<Self>(
10198                &ranges_to_highlight,
10199                |theme| theme.editor_highlighted_line_background,
10200                cx,
10201            );
10202        });
10203
10204        let item = Box::new(editor);
10205        let item_id = item.item_id();
10206
10207        if split {
10208            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10209        } else {
10210            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10211                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10212                    pane.close_current_preview_item(cx)
10213                } else {
10214                    None
10215                }
10216            });
10217            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10218        }
10219        workspace.active_pane().update(cx, |pane, cx| {
10220            pane.set_preview_item_id(Some(item_id), cx);
10221        });
10222    }
10223
10224    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10225        use language::ToOffset as _;
10226
10227        let provider = self.semantics_provider.clone()?;
10228        let selection = self.selections.newest_anchor().clone();
10229        let (cursor_buffer, cursor_buffer_position) = self
10230            .buffer
10231            .read(cx)
10232            .text_anchor_for_position(selection.head(), cx)?;
10233        let (tail_buffer, cursor_buffer_position_end) = self
10234            .buffer
10235            .read(cx)
10236            .text_anchor_for_position(selection.tail(), cx)?;
10237        if tail_buffer != cursor_buffer {
10238            return None;
10239        }
10240
10241        let snapshot = cursor_buffer.read(cx).snapshot();
10242        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10243        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10244        let prepare_rename = provider
10245            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10246            .unwrap_or_else(|| Task::ready(Ok(None)));
10247        drop(snapshot);
10248
10249        Some(cx.spawn(|this, mut cx| async move {
10250            let rename_range = if let Some(range) = prepare_rename.await? {
10251                Some(range)
10252            } else {
10253                this.update(&mut cx, |this, cx| {
10254                    let buffer = this.buffer.read(cx).snapshot(cx);
10255                    let mut buffer_highlights = this
10256                        .document_highlights_for_position(selection.head(), &buffer)
10257                        .filter(|highlight| {
10258                            highlight.start.excerpt_id == selection.head().excerpt_id
10259                                && highlight.end.excerpt_id == selection.head().excerpt_id
10260                        });
10261                    buffer_highlights
10262                        .next()
10263                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10264                })?
10265            };
10266            if let Some(rename_range) = rename_range {
10267                this.update(&mut cx, |this, cx| {
10268                    let snapshot = cursor_buffer.read(cx).snapshot();
10269                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10270                    let cursor_offset_in_rename_range =
10271                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10272                    let cursor_offset_in_rename_range_end =
10273                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10274
10275                    this.take_rename(false, cx);
10276                    let buffer = this.buffer.read(cx).read(cx);
10277                    let cursor_offset = selection.head().to_offset(&buffer);
10278                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10279                    let rename_end = rename_start + rename_buffer_range.len();
10280                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10281                    let mut old_highlight_id = None;
10282                    let old_name: Arc<str> = buffer
10283                        .chunks(rename_start..rename_end, true)
10284                        .map(|chunk| {
10285                            if old_highlight_id.is_none() {
10286                                old_highlight_id = chunk.syntax_highlight_id;
10287                            }
10288                            chunk.text
10289                        })
10290                        .collect::<String>()
10291                        .into();
10292
10293                    drop(buffer);
10294
10295                    // Position the selection in the rename editor so that it matches the current selection.
10296                    this.show_local_selections = false;
10297                    let rename_editor = cx.new_view(|cx| {
10298                        let mut editor = Editor::single_line(cx);
10299                        editor.buffer.update(cx, |buffer, cx| {
10300                            buffer.edit([(0..0, old_name.clone())], None, cx)
10301                        });
10302                        let rename_selection_range = match cursor_offset_in_rename_range
10303                            .cmp(&cursor_offset_in_rename_range_end)
10304                        {
10305                            Ordering::Equal => {
10306                                editor.select_all(&SelectAll, cx);
10307                                return editor;
10308                            }
10309                            Ordering::Less => {
10310                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10311                            }
10312                            Ordering::Greater => {
10313                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10314                            }
10315                        };
10316                        if rename_selection_range.end > old_name.len() {
10317                            editor.select_all(&SelectAll, cx);
10318                        } else {
10319                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10320                                s.select_ranges([rename_selection_range]);
10321                            });
10322                        }
10323                        editor
10324                    });
10325                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10326                        if e == &EditorEvent::Focused {
10327                            cx.emit(EditorEvent::FocusedIn)
10328                        }
10329                    })
10330                    .detach();
10331
10332                    let write_highlights =
10333                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10334                    let read_highlights =
10335                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10336                    let ranges = write_highlights
10337                        .iter()
10338                        .flat_map(|(_, ranges)| ranges.iter())
10339                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10340                        .cloned()
10341                        .collect();
10342
10343                    this.highlight_text::<Rename>(
10344                        ranges,
10345                        HighlightStyle {
10346                            fade_out: Some(0.6),
10347                            ..Default::default()
10348                        },
10349                        cx,
10350                    );
10351                    let rename_focus_handle = rename_editor.focus_handle(cx);
10352                    cx.focus(&rename_focus_handle);
10353                    let block_id = this.insert_blocks(
10354                        [BlockProperties {
10355                            style: BlockStyle::Flex,
10356                            placement: BlockPlacement::Below(range.start),
10357                            height: 1,
10358                            render: Box::new({
10359                                let rename_editor = rename_editor.clone();
10360                                move |cx: &mut BlockContext| {
10361                                    let mut text_style = cx.editor_style.text.clone();
10362                                    if let Some(highlight_style) = old_highlight_id
10363                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10364                                    {
10365                                        text_style = text_style.highlight(highlight_style);
10366                                    }
10367                                    div()
10368                                        .pl(cx.anchor_x)
10369                                        .child(EditorElement::new(
10370                                            &rename_editor,
10371                                            EditorStyle {
10372                                                background: cx.theme().system().transparent,
10373                                                local_player: cx.editor_style.local_player,
10374                                                text: text_style,
10375                                                scrollbar_width: cx.editor_style.scrollbar_width,
10376                                                syntax: cx.editor_style.syntax.clone(),
10377                                                status: cx.editor_style.status.clone(),
10378                                                inlay_hints_style: HighlightStyle {
10379                                                    font_weight: Some(FontWeight::BOLD),
10380                                                    ..make_inlay_hints_style(cx)
10381                                                },
10382                                                suggestions_style: HighlightStyle {
10383                                                    color: Some(cx.theme().status().predictive),
10384                                                    ..HighlightStyle::default()
10385                                                },
10386                                                ..EditorStyle::default()
10387                                            },
10388                                        ))
10389                                        .into_any_element()
10390                                }
10391                            }),
10392                            priority: 0,
10393                        }],
10394                        Some(Autoscroll::fit()),
10395                        cx,
10396                    )[0];
10397                    this.pending_rename = Some(RenameState {
10398                        range,
10399                        old_name,
10400                        editor: rename_editor,
10401                        block_id,
10402                    });
10403                })?;
10404            }
10405
10406            Ok(())
10407        }))
10408    }
10409
10410    pub fn confirm_rename(
10411        &mut self,
10412        _: &ConfirmRename,
10413        cx: &mut ViewContext<Self>,
10414    ) -> Option<Task<Result<()>>> {
10415        let rename = self.take_rename(false, cx)?;
10416        let workspace = self.workspace()?.downgrade();
10417        let (buffer, start) = self
10418            .buffer
10419            .read(cx)
10420            .text_anchor_for_position(rename.range.start, cx)?;
10421        let (end_buffer, _) = self
10422            .buffer
10423            .read(cx)
10424            .text_anchor_for_position(rename.range.end, cx)?;
10425        if buffer != end_buffer {
10426            return None;
10427        }
10428
10429        let old_name = rename.old_name;
10430        let new_name = rename.editor.read(cx).text(cx);
10431
10432        let rename = self.semantics_provider.as_ref()?.perform_rename(
10433            &buffer,
10434            start,
10435            new_name.clone(),
10436            cx,
10437        )?;
10438
10439        Some(cx.spawn(|editor, mut cx| async move {
10440            let project_transaction = rename.await?;
10441            Self::open_project_transaction(
10442                &editor,
10443                workspace,
10444                project_transaction,
10445                format!("Rename: {}{}", old_name, new_name),
10446                cx.clone(),
10447            )
10448            .await?;
10449
10450            editor.update(&mut cx, |editor, cx| {
10451                editor.refresh_document_highlights(cx);
10452            })?;
10453            Ok(())
10454        }))
10455    }
10456
10457    fn take_rename(
10458        &mut self,
10459        moving_cursor: bool,
10460        cx: &mut ViewContext<Self>,
10461    ) -> Option<RenameState> {
10462        let rename = self.pending_rename.take()?;
10463        if rename.editor.focus_handle(cx).is_focused(cx) {
10464            cx.focus(&self.focus_handle);
10465        }
10466
10467        self.remove_blocks(
10468            [rename.block_id].into_iter().collect(),
10469            Some(Autoscroll::fit()),
10470            cx,
10471        );
10472        self.clear_highlights::<Rename>(cx);
10473        self.show_local_selections = true;
10474
10475        if moving_cursor {
10476            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10477                editor.selections.newest::<usize>(cx).head()
10478            });
10479
10480            // Update the selection to match the position of the selection inside
10481            // the rename editor.
10482            let snapshot = self.buffer.read(cx).read(cx);
10483            let rename_range = rename.range.to_offset(&snapshot);
10484            let cursor_in_editor = snapshot
10485                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10486                .min(rename_range.end);
10487            drop(snapshot);
10488
10489            self.change_selections(None, cx, |s| {
10490                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10491            });
10492        } else {
10493            self.refresh_document_highlights(cx);
10494        }
10495
10496        Some(rename)
10497    }
10498
10499    pub fn pending_rename(&self) -> Option<&RenameState> {
10500        self.pending_rename.as_ref()
10501    }
10502
10503    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10504        let project = match &self.project {
10505            Some(project) => project.clone(),
10506            None => return None,
10507        };
10508
10509        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10510    }
10511
10512    fn format_selections(
10513        &mut self,
10514        _: &FormatSelections,
10515        cx: &mut ViewContext<Self>,
10516    ) -> Option<Task<Result<()>>> {
10517        let project = match &self.project {
10518            Some(project) => project.clone(),
10519            None => return None,
10520        };
10521
10522        let selections = self
10523            .selections
10524            .all_adjusted(cx)
10525            .into_iter()
10526            .filter(|s| !s.is_empty())
10527            .collect_vec();
10528
10529        Some(self.perform_format(
10530            project,
10531            FormatTrigger::Manual,
10532            FormatTarget::Ranges(selections),
10533            cx,
10534        ))
10535    }
10536
10537    fn perform_format(
10538        &mut self,
10539        project: Model<Project>,
10540        trigger: FormatTrigger,
10541        target: FormatTarget,
10542        cx: &mut ViewContext<Self>,
10543    ) -> Task<Result<()>> {
10544        let buffer = self.buffer().clone();
10545        let mut buffers = buffer.read(cx).all_buffers();
10546        if trigger == FormatTrigger::Save {
10547            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10548        }
10549
10550        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10551        let format = project.update(cx, |project, cx| {
10552            project.format(buffers, true, trigger, target, cx)
10553        });
10554
10555        cx.spawn(|_, mut cx| async move {
10556            let transaction = futures::select_biased! {
10557                () = timeout => {
10558                    log::warn!("timed out waiting for formatting");
10559                    None
10560                }
10561                transaction = format.log_err().fuse() => transaction,
10562            };
10563
10564            buffer
10565                .update(&mut cx, |buffer, cx| {
10566                    if let Some(transaction) = transaction {
10567                        if !buffer.is_singleton() {
10568                            buffer.push_transaction(&transaction.0, cx);
10569                        }
10570                    }
10571
10572                    cx.notify();
10573                })
10574                .ok();
10575
10576            Ok(())
10577        })
10578    }
10579
10580    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10581        if let Some(project) = self.project.clone() {
10582            self.buffer.update(cx, |multi_buffer, cx| {
10583                project.update(cx, |project, cx| {
10584                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10585                });
10586            })
10587        }
10588    }
10589
10590    fn cancel_language_server_work(
10591        &mut self,
10592        _: &actions::CancelLanguageServerWork,
10593        cx: &mut ViewContext<Self>,
10594    ) {
10595        if let Some(project) = self.project.clone() {
10596            self.buffer.update(cx, |multi_buffer, cx| {
10597                project.update(cx, |project, cx| {
10598                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10599                });
10600            })
10601        }
10602    }
10603
10604    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10605        cx.show_character_palette();
10606    }
10607
10608    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10609        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10610            let buffer = self.buffer.read(cx).snapshot(cx);
10611            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10612            let is_valid = buffer
10613                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10614                .any(|entry| {
10615                    entry.diagnostic.is_primary
10616                        && !entry.range.is_empty()
10617                        && entry.range.start == primary_range_start
10618                        && entry.diagnostic.message == active_diagnostics.primary_message
10619                });
10620
10621            if is_valid != active_diagnostics.is_valid {
10622                active_diagnostics.is_valid = is_valid;
10623                let mut new_styles = HashMap::default();
10624                for (block_id, diagnostic) in &active_diagnostics.blocks {
10625                    new_styles.insert(
10626                        *block_id,
10627                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10628                    );
10629                }
10630                self.display_map.update(cx, |display_map, _cx| {
10631                    display_map.replace_blocks(new_styles)
10632                });
10633            }
10634        }
10635    }
10636
10637    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10638        self.dismiss_diagnostics(cx);
10639        let snapshot = self.snapshot(cx);
10640        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10641            let buffer = self.buffer.read(cx).snapshot(cx);
10642
10643            let mut primary_range = None;
10644            let mut primary_message = None;
10645            let mut group_end = Point::zero();
10646            let diagnostic_group = buffer
10647                .diagnostic_group::<MultiBufferPoint>(group_id)
10648                .filter_map(|entry| {
10649                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10650                        && (entry.range.start.row == entry.range.end.row
10651                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10652                    {
10653                        return None;
10654                    }
10655                    if entry.range.end > group_end {
10656                        group_end = entry.range.end;
10657                    }
10658                    if entry.diagnostic.is_primary {
10659                        primary_range = Some(entry.range.clone());
10660                        primary_message = Some(entry.diagnostic.message.clone());
10661                    }
10662                    Some(entry)
10663                })
10664                .collect::<Vec<_>>();
10665            let primary_range = primary_range?;
10666            let primary_message = primary_message?;
10667            let primary_range =
10668                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10669
10670            let blocks = display_map
10671                .insert_blocks(
10672                    diagnostic_group.iter().map(|entry| {
10673                        let diagnostic = entry.diagnostic.clone();
10674                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10675                        BlockProperties {
10676                            style: BlockStyle::Fixed,
10677                            placement: BlockPlacement::Below(
10678                                buffer.anchor_after(entry.range.start),
10679                            ),
10680                            height: message_height,
10681                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10682                            priority: 0,
10683                        }
10684                    }),
10685                    cx,
10686                )
10687                .into_iter()
10688                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10689                .collect();
10690
10691            Some(ActiveDiagnosticGroup {
10692                primary_range,
10693                primary_message,
10694                group_id,
10695                blocks,
10696                is_valid: true,
10697            })
10698        });
10699        self.active_diagnostics.is_some()
10700    }
10701
10702    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10703        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10704            self.display_map.update(cx, |display_map, cx| {
10705                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10706            });
10707            cx.notify();
10708        }
10709    }
10710
10711    pub fn set_selections_from_remote(
10712        &mut self,
10713        selections: Vec<Selection<Anchor>>,
10714        pending_selection: Option<Selection<Anchor>>,
10715        cx: &mut ViewContext<Self>,
10716    ) {
10717        let old_cursor_position = self.selections.newest_anchor().head();
10718        self.selections.change_with(cx, |s| {
10719            s.select_anchors(selections);
10720            if let Some(pending_selection) = pending_selection {
10721                s.set_pending(pending_selection, SelectMode::Character);
10722            } else {
10723                s.clear_pending();
10724            }
10725        });
10726        self.selections_did_change(false, &old_cursor_position, true, cx);
10727    }
10728
10729    fn push_to_selection_history(&mut self) {
10730        self.selection_history.push(SelectionHistoryEntry {
10731            selections: self.selections.disjoint_anchors(),
10732            select_next_state: self.select_next_state.clone(),
10733            select_prev_state: self.select_prev_state.clone(),
10734            add_selections_state: self.add_selections_state.clone(),
10735        });
10736    }
10737
10738    pub fn transact(
10739        &mut self,
10740        cx: &mut ViewContext<Self>,
10741        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10742    ) -> Option<TransactionId> {
10743        self.start_transaction_at(Instant::now(), cx);
10744        update(self, cx);
10745        self.end_transaction_at(Instant::now(), cx)
10746    }
10747
10748    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10749        self.end_selection(cx);
10750        if let Some(tx_id) = self
10751            .buffer
10752            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10753        {
10754            self.selection_history
10755                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10756            cx.emit(EditorEvent::TransactionBegun {
10757                transaction_id: tx_id,
10758            })
10759        }
10760    }
10761
10762    fn end_transaction_at(
10763        &mut self,
10764        now: Instant,
10765        cx: &mut ViewContext<Self>,
10766    ) -> Option<TransactionId> {
10767        if let Some(transaction_id) = self
10768            .buffer
10769            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10770        {
10771            if let Some((_, end_selections)) =
10772                self.selection_history.transaction_mut(transaction_id)
10773            {
10774                *end_selections = Some(self.selections.disjoint_anchors());
10775            } else {
10776                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10777            }
10778
10779            cx.emit(EditorEvent::Edited { transaction_id });
10780            Some(transaction_id)
10781        } else {
10782            None
10783        }
10784    }
10785
10786    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10787        let selection = self.selections.newest::<Point>(cx);
10788
10789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10790        let range = if selection.is_empty() {
10791            let point = selection.head().to_display_point(&display_map);
10792            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10793            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10794                .to_point(&display_map);
10795            start..end
10796        } else {
10797            selection.range()
10798        };
10799        if display_map.folds_in_range(range).next().is_some() {
10800            self.unfold_lines(&Default::default(), cx)
10801        } else {
10802            self.fold(&Default::default(), cx)
10803        }
10804    }
10805
10806    pub fn toggle_fold_recursive(
10807        &mut self,
10808        _: &actions::ToggleFoldRecursive,
10809        cx: &mut ViewContext<Self>,
10810    ) {
10811        let selection = self.selections.newest::<Point>(cx);
10812
10813        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10814        let range = if selection.is_empty() {
10815            let point = selection.head().to_display_point(&display_map);
10816            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10817            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10818                .to_point(&display_map);
10819            start..end
10820        } else {
10821            selection.range()
10822        };
10823        if display_map.folds_in_range(range).next().is_some() {
10824            self.unfold_recursive(&Default::default(), cx)
10825        } else {
10826            self.fold_recursive(&Default::default(), cx)
10827        }
10828    }
10829
10830    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10831        let mut fold_ranges = Vec::new();
10832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10833        let selections = self.selections.all_adjusted(cx);
10834
10835        for selection in selections {
10836            let range = selection.range().sorted();
10837            let buffer_start_row = range.start.row;
10838
10839            if range.start.row != range.end.row {
10840                let mut found = false;
10841                let mut row = range.start.row;
10842                while row <= range.end.row {
10843                    if let Some((foldable_range, fold_text)) =
10844                        { display_map.foldable_range(MultiBufferRow(row)) }
10845                    {
10846                        found = true;
10847                        row = foldable_range.end.row + 1;
10848                        fold_ranges.push((foldable_range, fold_text));
10849                    } else {
10850                        row += 1
10851                    }
10852                }
10853                if found {
10854                    continue;
10855                }
10856            }
10857
10858            for row in (0..=range.start.row).rev() {
10859                if let Some((foldable_range, fold_text)) =
10860                    display_map.foldable_range(MultiBufferRow(row))
10861                {
10862                    if foldable_range.end.row >= buffer_start_row {
10863                        fold_ranges.push((foldable_range, fold_text));
10864                        if row <= range.start.row {
10865                            break;
10866                        }
10867                    }
10868                }
10869            }
10870        }
10871
10872        self.fold_ranges(fold_ranges, true, cx);
10873    }
10874
10875    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10876        let fold_at_level = fold_at.level;
10877        let snapshot = self.buffer.read(cx).snapshot(cx);
10878        let mut fold_ranges = Vec::new();
10879        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10880
10881        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10882            while start_row < end_row {
10883                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10884                    Some(foldable_range) => {
10885                        let nested_start_row = foldable_range.0.start.row + 1;
10886                        let nested_end_row = foldable_range.0.end.row;
10887
10888                        if current_level < fold_at_level {
10889                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10890                        } else if current_level == fold_at_level {
10891                            fold_ranges.push(foldable_range);
10892                        }
10893
10894                        start_row = nested_end_row + 1;
10895                    }
10896                    None => start_row += 1,
10897                }
10898            }
10899        }
10900
10901        self.fold_ranges(fold_ranges, true, cx);
10902    }
10903
10904    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10905        let mut fold_ranges = Vec::new();
10906        let snapshot = self.buffer.read(cx).snapshot(cx);
10907
10908        for row in 0..snapshot.max_buffer_row().0 {
10909            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10910                fold_ranges.push(foldable_range);
10911            }
10912        }
10913
10914        self.fold_ranges(fold_ranges, true, cx);
10915    }
10916
10917    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10918        let mut fold_ranges = Vec::new();
10919        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10920        let selections = self.selections.all_adjusted(cx);
10921
10922        for selection in selections {
10923            let range = selection.range().sorted();
10924            let buffer_start_row = range.start.row;
10925
10926            if range.start.row != range.end.row {
10927                let mut found = false;
10928                for row in range.start.row..=range.end.row {
10929                    if let Some((foldable_range, fold_text)) =
10930                        { display_map.foldable_range(MultiBufferRow(row)) }
10931                    {
10932                        found = true;
10933                        fold_ranges.push((foldable_range, fold_text));
10934                    }
10935                }
10936                if found {
10937                    continue;
10938                }
10939            }
10940
10941            for row in (0..=range.start.row).rev() {
10942                if let Some((foldable_range, fold_text)) =
10943                    display_map.foldable_range(MultiBufferRow(row))
10944                {
10945                    if foldable_range.end.row >= buffer_start_row {
10946                        fold_ranges.push((foldable_range, fold_text));
10947                    } else {
10948                        break;
10949                    }
10950                }
10951            }
10952        }
10953
10954        self.fold_ranges(fold_ranges, true, cx);
10955    }
10956
10957    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10958        let buffer_row = fold_at.buffer_row;
10959        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10960
10961        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10962            let autoscroll = self
10963                .selections
10964                .all::<Point>(cx)
10965                .iter()
10966                .any(|selection| fold_range.overlaps(&selection.range()));
10967
10968            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10969        }
10970    }
10971
10972    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10974        let buffer = &display_map.buffer_snapshot;
10975        let selections = self.selections.all::<Point>(cx);
10976        let ranges = selections
10977            .iter()
10978            .map(|s| {
10979                let range = s.display_range(&display_map).sorted();
10980                let mut start = range.start.to_point(&display_map);
10981                let mut end = range.end.to_point(&display_map);
10982                start.column = 0;
10983                end.column = buffer.line_len(MultiBufferRow(end.row));
10984                start..end
10985            })
10986            .collect::<Vec<_>>();
10987
10988        self.unfold_ranges(ranges, true, true, cx);
10989    }
10990
10991    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10992        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10993        let selections = self.selections.all::<Point>(cx);
10994        let ranges = selections
10995            .iter()
10996            .map(|s| {
10997                let mut range = s.display_range(&display_map).sorted();
10998                *range.start.column_mut() = 0;
10999                *range.end.column_mut() = display_map.line_len(range.end.row());
11000                let start = range.start.to_point(&display_map);
11001                let end = range.end.to_point(&display_map);
11002                start..end
11003            })
11004            .collect::<Vec<_>>();
11005
11006        self.unfold_ranges(ranges, true, true, cx);
11007    }
11008
11009    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11011
11012        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11013            ..Point::new(
11014                unfold_at.buffer_row.0,
11015                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11016            );
11017
11018        let autoscroll = self
11019            .selections
11020            .all::<Point>(cx)
11021            .iter()
11022            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11023
11024        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
11025    }
11026
11027    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11028        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11029        self.unfold_ranges(
11030            [Point::zero()..display_map.max_point().to_point(&display_map)],
11031            true,
11032            true,
11033            cx,
11034        );
11035    }
11036
11037    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11038        let selections = self.selections.all::<Point>(cx);
11039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11040        let line_mode = self.selections.line_mode;
11041        let ranges = selections.into_iter().map(|s| {
11042            if line_mode {
11043                let start = Point::new(s.start.row, 0);
11044                let end = Point::new(
11045                    s.end.row,
11046                    display_map
11047                        .buffer_snapshot
11048                        .line_len(MultiBufferRow(s.end.row)),
11049                );
11050                (start..end, display_map.fold_placeholder.clone())
11051            } else {
11052                (s.start..s.end, display_map.fold_placeholder.clone())
11053            }
11054        });
11055        self.fold_ranges(ranges, true, cx);
11056    }
11057
11058    pub fn fold_ranges<T: ToOffset + Clone>(
11059        &mut self,
11060        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11061        auto_scroll: bool,
11062        cx: &mut ViewContext<Self>,
11063    ) {
11064        let mut fold_ranges = Vec::new();
11065        let mut buffers_affected = HashMap::default();
11066        let multi_buffer = self.buffer().read(cx);
11067        for (fold_range, fold_text) in ranges {
11068            if let Some((_, buffer, _)) =
11069                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11070            {
11071                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11072            };
11073            fold_ranges.push((fold_range, fold_text));
11074        }
11075
11076        let mut ranges = fold_ranges.into_iter().peekable();
11077        if ranges.peek().is_some() {
11078            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11079
11080            if auto_scroll {
11081                self.request_autoscroll(Autoscroll::fit(), cx);
11082            }
11083
11084            for buffer in buffers_affected.into_values() {
11085                self.sync_expanded_diff_hunks(buffer, cx);
11086            }
11087
11088            cx.notify();
11089
11090            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11091                // Clear diagnostics block when folding a range that contains it.
11092                let snapshot = self.snapshot(cx);
11093                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11094                    drop(snapshot);
11095                    self.active_diagnostics = Some(active_diagnostics);
11096                    self.dismiss_diagnostics(cx);
11097                } else {
11098                    self.active_diagnostics = Some(active_diagnostics);
11099                }
11100            }
11101
11102            self.scrollbar_marker_state.dirty = true;
11103        }
11104    }
11105
11106    pub fn unfold_ranges<T: ToOffset + Clone>(
11107        &mut self,
11108        ranges: impl IntoIterator<Item = Range<T>>,
11109        inclusive: bool,
11110        auto_scroll: bool,
11111        cx: &mut ViewContext<Self>,
11112    ) {
11113        let mut unfold_ranges = Vec::new();
11114        let mut buffers_affected = HashMap::default();
11115        let multi_buffer = self.buffer().read(cx);
11116        for range in ranges {
11117            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11118                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11119            };
11120            unfold_ranges.push(range);
11121        }
11122
11123        let mut ranges = unfold_ranges.into_iter().peekable();
11124        if ranges.peek().is_some() {
11125            self.display_map
11126                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11127            if auto_scroll {
11128                self.request_autoscroll(Autoscroll::fit(), cx);
11129            }
11130
11131            for buffer in buffers_affected.into_values() {
11132                self.sync_expanded_diff_hunks(buffer, cx);
11133            }
11134
11135            cx.notify();
11136            self.scrollbar_marker_state.dirty = true;
11137            self.active_indent_guides_state.dirty = true;
11138        }
11139    }
11140
11141    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11142        self.display_map.read(cx).fold_placeholder.clone()
11143    }
11144
11145    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11146        if hovered != self.gutter_hovered {
11147            self.gutter_hovered = hovered;
11148            cx.notify();
11149        }
11150    }
11151
11152    pub fn insert_blocks(
11153        &mut self,
11154        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11155        autoscroll: Option<Autoscroll>,
11156        cx: &mut ViewContext<Self>,
11157    ) -> Vec<CustomBlockId> {
11158        let blocks = self
11159            .display_map
11160            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11161        if let Some(autoscroll) = autoscroll {
11162            self.request_autoscroll(autoscroll, cx);
11163        }
11164        cx.notify();
11165        blocks
11166    }
11167
11168    pub fn resize_blocks(
11169        &mut self,
11170        heights: HashMap<CustomBlockId, u32>,
11171        autoscroll: Option<Autoscroll>,
11172        cx: &mut ViewContext<Self>,
11173    ) {
11174        self.display_map
11175            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11176        if let Some(autoscroll) = autoscroll {
11177            self.request_autoscroll(autoscroll, cx);
11178        }
11179        cx.notify();
11180    }
11181
11182    pub fn replace_blocks(
11183        &mut self,
11184        renderers: HashMap<CustomBlockId, RenderBlock>,
11185        autoscroll: Option<Autoscroll>,
11186        cx: &mut ViewContext<Self>,
11187    ) {
11188        self.display_map
11189            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11190        if let Some(autoscroll) = autoscroll {
11191            self.request_autoscroll(autoscroll, cx);
11192        }
11193        cx.notify();
11194    }
11195
11196    pub fn remove_blocks(
11197        &mut self,
11198        block_ids: HashSet<CustomBlockId>,
11199        autoscroll: Option<Autoscroll>,
11200        cx: &mut ViewContext<Self>,
11201    ) {
11202        self.display_map.update(cx, |display_map, cx| {
11203            display_map.remove_blocks(block_ids, cx)
11204        });
11205        if let Some(autoscroll) = autoscroll {
11206            self.request_autoscroll(autoscroll, cx);
11207        }
11208        cx.notify();
11209    }
11210
11211    pub fn row_for_block(
11212        &self,
11213        block_id: CustomBlockId,
11214        cx: &mut ViewContext<Self>,
11215    ) -> Option<DisplayRow> {
11216        self.display_map
11217            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11218    }
11219
11220    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11221        self.focused_block = Some(focused_block);
11222    }
11223
11224    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11225        self.focused_block.take()
11226    }
11227
11228    pub fn insert_creases(
11229        &mut self,
11230        creases: impl IntoIterator<Item = Crease>,
11231        cx: &mut ViewContext<Self>,
11232    ) -> Vec<CreaseId> {
11233        self.display_map
11234            .update(cx, |map, cx| map.insert_creases(creases, cx))
11235    }
11236
11237    pub fn remove_creases(
11238        &mut self,
11239        ids: impl IntoIterator<Item = CreaseId>,
11240        cx: &mut ViewContext<Self>,
11241    ) {
11242        self.display_map
11243            .update(cx, |map, cx| map.remove_creases(ids, cx));
11244    }
11245
11246    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11247        self.display_map
11248            .update(cx, |map, cx| map.snapshot(cx))
11249            .longest_row()
11250    }
11251
11252    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11253        self.display_map
11254            .update(cx, |map, cx| map.snapshot(cx))
11255            .max_point()
11256    }
11257
11258    pub fn text(&self, cx: &AppContext) -> String {
11259        self.buffer.read(cx).read(cx).text()
11260    }
11261
11262    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11263        let text = self.text(cx);
11264        let text = text.trim();
11265
11266        if text.is_empty() {
11267            return None;
11268        }
11269
11270        Some(text.to_string())
11271    }
11272
11273    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11274        self.transact(cx, |this, cx| {
11275            this.buffer
11276                .read(cx)
11277                .as_singleton()
11278                .expect("you can only call set_text on editors for singleton buffers")
11279                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11280        });
11281    }
11282
11283    pub fn display_text(&self, cx: &mut AppContext) -> String {
11284        self.display_map
11285            .update(cx, |map, cx| map.snapshot(cx))
11286            .text()
11287    }
11288
11289    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11290        let mut wrap_guides = smallvec::smallvec![];
11291
11292        if self.show_wrap_guides == Some(false) {
11293            return wrap_guides;
11294        }
11295
11296        let settings = self.buffer.read(cx).settings_at(0, cx);
11297        if settings.show_wrap_guides {
11298            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11299                wrap_guides.push((soft_wrap as usize, true));
11300            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11301                wrap_guides.push((soft_wrap as usize, true));
11302            }
11303            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11304        }
11305
11306        wrap_guides
11307    }
11308
11309    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11310        let settings = self.buffer.read(cx).settings_at(0, cx);
11311        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11312        match mode {
11313            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11314                SoftWrap::None
11315            }
11316            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11317            language_settings::SoftWrap::PreferredLineLength => {
11318                SoftWrap::Column(settings.preferred_line_length)
11319            }
11320            language_settings::SoftWrap::Bounded => {
11321                SoftWrap::Bounded(settings.preferred_line_length)
11322            }
11323        }
11324    }
11325
11326    pub fn set_soft_wrap_mode(
11327        &mut self,
11328        mode: language_settings::SoftWrap,
11329        cx: &mut ViewContext<Self>,
11330    ) {
11331        self.soft_wrap_mode_override = Some(mode);
11332        cx.notify();
11333    }
11334
11335    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11336        self.text_style_refinement = Some(style);
11337    }
11338
11339    /// called by the Element so we know what style we were most recently rendered with.
11340    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11341        let rem_size = cx.rem_size();
11342        self.display_map.update(cx, |map, cx| {
11343            map.set_font(
11344                style.text.font(),
11345                style.text.font_size.to_pixels(rem_size),
11346                cx,
11347            )
11348        });
11349        self.style = Some(style);
11350    }
11351
11352    pub fn style(&self) -> Option<&EditorStyle> {
11353        self.style.as_ref()
11354    }
11355
11356    // Called by the element. This method is not designed to be called outside of the editor
11357    // element's layout code because it does not notify when rewrapping is computed synchronously.
11358    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11359        self.display_map
11360            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11361    }
11362
11363    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11364        if self.soft_wrap_mode_override.is_some() {
11365            self.soft_wrap_mode_override.take();
11366        } else {
11367            let soft_wrap = match self.soft_wrap_mode(cx) {
11368                SoftWrap::GitDiff => return,
11369                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11370                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11371                    language_settings::SoftWrap::None
11372                }
11373            };
11374            self.soft_wrap_mode_override = Some(soft_wrap);
11375        }
11376        cx.notify();
11377    }
11378
11379    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11380        let Some(workspace) = self.workspace() else {
11381            return;
11382        };
11383        let fs = workspace.read(cx).app_state().fs.clone();
11384        let current_show = TabBarSettings::get_global(cx).show;
11385        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11386            setting.show = Some(!current_show);
11387        });
11388    }
11389
11390    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11391        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11392            self.buffer
11393                .read(cx)
11394                .settings_at(0, cx)
11395                .indent_guides
11396                .enabled
11397        });
11398        self.show_indent_guides = Some(!currently_enabled);
11399        cx.notify();
11400    }
11401
11402    fn should_show_indent_guides(&self) -> Option<bool> {
11403        self.show_indent_guides
11404    }
11405
11406    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11407        let mut editor_settings = EditorSettings::get_global(cx).clone();
11408        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11409        EditorSettings::override_global(editor_settings, cx);
11410    }
11411
11412    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11413        self.use_relative_line_numbers
11414            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11415    }
11416
11417    pub fn toggle_relative_line_numbers(
11418        &mut self,
11419        _: &ToggleRelativeLineNumbers,
11420        cx: &mut ViewContext<Self>,
11421    ) {
11422        let is_relative = self.should_use_relative_line_numbers(cx);
11423        self.set_relative_line_number(Some(!is_relative), cx)
11424    }
11425
11426    pub fn set_relative_line_number(
11427        &mut self,
11428        is_relative: Option<bool>,
11429        cx: &mut ViewContext<Self>,
11430    ) {
11431        self.use_relative_line_numbers = is_relative;
11432        cx.notify();
11433    }
11434
11435    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11436        self.show_gutter = show_gutter;
11437        cx.notify();
11438    }
11439
11440    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11441        self.show_line_numbers = Some(show_line_numbers);
11442        cx.notify();
11443    }
11444
11445    pub fn set_show_git_diff_gutter(
11446        &mut self,
11447        show_git_diff_gutter: bool,
11448        cx: &mut ViewContext<Self>,
11449    ) {
11450        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11451        cx.notify();
11452    }
11453
11454    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11455        self.show_code_actions = Some(show_code_actions);
11456        cx.notify();
11457    }
11458
11459    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11460        self.show_runnables = Some(show_runnables);
11461        cx.notify();
11462    }
11463
11464    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11465        if self.display_map.read(cx).masked != masked {
11466            self.display_map.update(cx, |map, _| map.masked = masked);
11467        }
11468        cx.notify()
11469    }
11470
11471    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11472        self.show_wrap_guides = Some(show_wrap_guides);
11473        cx.notify();
11474    }
11475
11476    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11477        self.show_indent_guides = Some(show_indent_guides);
11478        cx.notify();
11479    }
11480
11481    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11482        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11483            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11484                if let Some(dir) = file.abs_path(cx).parent() {
11485                    return Some(dir.to_owned());
11486                }
11487            }
11488
11489            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11490                return Some(project_path.path.to_path_buf());
11491            }
11492        }
11493
11494        None
11495    }
11496
11497    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11498        self.active_excerpt(cx)?
11499            .1
11500            .read(cx)
11501            .file()
11502            .and_then(|f| f.as_local())
11503    }
11504
11505    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11506        if let Some(target) = self.target_file(cx) {
11507            cx.reveal_path(&target.abs_path(cx));
11508        }
11509    }
11510
11511    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11512        if let Some(file) = self.target_file(cx) {
11513            if let Some(path) = file.abs_path(cx).to_str() {
11514                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11515            }
11516        }
11517    }
11518
11519    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11520        if let Some(file) = self.target_file(cx) {
11521            if let Some(path) = file.path().to_str() {
11522                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11523            }
11524        }
11525    }
11526
11527    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11528        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11529
11530        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11531            self.start_git_blame(true, cx);
11532        }
11533
11534        cx.notify();
11535    }
11536
11537    pub fn toggle_git_blame_inline(
11538        &mut self,
11539        _: &ToggleGitBlameInline,
11540        cx: &mut ViewContext<Self>,
11541    ) {
11542        self.toggle_git_blame_inline_internal(true, cx);
11543        cx.notify();
11544    }
11545
11546    pub fn git_blame_inline_enabled(&self) -> bool {
11547        self.git_blame_inline_enabled
11548    }
11549
11550    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11551        self.show_selection_menu = self
11552            .show_selection_menu
11553            .map(|show_selections_menu| !show_selections_menu)
11554            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11555
11556        cx.notify();
11557    }
11558
11559    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11560        self.show_selection_menu
11561            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11562    }
11563
11564    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11565        if let Some(project) = self.project.as_ref() {
11566            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11567                return;
11568            };
11569
11570            if buffer.read(cx).file().is_none() {
11571                return;
11572            }
11573
11574            let focused = self.focus_handle(cx).contains_focused(cx);
11575
11576            let project = project.clone();
11577            let blame =
11578                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11579            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11580            self.blame = Some(blame);
11581        }
11582    }
11583
11584    fn toggle_git_blame_inline_internal(
11585        &mut self,
11586        user_triggered: bool,
11587        cx: &mut ViewContext<Self>,
11588    ) {
11589        if self.git_blame_inline_enabled {
11590            self.git_blame_inline_enabled = false;
11591            self.show_git_blame_inline = false;
11592            self.show_git_blame_inline_delay_task.take();
11593        } else {
11594            self.git_blame_inline_enabled = true;
11595            self.start_git_blame_inline(user_triggered, cx);
11596        }
11597
11598        cx.notify();
11599    }
11600
11601    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11602        self.start_git_blame(user_triggered, cx);
11603
11604        if ProjectSettings::get_global(cx)
11605            .git
11606            .inline_blame_delay()
11607            .is_some()
11608        {
11609            self.start_inline_blame_timer(cx);
11610        } else {
11611            self.show_git_blame_inline = true
11612        }
11613    }
11614
11615    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11616        self.blame.as_ref()
11617    }
11618
11619    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11620        self.show_git_blame_gutter && self.has_blame_entries(cx)
11621    }
11622
11623    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11624        self.show_git_blame_inline
11625            && self.focus_handle.is_focused(cx)
11626            && !self.newest_selection_head_on_empty_line(cx)
11627            && self.has_blame_entries(cx)
11628    }
11629
11630    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11631        self.blame()
11632            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11633    }
11634
11635    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11636        let cursor_anchor = self.selections.newest_anchor().head();
11637
11638        let snapshot = self.buffer.read(cx).snapshot(cx);
11639        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11640
11641        snapshot.line_len(buffer_row) == 0
11642    }
11643
11644    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11645        let buffer_and_selection = maybe!({
11646            let selection = self.selections.newest::<Point>(cx);
11647            let selection_range = selection.range();
11648
11649            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11650                (buffer, selection_range.start.row..selection_range.end.row)
11651            } else {
11652                let buffer_ranges = self
11653                    .buffer()
11654                    .read(cx)
11655                    .range_to_buffer_ranges(selection_range, cx);
11656
11657                let (buffer, range, _) = if selection.reversed {
11658                    buffer_ranges.first()
11659                } else {
11660                    buffer_ranges.last()
11661                }?;
11662
11663                let snapshot = buffer.read(cx).snapshot();
11664                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11665                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11666                (buffer.clone(), selection)
11667            };
11668
11669            Some((buffer, selection))
11670        });
11671
11672        let Some((buffer, selection)) = buffer_and_selection else {
11673            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11674        };
11675
11676        let Some(project) = self.project.as_ref() else {
11677            return Task::ready(Err(anyhow!("editor does not have project")));
11678        };
11679
11680        project.update(cx, |project, cx| {
11681            project.get_permalink_to_line(&buffer, selection, cx)
11682        })
11683    }
11684
11685    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11686        let permalink_task = self.get_permalink_to_line(cx);
11687        let workspace = self.workspace();
11688
11689        cx.spawn(|_, mut cx| async move {
11690            match permalink_task.await {
11691                Ok(permalink) => {
11692                    cx.update(|cx| {
11693                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11694                    })
11695                    .ok();
11696                }
11697                Err(err) => {
11698                    let message = format!("Failed to copy permalink: {err}");
11699
11700                    Err::<(), anyhow::Error>(err).log_err();
11701
11702                    if let Some(workspace) = workspace {
11703                        workspace
11704                            .update(&mut cx, |workspace, cx| {
11705                                struct CopyPermalinkToLine;
11706
11707                                workspace.show_toast(
11708                                    Toast::new(
11709                                        NotificationId::unique::<CopyPermalinkToLine>(),
11710                                        message,
11711                                    ),
11712                                    cx,
11713                                )
11714                            })
11715                            .ok();
11716                    }
11717                }
11718            }
11719        })
11720        .detach();
11721    }
11722
11723    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11724        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11725        if let Some(file) = self.target_file(cx) {
11726            if let Some(path) = file.path().to_str() {
11727                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11728            }
11729        }
11730    }
11731
11732    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11733        let permalink_task = self.get_permalink_to_line(cx);
11734        let workspace = self.workspace();
11735
11736        cx.spawn(|_, mut cx| async move {
11737            match permalink_task.await {
11738                Ok(permalink) => {
11739                    cx.update(|cx| {
11740                        cx.open_url(permalink.as_ref());
11741                    })
11742                    .ok();
11743                }
11744                Err(err) => {
11745                    let message = format!("Failed to open permalink: {err}");
11746
11747                    Err::<(), anyhow::Error>(err).log_err();
11748
11749                    if let Some(workspace) = workspace {
11750                        workspace
11751                            .update(&mut cx, |workspace, cx| {
11752                                struct OpenPermalinkToLine;
11753
11754                                workspace.show_toast(
11755                                    Toast::new(
11756                                        NotificationId::unique::<OpenPermalinkToLine>(),
11757                                        message,
11758                                    ),
11759                                    cx,
11760                                )
11761                            })
11762                            .ok();
11763                    }
11764                }
11765            }
11766        })
11767        .detach();
11768    }
11769
11770    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11771    /// last highlight added will be used.
11772    ///
11773    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11774    pub fn highlight_rows<T: 'static>(
11775        &mut self,
11776        range: Range<Anchor>,
11777        color: Hsla,
11778        should_autoscroll: bool,
11779        cx: &mut ViewContext<Self>,
11780    ) {
11781        let snapshot = self.buffer().read(cx).snapshot(cx);
11782        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11783        let ix = row_highlights.binary_search_by(|highlight| {
11784            Ordering::Equal
11785                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11786                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11787        });
11788
11789        if let Err(mut ix) = ix {
11790            let index = post_inc(&mut self.highlight_order);
11791
11792            // If this range intersects with the preceding highlight, then merge it with
11793            // the preceding highlight. Otherwise insert a new highlight.
11794            let mut merged = false;
11795            if ix > 0 {
11796                let prev_highlight = &mut row_highlights[ix - 1];
11797                if prev_highlight
11798                    .range
11799                    .end
11800                    .cmp(&range.start, &snapshot)
11801                    .is_ge()
11802                {
11803                    ix -= 1;
11804                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11805                        prev_highlight.range.end = range.end;
11806                    }
11807                    merged = true;
11808                    prev_highlight.index = index;
11809                    prev_highlight.color = color;
11810                    prev_highlight.should_autoscroll = should_autoscroll;
11811                }
11812            }
11813
11814            if !merged {
11815                row_highlights.insert(
11816                    ix,
11817                    RowHighlight {
11818                        range: range.clone(),
11819                        index,
11820                        color,
11821                        should_autoscroll,
11822                    },
11823                );
11824            }
11825
11826            // If any of the following highlights intersect with this one, merge them.
11827            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11828                let highlight = &row_highlights[ix];
11829                if next_highlight
11830                    .range
11831                    .start
11832                    .cmp(&highlight.range.end, &snapshot)
11833                    .is_le()
11834                {
11835                    if next_highlight
11836                        .range
11837                        .end
11838                        .cmp(&highlight.range.end, &snapshot)
11839                        .is_gt()
11840                    {
11841                        row_highlights[ix].range.end = next_highlight.range.end;
11842                    }
11843                    row_highlights.remove(ix + 1);
11844                } else {
11845                    break;
11846                }
11847            }
11848        }
11849    }
11850
11851    /// Remove any highlighted row ranges of the given type that intersect the
11852    /// given ranges.
11853    pub fn remove_highlighted_rows<T: 'static>(
11854        &mut self,
11855        ranges_to_remove: Vec<Range<Anchor>>,
11856        cx: &mut ViewContext<Self>,
11857    ) {
11858        let snapshot = self.buffer().read(cx).snapshot(cx);
11859        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11860        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11861        row_highlights.retain(|highlight| {
11862            while let Some(range_to_remove) = ranges_to_remove.peek() {
11863                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11864                    Ordering::Less | Ordering::Equal => {
11865                        ranges_to_remove.next();
11866                    }
11867                    Ordering::Greater => {
11868                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11869                            Ordering::Less | Ordering::Equal => {
11870                                return false;
11871                            }
11872                            Ordering::Greater => break,
11873                        }
11874                    }
11875                }
11876            }
11877
11878            true
11879        })
11880    }
11881
11882    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11883    pub fn clear_row_highlights<T: 'static>(&mut self) {
11884        self.highlighted_rows.remove(&TypeId::of::<T>());
11885    }
11886
11887    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11888    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11889        self.highlighted_rows
11890            .get(&TypeId::of::<T>())
11891            .map_or(&[] as &[_], |vec| vec.as_slice())
11892            .iter()
11893            .map(|highlight| (highlight.range.clone(), highlight.color))
11894    }
11895
11896    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11897    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11898    /// Allows to ignore certain kinds of highlights.
11899    pub fn highlighted_display_rows(
11900        &mut self,
11901        cx: &mut WindowContext,
11902    ) -> BTreeMap<DisplayRow, Hsla> {
11903        let snapshot = self.snapshot(cx);
11904        let mut used_highlight_orders = HashMap::default();
11905        self.highlighted_rows
11906            .iter()
11907            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11908            .fold(
11909                BTreeMap::<DisplayRow, Hsla>::new(),
11910                |mut unique_rows, highlight| {
11911                    let start = highlight.range.start.to_display_point(&snapshot);
11912                    let end = highlight.range.end.to_display_point(&snapshot);
11913                    let start_row = start.row().0;
11914                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11915                        && end.column() == 0
11916                    {
11917                        end.row().0.saturating_sub(1)
11918                    } else {
11919                        end.row().0
11920                    };
11921                    for row in start_row..=end_row {
11922                        let used_index =
11923                            used_highlight_orders.entry(row).or_insert(highlight.index);
11924                        if highlight.index >= *used_index {
11925                            *used_index = highlight.index;
11926                            unique_rows.insert(DisplayRow(row), highlight.color);
11927                        }
11928                    }
11929                    unique_rows
11930                },
11931            )
11932    }
11933
11934    pub fn highlighted_display_row_for_autoscroll(
11935        &self,
11936        snapshot: &DisplaySnapshot,
11937    ) -> Option<DisplayRow> {
11938        self.highlighted_rows
11939            .values()
11940            .flat_map(|highlighted_rows| highlighted_rows.iter())
11941            .filter_map(|highlight| {
11942                if highlight.should_autoscroll {
11943                    Some(highlight.range.start.to_display_point(snapshot).row())
11944                } else {
11945                    None
11946                }
11947            })
11948            .min()
11949    }
11950
11951    pub fn set_search_within_ranges(
11952        &mut self,
11953        ranges: &[Range<Anchor>],
11954        cx: &mut ViewContext<Self>,
11955    ) {
11956        self.highlight_background::<SearchWithinRange>(
11957            ranges,
11958            |colors| colors.editor_document_highlight_read_background,
11959            cx,
11960        )
11961    }
11962
11963    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11964        self.breadcrumb_header = Some(new_header);
11965    }
11966
11967    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11968        self.clear_background_highlights::<SearchWithinRange>(cx);
11969    }
11970
11971    pub fn highlight_background<T: 'static>(
11972        &mut self,
11973        ranges: &[Range<Anchor>],
11974        color_fetcher: fn(&ThemeColors) -> Hsla,
11975        cx: &mut ViewContext<Self>,
11976    ) {
11977        self.background_highlights
11978            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11979        self.scrollbar_marker_state.dirty = true;
11980        cx.notify();
11981    }
11982
11983    pub fn clear_background_highlights<T: 'static>(
11984        &mut self,
11985        cx: &mut ViewContext<Self>,
11986    ) -> Option<BackgroundHighlight> {
11987        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11988        if !text_highlights.1.is_empty() {
11989            self.scrollbar_marker_state.dirty = true;
11990            cx.notify();
11991        }
11992        Some(text_highlights)
11993    }
11994
11995    pub fn highlight_gutter<T: 'static>(
11996        &mut self,
11997        ranges: &[Range<Anchor>],
11998        color_fetcher: fn(&AppContext) -> Hsla,
11999        cx: &mut ViewContext<Self>,
12000    ) {
12001        self.gutter_highlights
12002            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12003        cx.notify();
12004    }
12005
12006    pub fn clear_gutter_highlights<T: 'static>(
12007        &mut self,
12008        cx: &mut ViewContext<Self>,
12009    ) -> Option<GutterHighlight> {
12010        cx.notify();
12011        self.gutter_highlights.remove(&TypeId::of::<T>())
12012    }
12013
12014    #[cfg(feature = "test-support")]
12015    pub fn all_text_background_highlights(
12016        &mut self,
12017        cx: &mut ViewContext<Self>,
12018    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12019        let snapshot = self.snapshot(cx);
12020        let buffer = &snapshot.buffer_snapshot;
12021        let start = buffer.anchor_before(0);
12022        let end = buffer.anchor_after(buffer.len());
12023        let theme = cx.theme().colors();
12024        self.background_highlights_in_range(start..end, &snapshot, theme)
12025    }
12026
12027    #[cfg(feature = "test-support")]
12028    pub fn search_background_highlights(
12029        &mut self,
12030        cx: &mut ViewContext<Self>,
12031    ) -> Vec<Range<Point>> {
12032        let snapshot = self.buffer().read(cx).snapshot(cx);
12033
12034        let highlights = self
12035            .background_highlights
12036            .get(&TypeId::of::<items::BufferSearchHighlights>());
12037
12038        if let Some((_color, ranges)) = highlights {
12039            ranges
12040                .iter()
12041                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12042                .collect_vec()
12043        } else {
12044            vec![]
12045        }
12046    }
12047
12048    fn document_highlights_for_position<'a>(
12049        &'a self,
12050        position: Anchor,
12051        buffer: &'a MultiBufferSnapshot,
12052    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12053        let read_highlights = self
12054            .background_highlights
12055            .get(&TypeId::of::<DocumentHighlightRead>())
12056            .map(|h| &h.1);
12057        let write_highlights = self
12058            .background_highlights
12059            .get(&TypeId::of::<DocumentHighlightWrite>())
12060            .map(|h| &h.1);
12061        let left_position = position.bias_left(buffer);
12062        let right_position = position.bias_right(buffer);
12063        read_highlights
12064            .into_iter()
12065            .chain(write_highlights)
12066            .flat_map(move |ranges| {
12067                let start_ix = match ranges.binary_search_by(|probe| {
12068                    let cmp = probe.end.cmp(&left_position, buffer);
12069                    if cmp.is_ge() {
12070                        Ordering::Greater
12071                    } else {
12072                        Ordering::Less
12073                    }
12074                }) {
12075                    Ok(i) | Err(i) => i,
12076                };
12077
12078                ranges[start_ix..]
12079                    .iter()
12080                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12081            })
12082    }
12083
12084    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12085        self.background_highlights
12086            .get(&TypeId::of::<T>())
12087            .map_or(false, |(_, highlights)| !highlights.is_empty())
12088    }
12089
12090    pub fn background_highlights_in_range(
12091        &self,
12092        search_range: Range<Anchor>,
12093        display_snapshot: &DisplaySnapshot,
12094        theme: &ThemeColors,
12095    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12096        let mut results = Vec::new();
12097        for (color_fetcher, ranges) in self.background_highlights.values() {
12098            let color = color_fetcher(theme);
12099            let start_ix = match ranges.binary_search_by(|probe| {
12100                let cmp = probe
12101                    .end
12102                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12103                if cmp.is_gt() {
12104                    Ordering::Greater
12105                } else {
12106                    Ordering::Less
12107                }
12108            }) {
12109                Ok(i) | Err(i) => i,
12110            };
12111            for range in &ranges[start_ix..] {
12112                if range
12113                    .start
12114                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12115                    .is_ge()
12116                {
12117                    break;
12118                }
12119
12120                let start = range.start.to_display_point(display_snapshot);
12121                let end = range.end.to_display_point(display_snapshot);
12122                results.push((start..end, color))
12123            }
12124        }
12125        results
12126    }
12127
12128    pub fn background_highlight_row_ranges<T: 'static>(
12129        &self,
12130        search_range: Range<Anchor>,
12131        display_snapshot: &DisplaySnapshot,
12132        count: usize,
12133    ) -> Vec<RangeInclusive<DisplayPoint>> {
12134        let mut results = Vec::new();
12135        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12136            return vec![];
12137        };
12138
12139        let start_ix = match ranges.binary_search_by(|probe| {
12140            let cmp = probe
12141                .end
12142                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12143            if cmp.is_gt() {
12144                Ordering::Greater
12145            } else {
12146                Ordering::Less
12147            }
12148        }) {
12149            Ok(i) | Err(i) => i,
12150        };
12151        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12152            if let (Some(start_display), Some(end_display)) = (start, end) {
12153                results.push(
12154                    start_display.to_display_point(display_snapshot)
12155                        ..=end_display.to_display_point(display_snapshot),
12156                );
12157            }
12158        };
12159        let mut start_row: Option<Point> = None;
12160        let mut end_row: Option<Point> = None;
12161        if ranges.len() > count {
12162            return Vec::new();
12163        }
12164        for range in &ranges[start_ix..] {
12165            if range
12166                .start
12167                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12168                .is_ge()
12169            {
12170                break;
12171            }
12172            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12173            if let Some(current_row) = &end_row {
12174                if end.row == current_row.row {
12175                    continue;
12176                }
12177            }
12178            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12179            if start_row.is_none() {
12180                assert_eq!(end_row, None);
12181                start_row = Some(start);
12182                end_row = Some(end);
12183                continue;
12184            }
12185            if let Some(current_end) = end_row.as_mut() {
12186                if start.row > current_end.row + 1 {
12187                    push_region(start_row, end_row);
12188                    start_row = Some(start);
12189                    end_row = Some(end);
12190                } else {
12191                    // Merge two hunks.
12192                    *current_end = end;
12193                }
12194            } else {
12195                unreachable!();
12196            }
12197        }
12198        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12199        push_region(start_row, end_row);
12200        results
12201    }
12202
12203    pub fn gutter_highlights_in_range(
12204        &self,
12205        search_range: Range<Anchor>,
12206        display_snapshot: &DisplaySnapshot,
12207        cx: &AppContext,
12208    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12209        let mut results = Vec::new();
12210        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12211            let color = color_fetcher(cx);
12212            let start_ix = match ranges.binary_search_by(|probe| {
12213                let cmp = probe
12214                    .end
12215                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12216                if cmp.is_gt() {
12217                    Ordering::Greater
12218                } else {
12219                    Ordering::Less
12220                }
12221            }) {
12222                Ok(i) | Err(i) => i,
12223            };
12224            for range in &ranges[start_ix..] {
12225                if range
12226                    .start
12227                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12228                    .is_ge()
12229                {
12230                    break;
12231                }
12232
12233                let start = range.start.to_display_point(display_snapshot);
12234                let end = range.end.to_display_point(display_snapshot);
12235                results.push((start..end, color))
12236            }
12237        }
12238        results
12239    }
12240
12241    /// Get the text ranges corresponding to the redaction query
12242    pub fn redacted_ranges(
12243        &self,
12244        search_range: Range<Anchor>,
12245        display_snapshot: &DisplaySnapshot,
12246        cx: &WindowContext,
12247    ) -> Vec<Range<DisplayPoint>> {
12248        display_snapshot
12249            .buffer_snapshot
12250            .redacted_ranges(search_range, |file| {
12251                if let Some(file) = file {
12252                    file.is_private()
12253                        && EditorSettings::get(
12254                            Some(SettingsLocation {
12255                                worktree_id: file.worktree_id(cx),
12256                                path: file.path().as_ref(),
12257                            }),
12258                            cx,
12259                        )
12260                        .redact_private_values
12261                } else {
12262                    false
12263                }
12264            })
12265            .map(|range| {
12266                range.start.to_display_point(display_snapshot)
12267                    ..range.end.to_display_point(display_snapshot)
12268            })
12269            .collect()
12270    }
12271
12272    pub fn highlight_text<T: 'static>(
12273        &mut self,
12274        ranges: Vec<Range<Anchor>>,
12275        style: HighlightStyle,
12276        cx: &mut ViewContext<Self>,
12277    ) {
12278        self.display_map.update(cx, |map, _| {
12279            map.highlight_text(TypeId::of::<T>(), ranges, style)
12280        });
12281        cx.notify();
12282    }
12283
12284    pub(crate) fn highlight_inlays<T: 'static>(
12285        &mut self,
12286        highlights: Vec<InlayHighlight>,
12287        style: HighlightStyle,
12288        cx: &mut ViewContext<Self>,
12289    ) {
12290        self.display_map.update(cx, |map, _| {
12291            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12292        });
12293        cx.notify();
12294    }
12295
12296    pub fn text_highlights<'a, T: 'static>(
12297        &'a self,
12298        cx: &'a AppContext,
12299    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12300        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12301    }
12302
12303    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12304        let cleared = self
12305            .display_map
12306            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12307        if cleared {
12308            cx.notify();
12309        }
12310    }
12311
12312    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12313        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12314            && self.focus_handle.is_focused(cx)
12315    }
12316
12317    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12318        self.show_cursor_when_unfocused = is_enabled;
12319        cx.notify();
12320    }
12321
12322    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12323        cx.notify();
12324    }
12325
12326    fn on_buffer_event(
12327        &mut self,
12328        multibuffer: Model<MultiBuffer>,
12329        event: &multi_buffer::Event,
12330        cx: &mut ViewContext<Self>,
12331    ) {
12332        match event {
12333            multi_buffer::Event::Edited {
12334                singleton_buffer_edited,
12335            } => {
12336                self.scrollbar_marker_state.dirty = true;
12337                self.active_indent_guides_state.dirty = true;
12338                self.refresh_active_diagnostics(cx);
12339                self.refresh_code_actions(cx);
12340                if self.has_active_inline_completion(cx) {
12341                    self.update_visible_inline_completion(cx);
12342                }
12343                cx.emit(EditorEvent::BufferEdited);
12344                cx.emit(SearchEvent::MatchesInvalidated);
12345                if *singleton_buffer_edited {
12346                    if let Some(project) = &self.project {
12347                        let project = project.read(cx);
12348                        #[allow(clippy::mutable_key_type)]
12349                        let languages_affected = multibuffer
12350                            .read(cx)
12351                            .all_buffers()
12352                            .into_iter()
12353                            .filter_map(|buffer| {
12354                                let buffer = buffer.read(cx);
12355                                let language = buffer.language()?;
12356                                if project.is_local()
12357                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12358                                {
12359                                    None
12360                                } else {
12361                                    Some(language)
12362                                }
12363                            })
12364                            .cloned()
12365                            .collect::<HashSet<_>>();
12366                        if !languages_affected.is_empty() {
12367                            self.refresh_inlay_hints(
12368                                InlayHintRefreshReason::BufferEdited(languages_affected),
12369                                cx,
12370                            );
12371                        }
12372                    }
12373                }
12374
12375                let Some(project) = &self.project else { return };
12376                let (telemetry, is_via_ssh) = {
12377                    let project = project.read(cx);
12378                    let telemetry = project.client().telemetry().clone();
12379                    let is_via_ssh = project.is_via_ssh();
12380                    (telemetry, is_via_ssh)
12381                };
12382                refresh_linked_ranges(self, cx);
12383                telemetry.log_edit_event("editor", is_via_ssh);
12384            }
12385            multi_buffer::Event::ExcerptsAdded {
12386                buffer,
12387                predecessor,
12388                excerpts,
12389            } => {
12390                self.tasks_update_task = Some(self.refresh_runnables(cx));
12391                cx.emit(EditorEvent::ExcerptsAdded {
12392                    buffer: buffer.clone(),
12393                    predecessor: *predecessor,
12394                    excerpts: excerpts.clone(),
12395                });
12396                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12397            }
12398            multi_buffer::Event::ExcerptsRemoved { ids } => {
12399                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12400                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12401            }
12402            multi_buffer::Event::ExcerptsEdited { ids } => {
12403                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12404            }
12405            multi_buffer::Event::ExcerptsExpanded { ids } => {
12406                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12407            }
12408            multi_buffer::Event::Reparsed(buffer_id) => {
12409                self.tasks_update_task = Some(self.refresh_runnables(cx));
12410
12411                cx.emit(EditorEvent::Reparsed(*buffer_id));
12412            }
12413            multi_buffer::Event::LanguageChanged(buffer_id) => {
12414                linked_editing_ranges::refresh_linked_ranges(self, cx);
12415                cx.emit(EditorEvent::Reparsed(*buffer_id));
12416                cx.notify();
12417            }
12418            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12419            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12420            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12421                cx.emit(EditorEvent::TitleChanged)
12422            }
12423            multi_buffer::Event::DiffBaseChanged => {
12424                self.scrollbar_marker_state.dirty = true;
12425                cx.emit(EditorEvent::DiffBaseChanged);
12426                cx.notify();
12427            }
12428            multi_buffer::Event::DiffUpdated { buffer } => {
12429                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12430                cx.notify();
12431            }
12432            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12433            multi_buffer::Event::DiagnosticsUpdated => {
12434                self.refresh_active_diagnostics(cx);
12435                self.scrollbar_marker_state.dirty = true;
12436                cx.notify();
12437            }
12438            _ => {}
12439        };
12440    }
12441
12442    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12443        cx.notify();
12444    }
12445
12446    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12447        self.tasks_update_task = Some(self.refresh_runnables(cx));
12448        self.refresh_inline_completion(true, false, cx);
12449        self.refresh_inlay_hints(
12450            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12451                self.selections.newest_anchor().head(),
12452                &self.buffer.read(cx).snapshot(cx),
12453                cx,
12454            )),
12455            cx,
12456        );
12457
12458        let old_cursor_shape = self.cursor_shape;
12459
12460        {
12461            let editor_settings = EditorSettings::get_global(cx);
12462            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12463            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12464            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12465        }
12466
12467        if old_cursor_shape != self.cursor_shape {
12468            cx.emit(EditorEvent::CursorShapeChanged);
12469        }
12470
12471        let project_settings = ProjectSettings::get_global(cx);
12472        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12473
12474        if self.mode == EditorMode::Full {
12475            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12476            if self.git_blame_inline_enabled != inline_blame_enabled {
12477                self.toggle_git_blame_inline_internal(false, cx);
12478            }
12479        }
12480
12481        cx.notify();
12482    }
12483
12484    pub fn set_searchable(&mut self, searchable: bool) {
12485        self.searchable = searchable;
12486    }
12487
12488    pub fn searchable(&self) -> bool {
12489        self.searchable
12490    }
12491
12492    fn open_proposed_changes_editor(
12493        &mut self,
12494        _: &OpenProposedChangesEditor,
12495        cx: &mut ViewContext<Self>,
12496    ) {
12497        let Some(workspace) = self.workspace() else {
12498            cx.propagate();
12499            return;
12500        };
12501
12502        let selections = self.selections.all::<usize>(cx);
12503        let buffer = self.buffer.read(cx);
12504        let mut new_selections_by_buffer = HashMap::default();
12505        for selection in selections {
12506            for (buffer, range, _) in
12507                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12508            {
12509                let mut range = range.to_point(buffer.read(cx));
12510                range.start.column = 0;
12511                range.end.column = buffer.read(cx).line_len(range.end.row);
12512                new_selections_by_buffer
12513                    .entry(buffer)
12514                    .or_insert(Vec::new())
12515                    .push(range)
12516            }
12517        }
12518
12519        let proposed_changes_buffers = new_selections_by_buffer
12520            .into_iter()
12521            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12522            .collect::<Vec<_>>();
12523        let proposed_changes_editor = cx.new_view(|cx| {
12524            ProposedChangesEditor::new(
12525                "Proposed changes",
12526                proposed_changes_buffers,
12527                self.project.clone(),
12528                cx,
12529            )
12530        });
12531
12532        cx.window_context().defer(move |cx| {
12533            workspace.update(cx, |workspace, cx| {
12534                workspace.active_pane().update(cx, |pane, cx| {
12535                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12536                });
12537            });
12538        });
12539    }
12540
12541    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12542        self.open_excerpts_common(true, cx)
12543    }
12544
12545    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12546        self.open_excerpts_common(false, cx)
12547    }
12548
12549    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12550        let selections = self.selections.all::<usize>(cx);
12551        let buffer = self.buffer.read(cx);
12552        if buffer.is_singleton() {
12553            cx.propagate();
12554            return;
12555        }
12556
12557        let Some(workspace) = self.workspace() else {
12558            cx.propagate();
12559            return;
12560        };
12561
12562        let mut new_selections_by_buffer = HashMap::default();
12563        for selection in selections {
12564            for (mut buffer_handle, mut range, _) in
12565                buffer.range_to_buffer_ranges(selection.range(), cx)
12566            {
12567                // When editing branch buffers, jump to the corresponding location
12568                // in their base buffer.
12569                let buffer = buffer_handle.read(cx);
12570                if let Some(base_buffer) = buffer.diff_base_buffer() {
12571                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12572                    buffer_handle = base_buffer;
12573                }
12574
12575                if selection.reversed {
12576                    mem::swap(&mut range.start, &mut range.end);
12577                }
12578                new_selections_by_buffer
12579                    .entry(buffer_handle)
12580                    .or_insert(Vec::new())
12581                    .push(range)
12582            }
12583        }
12584
12585        // We defer the pane interaction because we ourselves are a workspace item
12586        // and activating a new item causes the pane to call a method on us reentrantly,
12587        // which panics if we're on the stack.
12588        cx.window_context().defer(move |cx| {
12589            workspace.update(cx, |workspace, cx| {
12590                let pane = if split {
12591                    workspace.adjacent_pane(cx)
12592                } else {
12593                    workspace.active_pane().clone()
12594                };
12595
12596                for (buffer, ranges) in new_selections_by_buffer {
12597                    let editor =
12598                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12599                    editor.update(cx, |editor, cx| {
12600                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12601                            s.select_ranges(ranges);
12602                        });
12603                    });
12604                }
12605            })
12606        });
12607    }
12608
12609    fn jump(
12610        &mut self,
12611        path: ProjectPath,
12612        position: Point,
12613        anchor: language::Anchor,
12614        offset_from_top: u32,
12615        cx: &mut ViewContext<Self>,
12616    ) {
12617        let workspace = self.workspace();
12618        cx.spawn(|_, mut cx| async move {
12619            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12620            let editor = workspace.update(&mut cx, |workspace, cx| {
12621                // Reset the preview item id before opening the new item
12622                workspace.active_pane().update(cx, |pane, cx| {
12623                    pane.set_preview_item_id(None, cx);
12624                });
12625                workspace.open_path_preview(path, None, true, true, cx)
12626            })?;
12627            let editor = editor
12628                .await?
12629                .downcast::<Editor>()
12630                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12631                .downgrade();
12632            editor.update(&mut cx, |editor, cx| {
12633                let buffer = editor
12634                    .buffer()
12635                    .read(cx)
12636                    .as_singleton()
12637                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12638                let buffer = buffer.read(cx);
12639                let cursor = if buffer.can_resolve(&anchor) {
12640                    language::ToPoint::to_point(&anchor, buffer)
12641                } else {
12642                    buffer.clip_point(position, Bias::Left)
12643                };
12644
12645                let nav_history = editor.nav_history.take();
12646                editor.change_selections(
12647                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12648                    cx,
12649                    |s| {
12650                        s.select_ranges([cursor..cursor]);
12651                    },
12652                );
12653                editor.nav_history = nav_history;
12654
12655                anyhow::Ok(())
12656            })??;
12657
12658            anyhow::Ok(())
12659        })
12660        .detach_and_log_err(cx);
12661    }
12662
12663    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12664        let snapshot = self.buffer.read(cx).read(cx);
12665        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12666        Some(
12667            ranges
12668                .iter()
12669                .map(move |range| {
12670                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12671                })
12672                .collect(),
12673        )
12674    }
12675
12676    fn selection_replacement_ranges(
12677        &self,
12678        range: Range<OffsetUtf16>,
12679        cx: &mut AppContext,
12680    ) -> Vec<Range<OffsetUtf16>> {
12681        let selections = self.selections.all::<OffsetUtf16>(cx);
12682        let newest_selection = selections
12683            .iter()
12684            .max_by_key(|selection| selection.id)
12685            .unwrap();
12686        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12687        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12688        let snapshot = self.buffer.read(cx).read(cx);
12689        selections
12690            .into_iter()
12691            .map(|mut selection| {
12692                selection.start.0 =
12693                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12694                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12695                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12696                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12697            })
12698            .collect()
12699    }
12700
12701    fn report_editor_event(
12702        &self,
12703        operation: &'static str,
12704        file_extension: Option<String>,
12705        cx: &AppContext,
12706    ) {
12707        if cfg!(any(test, feature = "test-support")) {
12708            return;
12709        }
12710
12711        let Some(project) = &self.project else { return };
12712
12713        // If None, we are in a file without an extension
12714        let file = self
12715            .buffer
12716            .read(cx)
12717            .as_singleton()
12718            .and_then(|b| b.read(cx).file());
12719        let file_extension = file_extension.or(file
12720            .as_ref()
12721            .and_then(|file| Path::new(file.file_name(cx)).extension())
12722            .and_then(|e| e.to_str())
12723            .map(|a| a.to_string()));
12724
12725        let vim_mode = cx
12726            .global::<SettingsStore>()
12727            .raw_user_settings()
12728            .get("vim_mode")
12729            == Some(&serde_json::Value::Bool(true));
12730
12731        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12732            == language::language_settings::InlineCompletionProvider::Copilot;
12733        let copilot_enabled_for_language = self
12734            .buffer
12735            .read(cx)
12736            .settings_at(0, cx)
12737            .show_inline_completions;
12738
12739        let project = project.read(cx);
12740        let telemetry = project.client().telemetry().clone();
12741        telemetry.report_editor_event(
12742            file_extension,
12743            vim_mode,
12744            operation,
12745            copilot_enabled,
12746            copilot_enabled_for_language,
12747            project.is_via_ssh(),
12748        )
12749    }
12750
12751    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12752    /// with each line being an array of {text, highlight} objects.
12753    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12754        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12755            return;
12756        };
12757
12758        #[derive(Serialize)]
12759        struct Chunk<'a> {
12760            text: String,
12761            highlight: Option<&'a str>,
12762        }
12763
12764        let snapshot = buffer.read(cx).snapshot();
12765        let range = self
12766            .selected_text_range(false, cx)
12767            .and_then(|selection| {
12768                if selection.range.is_empty() {
12769                    None
12770                } else {
12771                    Some(selection.range)
12772                }
12773            })
12774            .unwrap_or_else(|| 0..snapshot.len());
12775
12776        let chunks = snapshot.chunks(range, true);
12777        let mut lines = Vec::new();
12778        let mut line: VecDeque<Chunk> = VecDeque::new();
12779
12780        let Some(style) = self.style.as_ref() else {
12781            return;
12782        };
12783
12784        for chunk in chunks {
12785            let highlight = chunk
12786                .syntax_highlight_id
12787                .and_then(|id| id.name(&style.syntax));
12788            let mut chunk_lines = chunk.text.split('\n').peekable();
12789            while let Some(text) = chunk_lines.next() {
12790                let mut merged_with_last_token = false;
12791                if let Some(last_token) = line.back_mut() {
12792                    if last_token.highlight == highlight {
12793                        last_token.text.push_str(text);
12794                        merged_with_last_token = true;
12795                    }
12796                }
12797
12798                if !merged_with_last_token {
12799                    line.push_back(Chunk {
12800                        text: text.into(),
12801                        highlight,
12802                    });
12803                }
12804
12805                if chunk_lines.peek().is_some() {
12806                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12807                        line.pop_front();
12808                    }
12809                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12810                        line.pop_back();
12811                    }
12812
12813                    lines.push(mem::take(&mut line));
12814                }
12815            }
12816        }
12817
12818        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12819            return;
12820        };
12821        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12822    }
12823
12824    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12825        &self.inlay_hint_cache
12826    }
12827
12828    pub fn replay_insert_event(
12829        &mut self,
12830        text: &str,
12831        relative_utf16_range: Option<Range<isize>>,
12832        cx: &mut ViewContext<Self>,
12833    ) {
12834        if !self.input_enabled {
12835            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12836            return;
12837        }
12838        if let Some(relative_utf16_range) = relative_utf16_range {
12839            let selections = self.selections.all::<OffsetUtf16>(cx);
12840            self.change_selections(None, cx, |s| {
12841                let new_ranges = selections.into_iter().map(|range| {
12842                    let start = OffsetUtf16(
12843                        range
12844                            .head()
12845                            .0
12846                            .saturating_add_signed(relative_utf16_range.start),
12847                    );
12848                    let end = OffsetUtf16(
12849                        range
12850                            .head()
12851                            .0
12852                            .saturating_add_signed(relative_utf16_range.end),
12853                    );
12854                    start..end
12855                });
12856                s.select_ranges(new_ranges);
12857            });
12858        }
12859
12860        self.handle_input(text, cx);
12861    }
12862
12863    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12864        let Some(provider) = self.semantics_provider.as_ref() else {
12865            return false;
12866        };
12867
12868        let mut supports = false;
12869        self.buffer().read(cx).for_each_buffer(|buffer| {
12870            supports |= provider.supports_inlay_hints(buffer, cx);
12871        });
12872        supports
12873    }
12874
12875    pub fn focus(&self, cx: &mut WindowContext) {
12876        cx.focus(&self.focus_handle)
12877    }
12878
12879    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12880        self.focus_handle.is_focused(cx)
12881    }
12882
12883    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12884        cx.emit(EditorEvent::Focused);
12885
12886        if let Some(descendant) = self
12887            .last_focused_descendant
12888            .take()
12889            .and_then(|descendant| descendant.upgrade())
12890        {
12891            cx.focus(&descendant);
12892        } else {
12893            if let Some(blame) = self.blame.as_ref() {
12894                blame.update(cx, GitBlame::focus)
12895            }
12896
12897            self.blink_manager.update(cx, BlinkManager::enable);
12898            self.show_cursor_names(cx);
12899            self.buffer.update(cx, |buffer, cx| {
12900                buffer.finalize_last_transaction(cx);
12901                if self.leader_peer_id.is_none() {
12902                    buffer.set_active_selections(
12903                        &self.selections.disjoint_anchors(),
12904                        self.selections.line_mode,
12905                        self.cursor_shape,
12906                        cx,
12907                    );
12908                }
12909            });
12910        }
12911    }
12912
12913    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12914        cx.emit(EditorEvent::FocusedIn)
12915    }
12916
12917    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12918        if event.blurred != self.focus_handle {
12919            self.last_focused_descendant = Some(event.blurred);
12920        }
12921    }
12922
12923    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12924        self.blink_manager.update(cx, BlinkManager::disable);
12925        self.buffer
12926            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12927
12928        if let Some(blame) = self.blame.as_ref() {
12929            blame.update(cx, GitBlame::blur)
12930        }
12931        if !self.hover_state.focused(cx) {
12932            hide_hover(self, cx);
12933        }
12934
12935        self.hide_context_menu(cx);
12936        cx.emit(EditorEvent::Blurred);
12937        cx.notify();
12938    }
12939
12940    pub fn register_action<A: Action>(
12941        &mut self,
12942        listener: impl Fn(&A, &mut WindowContext) + 'static,
12943    ) -> Subscription {
12944        let id = self.next_editor_action_id.post_inc();
12945        let listener = Arc::new(listener);
12946        self.editor_actions.borrow_mut().insert(
12947            id,
12948            Box::new(move |cx| {
12949                let cx = cx.window_context();
12950                let listener = listener.clone();
12951                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12952                    let action = action.downcast_ref().unwrap();
12953                    if phase == DispatchPhase::Bubble {
12954                        listener(action, cx)
12955                    }
12956                })
12957            }),
12958        );
12959
12960        let editor_actions = self.editor_actions.clone();
12961        Subscription::new(move || {
12962            editor_actions.borrow_mut().remove(&id);
12963        })
12964    }
12965
12966    pub fn file_header_size(&self) -> u32 {
12967        FILE_HEADER_HEIGHT
12968    }
12969
12970    pub fn revert(
12971        &mut self,
12972        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12973        cx: &mut ViewContext<Self>,
12974    ) {
12975        self.buffer().update(cx, |multi_buffer, cx| {
12976            for (buffer_id, changes) in revert_changes {
12977                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12978                    buffer.update(cx, |buffer, cx| {
12979                        buffer.edit(
12980                            changes.into_iter().map(|(range, text)| {
12981                                (range, text.to_string().map(Arc::<str>::from))
12982                            }),
12983                            None,
12984                            cx,
12985                        );
12986                    });
12987                }
12988            }
12989        });
12990        self.change_selections(None, cx, |selections| selections.refresh());
12991    }
12992
12993    pub fn to_pixel_point(
12994        &mut self,
12995        source: multi_buffer::Anchor,
12996        editor_snapshot: &EditorSnapshot,
12997        cx: &mut ViewContext<Self>,
12998    ) -> Option<gpui::Point<Pixels>> {
12999        let source_point = source.to_display_point(editor_snapshot);
13000        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13001    }
13002
13003    pub fn display_to_pixel_point(
13004        &mut self,
13005        source: DisplayPoint,
13006        editor_snapshot: &EditorSnapshot,
13007        cx: &mut ViewContext<Self>,
13008    ) -> Option<gpui::Point<Pixels>> {
13009        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13010        let text_layout_details = self.text_layout_details(cx);
13011        let scroll_top = text_layout_details
13012            .scroll_anchor
13013            .scroll_position(editor_snapshot)
13014            .y;
13015
13016        if source.row().as_f32() < scroll_top.floor() {
13017            return None;
13018        }
13019        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13020        let source_y = line_height * (source.row().as_f32() - scroll_top);
13021        Some(gpui::Point::new(source_x, source_y))
13022    }
13023
13024    pub fn has_active_completions_menu(&self) -> bool {
13025        self.context_menu.read().as_ref().map_or(false, |menu| {
13026            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13027        })
13028    }
13029
13030    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13031        self.addons
13032            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13033    }
13034
13035    pub fn unregister_addon<T: Addon>(&mut self) {
13036        self.addons.remove(&std::any::TypeId::of::<T>());
13037    }
13038
13039    pub fn addon<T: Addon>(&self) -> Option<&T> {
13040        let type_id = std::any::TypeId::of::<T>();
13041        self.addons
13042            .get(&type_id)
13043            .and_then(|item| item.to_any().downcast_ref::<T>())
13044    }
13045}
13046
13047fn len_with_expanded_tabs(offset: usize, comment_prefix: &str, tab_size: NonZeroU32) -> usize {
13048    let tab_size = tab_size.get() as usize;
13049    let mut width = offset;
13050
13051    for c in comment_prefix.chars() {
13052        width += if c == '\t' {
13053            tab_size - (width % tab_size)
13054        } else {
13055            1
13056        };
13057    }
13058
13059    width - offset
13060}
13061
13062#[cfg(test)]
13063mod tests {
13064    use super::*;
13065
13066    #[test]
13067    fn test_string_size_with_expanded_tabs() {
13068        let nz = |val| NonZeroU32::new(val).unwrap();
13069        assert_eq!(len_with_expanded_tabs(0, "", nz(4)), 0);
13070        assert_eq!(len_with_expanded_tabs(0, "hello", nz(4)), 5);
13071        assert_eq!(len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13072        assert_eq!(len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13073        assert_eq!(len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13074        assert_eq!(len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13075        assert_eq!(len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13076        assert_eq!(len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13077    }
13078}
13079
13080fn wrap_with_prefix(
13081    line_prefix: String,
13082    unwrapped_text: String,
13083    wrap_column: usize,
13084    tab_size: NonZeroU32,
13085) -> String {
13086    let line_prefix_display_len = len_with_expanded_tabs(0, &line_prefix, tab_size);
13087    let mut wrapped_text = String::new();
13088    let mut current_line = line_prefix.to_string();
13089    let prefix_extra_chars = line_prefix_display_len - line_prefix.len();
13090
13091    for word in unwrapped_text.split_whitespace() {
13092        if current_line.len() + prefix_extra_chars + word.len() >= wrap_column {
13093            wrapped_text.push_str(&current_line);
13094            wrapped_text.push('\n');
13095            current_line.truncate(line_prefix.len());
13096        }
13097
13098        if current_line.len() > line_prefix.len() {
13099            current_line.push(' ');
13100        }
13101
13102        current_line.push_str(word);
13103    }
13104
13105    if !current_line.is_empty() {
13106        wrapped_text.push_str(&current_line);
13107    }
13108    wrapped_text
13109}
13110
13111fn hunks_for_selections(
13112    multi_buffer_snapshot: &MultiBufferSnapshot,
13113    selections: &[Selection<Anchor>],
13114) -> Vec<MultiBufferDiffHunk> {
13115    let buffer_rows_for_selections = selections.iter().map(|selection| {
13116        let head = selection.head();
13117        let tail = selection.tail();
13118        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13119        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13120        if start > end {
13121            end..start
13122        } else {
13123            start..end
13124        }
13125    });
13126
13127    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13128}
13129
13130pub fn hunks_for_rows(
13131    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13132    multi_buffer_snapshot: &MultiBufferSnapshot,
13133) -> Vec<MultiBufferDiffHunk> {
13134    let mut hunks = Vec::new();
13135    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13136        HashMap::default();
13137    for selected_multi_buffer_rows in rows {
13138        let query_rows =
13139            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13140        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13141            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13142            // when the caret is just above or just below the deleted hunk.
13143            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13144            let related_to_selection = if allow_adjacent {
13145                hunk.row_range.overlaps(&query_rows)
13146                    || hunk.row_range.start == query_rows.end
13147                    || hunk.row_range.end == query_rows.start
13148            } else {
13149                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13150                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13151                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13152                    || selected_multi_buffer_rows.end == hunk.row_range.start
13153            };
13154            if related_to_selection {
13155                if !processed_buffer_rows
13156                    .entry(hunk.buffer_id)
13157                    .or_default()
13158                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13159                {
13160                    continue;
13161                }
13162                hunks.push(hunk);
13163            }
13164        }
13165    }
13166
13167    hunks
13168}
13169
13170pub trait CollaborationHub {
13171    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13172    fn user_participant_indices<'a>(
13173        &self,
13174        cx: &'a AppContext,
13175    ) -> &'a HashMap<u64, ParticipantIndex>;
13176    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13177}
13178
13179impl CollaborationHub for Model<Project> {
13180    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13181        self.read(cx).collaborators()
13182    }
13183
13184    fn user_participant_indices<'a>(
13185        &self,
13186        cx: &'a AppContext,
13187    ) -> &'a HashMap<u64, ParticipantIndex> {
13188        self.read(cx).user_store().read(cx).participant_indices()
13189    }
13190
13191    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13192        let this = self.read(cx);
13193        let user_ids = this.collaborators().values().map(|c| c.user_id);
13194        this.user_store().read_with(cx, |user_store, cx| {
13195            user_store.participant_names(user_ids, cx)
13196        })
13197    }
13198}
13199
13200pub trait SemanticsProvider {
13201    fn hover(
13202        &self,
13203        buffer: &Model<Buffer>,
13204        position: text::Anchor,
13205        cx: &mut AppContext,
13206    ) -> Option<Task<Vec<project::Hover>>>;
13207
13208    fn inlay_hints(
13209        &self,
13210        buffer_handle: Model<Buffer>,
13211        range: Range<text::Anchor>,
13212        cx: &mut AppContext,
13213    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13214
13215    fn resolve_inlay_hint(
13216        &self,
13217        hint: InlayHint,
13218        buffer_handle: Model<Buffer>,
13219        server_id: LanguageServerId,
13220        cx: &mut AppContext,
13221    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13222
13223    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13224
13225    fn document_highlights(
13226        &self,
13227        buffer: &Model<Buffer>,
13228        position: text::Anchor,
13229        cx: &mut AppContext,
13230    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13231
13232    fn definitions(
13233        &self,
13234        buffer: &Model<Buffer>,
13235        position: text::Anchor,
13236        kind: GotoDefinitionKind,
13237        cx: &mut AppContext,
13238    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13239
13240    fn range_for_rename(
13241        &self,
13242        buffer: &Model<Buffer>,
13243        position: text::Anchor,
13244        cx: &mut AppContext,
13245    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13246
13247    fn perform_rename(
13248        &self,
13249        buffer: &Model<Buffer>,
13250        position: text::Anchor,
13251        new_name: String,
13252        cx: &mut AppContext,
13253    ) -> Option<Task<Result<ProjectTransaction>>>;
13254}
13255
13256pub trait CompletionProvider {
13257    fn completions(
13258        &self,
13259        buffer: &Model<Buffer>,
13260        buffer_position: text::Anchor,
13261        trigger: CompletionContext,
13262        cx: &mut ViewContext<Editor>,
13263    ) -> Task<Result<Vec<Completion>>>;
13264
13265    fn resolve_completions(
13266        &self,
13267        buffer: Model<Buffer>,
13268        completion_indices: Vec<usize>,
13269        completions: Arc<RwLock<Box<[Completion]>>>,
13270        cx: &mut ViewContext<Editor>,
13271    ) -> Task<Result<bool>>;
13272
13273    fn apply_additional_edits_for_completion(
13274        &self,
13275        buffer: Model<Buffer>,
13276        completion: Completion,
13277        push_to_history: bool,
13278        cx: &mut ViewContext<Editor>,
13279    ) -> Task<Result<Option<language::Transaction>>>;
13280
13281    fn is_completion_trigger(
13282        &self,
13283        buffer: &Model<Buffer>,
13284        position: language::Anchor,
13285        text: &str,
13286        trigger_in_words: bool,
13287        cx: &mut ViewContext<Editor>,
13288    ) -> bool;
13289
13290    fn sort_completions(&self) -> bool {
13291        true
13292    }
13293}
13294
13295pub trait CodeActionProvider {
13296    fn code_actions(
13297        &self,
13298        buffer: &Model<Buffer>,
13299        range: Range<text::Anchor>,
13300        cx: &mut WindowContext,
13301    ) -> Task<Result<Vec<CodeAction>>>;
13302
13303    fn apply_code_action(
13304        &self,
13305        buffer_handle: Model<Buffer>,
13306        action: CodeAction,
13307        excerpt_id: ExcerptId,
13308        push_to_history: bool,
13309        cx: &mut WindowContext,
13310    ) -> Task<Result<ProjectTransaction>>;
13311}
13312
13313impl CodeActionProvider for Model<Project> {
13314    fn code_actions(
13315        &self,
13316        buffer: &Model<Buffer>,
13317        range: Range<text::Anchor>,
13318        cx: &mut WindowContext,
13319    ) -> Task<Result<Vec<CodeAction>>> {
13320        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13321    }
13322
13323    fn apply_code_action(
13324        &self,
13325        buffer_handle: Model<Buffer>,
13326        action: CodeAction,
13327        _excerpt_id: ExcerptId,
13328        push_to_history: bool,
13329        cx: &mut WindowContext,
13330    ) -> Task<Result<ProjectTransaction>> {
13331        self.update(cx, |project, cx| {
13332            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13333        })
13334    }
13335}
13336
13337fn snippet_completions(
13338    project: &Project,
13339    buffer: &Model<Buffer>,
13340    buffer_position: text::Anchor,
13341    cx: &mut AppContext,
13342) -> Vec<Completion> {
13343    let language = buffer.read(cx).language_at(buffer_position);
13344    let language_name = language.as_ref().map(|language| language.lsp_id());
13345    let snippet_store = project.snippets().read(cx);
13346    let snippets = snippet_store.snippets_for(language_name, cx);
13347
13348    if snippets.is_empty() {
13349        return vec![];
13350    }
13351    let snapshot = buffer.read(cx).text_snapshot();
13352    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13353
13354    let scope = language.map(|language| language.default_scope());
13355    let classifier = CharClassifier::new(scope).for_completion(true);
13356    let mut last_word = chars
13357        .take_while(|c| classifier.is_word(*c))
13358        .collect::<String>();
13359    last_word = last_word.chars().rev().collect();
13360    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13361    let to_lsp = |point: &text::Anchor| {
13362        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13363        point_to_lsp(end)
13364    };
13365    let lsp_end = to_lsp(&buffer_position);
13366    snippets
13367        .into_iter()
13368        .filter_map(|snippet| {
13369            let matching_prefix = snippet
13370                .prefix
13371                .iter()
13372                .find(|prefix| prefix.starts_with(&last_word))?;
13373            let start = as_offset - last_word.len();
13374            let start = snapshot.anchor_before(start);
13375            let range = start..buffer_position;
13376            let lsp_start = to_lsp(&start);
13377            let lsp_range = lsp::Range {
13378                start: lsp_start,
13379                end: lsp_end,
13380            };
13381            Some(Completion {
13382                old_range: range,
13383                new_text: snippet.body.clone(),
13384                label: CodeLabel {
13385                    text: matching_prefix.clone(),
13386                    runs: vec![],
13387                    filter_range: 0..matching_prefix.len(),
13388                },
13389                server_id: LanguageServerId(usize::MAX),
13390                documentation: snippet.description.clone().map(Documentation::SingleLine),
13391                lsp_completion: lsp::CompletionItem {
13392                    label: snippet.prefix.first().unwrap().clone(),
13393                    kind: Some(CompletionItemKind::SNIPPET),
13394                    label_details: snippet.description.as_ref().map(|description| {
13395                        lsp::CompletionItemLabelDetails {
13396                            detail: Some(description.clone()),
13397                            description: None,
13398                        }
13399                    }),
13400                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13401                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13402                        lsp::InsertReplaceEdit {
13403                            new_text: snippet.body.clone(),
13404                            insert: lsp_range,
13405                            replace: lsp_range,
13406                        },
13407                    )),
13408                    filter_text: Some(snippet.body.clone()),
13409                    sort_text: Some(char::MAX.to_string()),
13410                    ..Default::default()
13411                },
13412                confirm: None,
13413            })
13414        })
13415        .collect()
13416}
13417
13418impl CompletionProvider for Model<Project> {
13419    fn completions(
13420        &self,
13421        buffer: &Model<Buffer>,
13422        buffer_position: text::Anchor,
13423        options: CompletionContext,
13424        cx: &mut ViewContext<Editor>,
13425    ) -> Task<Result<Vec<Completion>>> {
13426        self.update(cx, |project, cx| {
13427            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13428            let project_completions = project.completions(buffer, buffer_position, options, cx);
13429            cx.background_executor().spawn(async move {
13430                let mut completions = project_completions.await?;
13431                //let snippets = snippets.into_iter().;
13432                completions.extend(snippets);
13433                Ok(completions)
13434            })
13435        })
13436    }
13437
13438    fn resolve_completions(
13439        &self,
13440        buffer: Model<Buffer>,
13441        completion_indices: Vec<usize>,
13442        completions: Arc<RwLock<Box<[Completion]>>>,
13443        cx: &mut ViewContext<Editor>,
13444    ) -> Task<Result<bool>> {
13445        self.update(cx, |project, cx| {
13446            project.resolve_completions(buffer, completion_indices, completions, cx)
13447        })
13448    }
13449
13450    fn apply_additional_edits_for_completion(
13451        &self,
13452        buffer: Model<Buffer>,
13453        completion: Completion,
13454        push_to_history: bool,
13455        cx: &mut ViewContext<Editor>,
13456    ) -> Task<Result<Option<language::Transaction>>> {
13457        self.update(cx, |project, cx| {
13458            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13459        })
13460    }
13461
13462    fn is_completion_trigger(
13463        &self,
13464        buffer: &Model<Buffer>,
13465        position: language::Anchor,
13466        text: &str,
13467        trigger_in_words: bool,
13468        cx: &mut ViewContext<Editor>,
13469    ) -> bool {
13470        if !EditorSettings::get_global(cx).show_completions_on_input {
13471            return false;
13472        }
13473
13474        let mut chars = text.chars();
13475        let char = if let Some(char) = chars.next() {
13476            char
13477        } else {
13478            return false;
13479        };
13480        if chars.next().is_some() {
13481            return false;
13482        }
13483
13484        let buffer = buffer.read(cx);
13485        let classifier = buffer
13486            .snapshot()
13487            .char_classifier_at(position)
13488            .for_completion(true);
13489        if trigger_in_words && classifier.is_word(char) {
13490            return true;
13491        }
13492
13493        buffer
13494            .completion_triggers()
13495            .iter()
13496            .any(|string| string == text)
13497    }
13498}
13499
13500impl SemanticsProvider for Model<Project> {
13501    fn hover(
13502        &self,
13503        buffer: &Model<Buffer>,
13504        position: text::Anchor,
13505        cx: &mut AppContext,
13506    ) -> Option<Task<Vec<project::Hover>>> {
13507        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13508    }
13509
13510    fn document_highlights(
13511        &self,
13512        buffer: &Model<Buffer>,
13513        position: text::Anchor,
13514        cx: &mut AppContext,
13515    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13516        Some(self.update(cx, |project, cx| {
13517            project.document_highlights(buffer, position, cx)
13518        }))
13519    }
13520
13521    fn definitions(
13522        &self,
13523        buffer: &Model<Buffer>,
13524        position: text::Anchor,
13525        kind: GotoDefinitionKind,
13526        cx: &mut AppContext,
13527    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13528        Some(self.update(cx, |project, cx| match kind {
13529            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13530            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13531            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13532            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13533        }))
13534    }
13535
13536    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13537        // TODO: make this work for remote projects
13538        self.read(cx)
13539            .language_servers_for_buffer(buffer.read(cx), cx)
13540            .any(
13541                |(_, server)| match server.capabilities().inlay_hint_provider {
13542                    Some(lsp::OneOf::Left(enabled)) => enabled,
13543                    Some(lsp::OneOf::Right(_)) => true,
13544                    None => false,
13545                },
13546            )
13547    }
13548
13549    fn inlay_hints(
13550        &self,
13551        buffer_handle: Model<Buffer>,
13552        range: Range<text::Anchor>,
13553        cx: &mut AppContext,
13554    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13555        Some(self.update(cx, |project, cx| {
13556            project.inlay_hints(buffer_handle, range, cx)
13557        }))
13558    }
13559
13560    fn resolve_inlay_hint(
13561        &self,
13562        hint: InlayHint,
13563        buffer_handle: Model<Buffer>,
13564        server_id: LanguageServerId,
13565        cx: &mut AppContext,
13566    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13567        Some(self.update(cx, |project, cx| {
13568            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13569        }))
13570    }
13571
13572    fn range_for_rename(
13573        &self,
13574        buffer: &Model<Buffer>,
13575        position: text::Anchor,
13576        cx: &mut AppContext,
13577    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13578        Some(self.update(cx, |project, cx| {
13579            project.prepare_rename(buffer.clone(), position, cx)
13580        }))
13581    }
13582
13583    fn perform_rename(
13584        &self,
13585        buffer: &Model<Buffer>,
13586        position: text::Anchor,
13587        new_name: String,
13588        cx: &mut AppContext,
13589    ) -> Option<Task<Result<ProjectTransaction>>> {
13590        Some(self.update(cx, |project, cx| {
13591            project.perform_rename(buffer.clone(), position, new_name, cx)
13592        }))
13593    }
13594}
13595
13596fn inlay_hint_settings(
13597    location: Anchor,
13598    snapshot: &MultiBufferSnapshot,
13599    cx: &mut ViewContext<'_, Editor>,
13600) -> InlayHintSettings {
13601    let file = snapshot.file_at(location);
13602    let language = snapshot.language_at(location).map(|l| l.name());
13603    language_settings(language, file, cx).inlay_hints
13604}
13605
13606fn consume_contiguous_rows(
13607    contiguous_row_selections: &mut Vec<Selection<Point>>,
13608    selection: &Selection<Point>,
13609    display_map: &DisplaySnapshot,
13610    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13611) -> (MultiBufferRow, MultiBufferRow) {
13612    contiguous_row_selections.push(selection.clone());
13613    let start_row = MultiBufferRow(selection.start.row);
13614    let mut end_row = ending_row(selection, display_map);
13615
13616    while let Some(next_selection) = selections.peek() {
13617        if next_selection.start.row <= end_row.0 {
13618            end_row = ending_row(next_selection, display_map);
13619            contiguous_row_selections.push(selections.next().unwrap().clone());
13620        } else {
13621            break;
13622        }
13623    }
13624    (start_row, end_row)
13625}
13626
13627fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13628    if next_selection.end.column > 0 || next_selection.is_empty() {
13629        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13630    } else {
13631        MultiBufferRow(next_selection.end.row)
13632    }
13633}
13634
13635impl EditorSnapshot {
13636    pub fn remote_selections_in_range<'a>(
13637        &'a self,
13638        range: &'a Range<Anchor>,
13639        collaboration_hub: &dyn CollaborationHub,
13640        cx: &'a AppContext,
13641    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13642        let participant_names = collaboration_hub.user_names(cx);
13643        let participant_indices = collaboration_hub.user_participant_indices(cx);
13644        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13645        let collaborators_by_replica_id = collaborators_by_peer_id
13646            .iter()
13647            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13648            .collect::<HashMap<_, _>>();
13649        self.buffer_snapshot
13650            .selections_in_range(range, false)
13651            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13652                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13653                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13654                let user_name = participant_names.get(&collaborator.user_id).cloned();
13655                Some(RemoteSelection {
13656                    replica_id,
13657                    selection,
13658                    cursor_shape,
13659                    line_mode,
13660                    participant_index,
13661                    peer_id: collaborator.peer_id,
13662                    user_name,
13663                })
13664            })
13665    }
13666
13667    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13668        self.display_snapshot.buffer_snapshot.language_at(position)
13669    }
13670
13671    pub fn is_focused(&self) -> bool {
13672        self.is_focused
13673    }
13674
13675    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13676        self.placeholder_text.as_ref()
13677    }
13678
13679    pub fn scroll_position(&self) -> gpui::Point<f32> {
13680        self.scroll_anchor.scroll_position(&self.display_snapshot)
13681    }
13682
13683    fn gutter_dimensions(
13684        &self,
13685        font_id: FontId,
13686        font_size: Pixels,
13687        em_width: Pixels,
13688        em_advance: Pixels,
13689        max_line_number_width: Pixels,
13690        cx: &AppContext,
13691    ) -> GutterDimensions {
13692        if !self.show_gutter {
13693            return GutterDimensions::default();
13694        }
13695        let descent = cx.text_system().descent(font_id, font_size);
13696
13697        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13698            matches!(
13699                ProjectSettings::get_global(cx).git.git_gutter,
13700                Some(GitGutterSetting::TrackedFiles)
13701            )
13702        });
13703        let gutter_settings = EditorSettings::get_global(cx).gutter;
13704        let show_line_numbers = self
13705            .show_line_numbers
13706            .unwrap_or(gutter_settings.line_numbers);
13707        let line_gutter_width = if show_line_numbers {
13708            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13709            let min_width_for_number_on_gutter = em_advance * 4.0;
13710            max_line_number_width.max(min_width_for_number_on_gutter)
13711        } else {
13712            0.0.into()
13713        };
13714
13715        let show_code_actions = self
13716            .show_code_actions
13717            .unwrap_or(gutter_settings.code_actions);
13718
13719        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13720
13721        let git_blame_entries_width =
13722            self.git_blame_gutter_max_author_length
13723                .map(|max_author_length| {
13724                    // Length of the author name, but also space for the commit hash,
13725                    // the spacing and the timestamp.
13726                    let max_char_count = max_author_length
13727                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13728                        + 7 // length of commit sha
13729                        + 14 // length of max relative timestamp ("60 minutes ago")
13730                        + 4; // gaps and margins
13731
13732                    em_advance * max_char_count
13733                });
13734
13735        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13736        left_padding += if show_code_actions || show_runnables {
13737            em_width * 3.0
13738        } else if show_git_gutter && show_line_numbers {
13739            em_width * 2.0
13740        } else if show_git_gutter || show_line_numbers {
13741            em_width
13742        } else {
13743            px(0.)
13744        };
13745
13746        let right_padding = if gutter_settings.folds && show_line_numbers {
13747            em_width * 4.0
13748        } else if gutter_settings.folds {
13749            em_width * 3.0
13750        } else if show_line_numbers {
13751            em_width
13752        } else {
13753            px(0.)
13754        };
13755
13756        GutterDimensions {
13757            left_padding,
13758            right_padding,
13759            width: line_gutter_width + left_padding + right_padding,
13760            margin: -descent,
13761            git_blame_entries_width,
13762        }
13763    }
13764
13765    pub fn render_fold_toggle(
13766        &self,
13767        buffer_row: MultiBufferRow,
13768        row_contains_cursor: bool,
13769        editor: View<Editor>,
13770        cx: &mut WindowContext,
13771    ) -> Option<AnyElement> {
13772        let folded = self.is_line_folded(buffer_row);
13773
13774        if let Some(crease) = self
13775            .crease_snapshot
13776            .query_row(buffer_row, &self.buffer_snapshot)
13777        {
13778            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13779                if folded {
13780                    editor.update(cx, |editor, cx| {
13781                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13782                    });
13783                } else {
13784                    editor.update(cx, |editor, cx| {
13785                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13786                    });
13787                }
13788            });
13789
13790            Some((crease.render_toggle)(
13791                buffer_row,
13792                folded,
13793                toggle_callback,
13794                cx,
13795            ))
13796        } else if folded
13797            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13798        {
13799            Some(
13800                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13801                    .selected(folded)
13802                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13803                        if folded {
13804                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13805                        } else {
13806                            this.fold_at(&FoldAt { buffer_row }, cx);
13807                        }
13808                    }))
13809                    .into_any_element(),
13810            )
13811        } else {
13812            None
13813        }
13814    }
13815
13816    pub fn render_crease_trailer(
13817        &self,
13818        buffer_row: MultiBufferRow,
13819        cx: &mut WindowContext,
13820    ) -> Option<AnyElement> {
13821        let folded = self.is_line_folded(buffer_row);
13822        let crease = self
13823            .crease_snapshot
13824            .query_row(buffer_row, &self.buffer_snapshot)?;
13825        Some((crease.render_trailer)(buffer_row, folded, cx))
13826    }
13827}
13828
13829impl Deref for EditorSnapshot {
13830    type Target = DisplaySnapshot;
13831
13832    fn deref(&self) -> &Self::Target {
13833        &self.display_snapshot
13834    }
13835}
13836
13837#[derive(Clone, Debug, PartialEq, Eq)]
13838pub enum EditorEvent {
13839    InputIgnored {
13840        text: Arc<str>,
13841    },
13842    InputHandled {
13843        utf16_range_to_replace: Option<Range<isize>>,
13844        text: Arc<str>,
13845    },
13846    ExcerptsAdded {
13847        buffer: Model<Buffer>,
13848        predecessor: ExcerptId,
13849        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13850    },
13851    ExcerptsRemoved {
13852        ids: Vec<ExcerptId>,
13853    },
13854    ExcerptsEdited {
13855        ids: Vec<ExcerptId>,
13856    },
13857    ExcerptsExpanded {
13858        ids: Vec<ExcerptId>,
13859    },
13860    BufferEdited,
13861    Edited {
13862        transaction_id: clock::Lamport,
13863    },
13864    Reparsed(BufferId),
13865    Focused,
13866    FocusedIn,
13867    Blurred,
13868    DirtyChanged,
13869    Saved,
13870    TitleChanged,
13871    DiffBaseChanged,
13872    SelectionsChanged {
13873        local: bool,
13874    },
13875    ScrollPositionChanged {
13876        local: bool,
13877        autoscroll: bool,
13878    },
13879    Closed,
13880    TransactionUndone {
13881        transaction_id: clock::Lamport,
13882    },
13883    TransactionBegun {
13884        transaction_id: clock::Lamport,
13885    },
13886    Reloaded,
13887    CursorShapeChanged,
13888}
13889
13890impl EventEmitter<EditorEvent> for Editor {}
13891
13892impl FocusableView for Editor {
13893    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13894        self.focus_handle.clone()
13895    }
13896}
13897
13898impl Render for Editor {
13899    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13900        let settings = ThemeSettings::get_global(cx);
13901
13902        let mut text_style = match self.mode {
13903            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13904                color: cx.theme().colors().editor_foreground,
13905                font_family: settings.ui_font.family.clone(),
13906                font_features: settings.ui_font.features.clone(),
13907                font_fallbacks: settings.ui_font.fallbacks.clone(),
13908                font_size: rems(0.875).into(),
13909                font_weight: settings.ui_font.weight,
13910                line_height: relative(settings.buffer_line_height.value()),
13911                ..Default::default()
13912            },
13913            EditorMode::Full => TextStyle {
13914                color: cx.theme().colors().editor_foreground,
13915                font_family: settings.buffer_font.family.clone(),
13916                font_features: settings.buffer_font.features.clone(),
13917                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13918                font_size: settings.buffer_font_size(cx).into(),
13919                font_weight: settings.buffer_font.weight,
13920                line_height: relative(settings.buffer_line_height.value()),
13921                ..Default::default()
13922            },
13923        };
13924        if let Some(text_style_refinement) = &self.text_style_refinement {
13925            text_style.refine(text_style_refinement)
13926        }
13927
13928        let background = match self.mode {
13929            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13930            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13931            EditorMode::Full => cx.theme().colors().editor_background,
13932        };
13933
13934        EditorElement::new(
13935            cx.view(),
13936            EditorStyle {
13937                background,
13938                local_player: cx.theme().players().local(),
13939                text: text_style,
13940                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13941                syntax: cx.theme().syntax().clone(),
13942                status: cx.theme().status().clone(),
13943                inlay_hints_style: make_inlay_hints_style(cx),
13944                suggestions_style: HighlightStyle {
13945                    color: Some(cx.theme().status().predictive),
13946                    ..HighlightStyle::default()
13947                },
13948                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13949            },
13950        )
13951    }
13952}
13953
13954impl ViewInputHandler for Editor {
13955    fn text_for_range(
13956        &mut self,
13957        range_utf16: Range<usize>,
13958        cx: &mut ViewContext<Self>,
13959    ) -> Option<String> {
13960        Some(
13961            self.buffer
13962                .read(cx)
13963                .read(cx)
13964                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13965                .collect(),
13966        )
13967    }
13968
13969    fn selected_text_range(
13970        &mut self,
13971        ignore_disabled_input: bool,
13972        cx: &mut ViewContext<Self>,
13973    ) -> Option<UTF16Selection> {
13974        // Prevent the IME menu from appearing when holding down an alphabetic key
13975        // while input is disabled.
13976        if !ignore_disabled_input && !self.input_enabled {
13977            return None;
13978        }
13979
13980        let selection = self.selections.newest::<OffsetUtf16>(cx);
13981        let range = selection.range();
13982
13983        Some(UTF16Selection {
13984            range: range.start.0..range.end.0,
13985            reversed: selection.reversed,
13986        })
13987    }
13988
13989    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13990        let snapshot = self.buffer.read(cx).read(cx);
13991        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13992        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13993    }
13994
13995    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13996        self.clear_highlights::<InputComposition>(cx);
13997        self.ime_transaction.take();
13998    }
13999
14000    fn replace_text_in_range(
14001        &mut self,
14002        range_utf16: Option<Range<usize>>,
14003        text: &str,
14004        cx: &mut ViewContext<Self>,
14005    ) {
14006        if !self.input_enabled {
14007            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14008            return;
14009        }
14010
14011        self.transact(cx, |this, cx| {
14012            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14013                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14014                Some(this.selection_replacement_ranges(range_utf16, cx))
14015            } else {
14016                this.marked_text_ranges(cx)
14017            };
14018
14019            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14020                let newest_selection_id = this.selections.newest_anchor().id;
14021                this.selections
14022                    .all::<OffsetUtf16>(cx)
14023                    .iter()
14024                    .zip(ranges_to_replace.iter())
14025                    .find_map(|(selection, range)| {
14026                        if selection.id == newest_selection_id {
14027                            Some(
14028                                (range.start.0 as isize - selection.head().0 as isize)
14029                                    ..(range.end.0 as isize - selection.head().0 as isize),
14030                            )
14031                        } else {
14032                            None
14033                        }
14034                    })
14035            });
14036
14037            cx.emit(EditorEvent::InputHandled {
14038                utf16_range_to_replace: range_to_replace,
14039                text: text.into(),
14040            });
14041
14042            if let Some(new_selected_ranges) = new_selected_ranges {
14043                this.change_selections(None, cx, |selections| {
14044                    selections.select_ranges(new_selected_ranges)
14045                });
14046                this.backspace(&Default::default(), cx);
14047            }
14048
14049            this.handle_input(text, cx);
14050        });
14051
14052        if let Some(transaction) = self.ime_transaction {
14053            self.buffer.update(cx, |buffer, cx| {
14054                buffer.group_until_transaction(transaction, cx);
14055            });
14056        }
14057
14058        self.unmark_text(cx);
14059    }
14060
14061    fn replace_and_mark_text_in_range(
14062        &mut self,
14063        range_utf16: Option<Range<usize>>,
14064        text: &str,
14065        new_selected_range_utf16: Option<Range<usize>>,
14066        cx: &mut ViewContext<Self>,
14067    ) {
14068        if !self.input_enabled {
14069            return;
14070        }
14071
14072        let transaction = self.transact(cx, |this, cx| {
14073            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14074                let snapshot = this.buffer.read(cx).read(cx);
14075                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14076                    for marked_range in &mut marked_ranges {
14077                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14078                        marked_range.start.0 += relative_range_utf16.start;
14079                        marked_range.start =
14080                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14081                        marked_range.end =
14082                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14083                    }
14084                }
14085                Some(marked_ranges)
14086            } else if let Some(range_utf16) = range_utf16 {
14087                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14088                Some(this.selection_replacement_ranges(range_utf16, cx))
14089            } else {
14090                None
14091            };
14092
14093            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14094                let newest_selection_id = this.selections.newest_anchor().id;
14095                this.selections
14096                    .all::<OffsetUtf16>(cx)
14097                    .iter()
14098                    .zip(ranges_to_replace.iter())
14099                    .find_map(|(selection, range)| {
14100                        if selection.id == newest_selection_id {
14101                            Some(
14102                                (range.start.0 as isize - selection.head().0 as isize)
14103                                    ..(range.end.0 as isize - selection.head().0 as isize),
14104                            )
14105                        } else {
14106                            None
14107                        }
14108                    })
14109            });
14110
14111            cx.emit(EditorEvent::InputHandled {
14112                utf16_range_to_replace: range_to_replace,
14113                text: text.into(),
14114            });
14115
14116            if let Some(ranges) = ranges_to_replace {
14117                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14118            }
14119
14120            let marked_ranges = {
14121                let snapshot = this.buffer.read(cx).read(cx);
14122                this.selections
14123                    .disjoint_anchors()
14124                    .iter()
14125                    .map(|selection| {
14126                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14127                    })
14128                    .collect::<Vec<_>>()
14129            };
14130
14131            if text.is_empty() {
14132                this.unmark_text(cx);
14133            } else {
14134                this.highlight_text::<InputComposition>(
14135                    marked_ranges.clone(),
14136                    HighlightStyle {
14137                        underline: Some(UnderlineStyle {
14138                            thickness: px(1.),
14139                            color: None,
14140                            wavy: false,
14141                        }),
14142                        ..Default::default()
14143                    },
14144                    cx,
14145                );
14146            }
14147
14148            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14149            let use_autoclose = this.use_autoclose;
14150            let use_auto_surround = this.use_auto_surround;
14151            this.set_use_autoclose(false);
14152            this.set_use_auto_surround(false);
14153            this.handle_input(text, cx);
14154            this.set_use_autoclose(use_autoclose);
14155            this.set_use_auto_surround(use_auto_surround);
14156
14157            if let Some(new_selected_range) = new_selected_range_utf16 {
14158                let snapshot = this.buffer.read(cx).read(cx);
14159                let new_selected_ranges = marked_ranges
14160                    .into_iter()
14161                    .map(|marked_range| {
14162                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14163                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14164                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14165                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14166                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14167                    })
14168                    .collect::<Vec<_>>();
14169
14170                drop(snapshot);
14171                this.change_selections(None, cx, |selections| {
14172                    selections.select_ranges(new_selected_ranges)
14173                });
14174            }
14175        });
14176
14177        self.ime_transaction = self.ime_transaction.or(transaction);
14178        if let Some(transaction) = self.ime_transaction {
14179            self.buffer.update(cx, |buffer, cx| {
14180                buffer.group_until_transaction(transaction, cx);
14181            });
14182        }
14183
14184        if self.text_highlights::<InputComposition>(cx).is_none() {
14185            self.ime_transaction.take();
14186        }
14187    }
14188
14189    fn bounds_for_range(
14190        &mut self,
14191        range_utf16: Range<usize>,
14192        element_bounds: gpui::Bounds<Pixels>,
14193        cx: &mut ViewContext<Self>,
14194    ) -> Option<gpui::Bounds<Pixels>> {
14195        let text_layout_details = self.text_layout_details(cx);
14196        let style = &text_layout_details.editor_style;
14197        let font_id = cx.text_system().resolve_font(&style.text.font());
14198        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14199        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14200
14201        let em_width = cx
14202            .text_system()
14203            .typographic_bounds(font_id, font_size, 'm')
14204            .unwrap()
14205            .size
14206            .width;
14207
14208        let snapshot = self.snapshot(cx);
14209        let scroll_position = snapshot.scroll_position();
14210        let scroll_left = scroll_position.x * em_width;
14211
14212        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14213        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14214            + self.gutter_dimensions.width;
14215        let y = line_height * (start.row().as_f32() - scroll_position.y);
14216
14217        Some(Bounds {
14218            origin: element_bounds.origin + point(x, y),
14219            size: size(em_width, line_height),
14220        })
14221    }
14222}
14223
14224trait SelectionExt {
14225    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14226    fn spanned_rows(
14227        &self,
14228        include_end_if_at_line_start: bool,
14229        map: &DisplaySnapshot,
14230    ) -> Range<MultiBufferRow>;
14231}
14232
14233impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14234    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14235        let start = self
14236            .start
14237            .to_point(&map.buffer_snapshot)
14238            .to_display_point(map);
14239        let end = self
14240            .end
14241            .to_point(&map.buffer_snapshot)
14242            .to_display_point(map);
14243        if self.reversed {
14244            end..start
14245        } else {
14246            start..end
14247        }
14248    }
14249
14250    fn spanned_rows(
14251        &self,
14252        include_end_if_at_line_start: bool,
14253        map: &DisplaySnapshot,
14254    ) -> Range<MultiBufferRow> {
14255        let start = self.start.to_point(&map.buffer_snapshot);
14256        let mut end = self.end.to_point(&map.buffer_snapshot);
14257        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14258            end.row -= 1;
14259        }
14260
14261        let buffer_start = map.prev_line_boundary(start).0;
14262        let buffer_end = map.next_line_boundary(end).0;
14263        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14264    }
14265}
14266
14267impl<T: InvalidationRegion> InvalidationStack<T> {
14268    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14269    where
14270        S: Clone + ToOffset,
14271    {
14272        while let Some(region) = self.last() {
14273            let all_selections_inside_invalidation_ranges =
14274                if selections.len() == region.ranges().len() {
14275                    selections
14276                        .iter()
14277                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14278                        .all(|(selection, invalidation_range)| {
14279                            let head = selection.head().to_offset(buffer);
14280                            invalidation_range.start <= head && invalidation_range.end >= head
14281                        })
14282                } else {
14283                    false
14284                };
14285
14286            if all_selections_inside_invalidation_ranges {
14287                break;
14288            } else {
14289                self.pop();
14290            }
14291        }
14292    }
14293}
14294
14295impl<T> Default for InvalidationStack<T> {
14296    fn default() -> Self {
14297        Self(Default::default())
14298    }
14299}
14300
14301impl<T> Deref for InvalidationStack<T> {
14302    type Target = Vec<T>;
14303
14304    fn deref(&self) -> &Self::Target {
14305        &self.0
14306    }
14307}
14308
14309impl<T> DerefMut for InvalidationStack<T> {
14310    fn deref_mut(&mut self) -> &mut Self::Target {
14311        &mut self.0
14312    }
14313}
14314
14315impl InvalidationRegion for SnippetState {
14316    fn ranges(&self) -> &[Range<Anchor>] {
14317        &self.ranges[self.active_index]
14318    }
14319}
14320
14321pub fn diagnostic_block_renderer(
14322    diagnostic: Diagnostic,
14323    max_message_rows: Option<u8>,
14324    allow_closing: bool,
14325    _is_valid: bool,
14326) -> RenderBlock {
14327    let (text_without_backticks, code_ranges) =
14328        highlight_diagnostic_message(&diagnostic, max_message_rows);
14329
14330    Box::new(move |cx: &mut BlockContext| {
14331        let group_id: SharedString = cx.block_id.to_string().into();
14332
14333        let mut text_style = cx.text_style().clone();
14334        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14335        let theme_settings = ThemeSettings::get_global(cx);
14336        text_style.font_family = theme_settings.buffer_font.family.clone();
14337        text_style.font_style = theme_settings.buffer_font.style;
14338        text_style.font_features = theme_settings.buffer_font.features.clone();
14339        text_style.font_weight = theme_settings.buffer_font.weight;
14340
14341        let multi_line_diagnostic = diagnostic.message.contains('\n');
14342
14343        let buttons = |diagnostic: &Diagnostic| {
14344            if multi_line_diagnostic {
14345                v_flex()
14346            } else {
14347                h_flex()
14348            }
14349            .when(allow_closing, |div| {
14350                div.children(diagnostic.is_primary.then(|| {
14351                    IconButton::new("close-block", IconName::XCircle)
14352                        .icon_color(Color::Muted)
14353                        .size(ButtonSize::Compact)
14354                        .style(ButtonStyle::Transparent)
14355                        .visible_on_hover(group_id.clone())
14356                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14357                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14358                }))
14359            })
14360            .child(
14361                IconButton::new("copy-block", IconName::Copy)
14362                    .icon_color(Color::Muted)
14363                    .size(ButtonSize::Compact)
14364                    .style(ButtonStyle::Transparent)
14365                    .visible_on_hover(group_id.clone())
14366                    .on_click({
14367                        let message = diagnostic.message.clone();
14368                        move |_click, cx| {
14369                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14370                        }
14371                    })
14372                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14373            )
14374        };
14375
14376        let icon_size = buttons(&diagnostic)
14377            .into_any_element()
14378            .layout_as_root(AvailableSpace::min_size(), cx);
14379
14380        h_flex()
14381            .id(cx.block_id)
14382            .group(group_id.clone())
14383            .relative()
14384            .size_full()
14385            .pl(cx.gutter_dimensions.width)
14386            .w(cx.max_width - cx.gutter_dimensions.full_width())
14387            .child(
14388                div()
14389                    .flex()
14390                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14391                    .flex_shrink(),
14392            )
14393            .child(buttons(&diagnostic))
14394            .child(div().flex().flex_shrink_0().child(
14395                StyledText::new(text_without_backticks.clone()).with_highlights(
14396                    &text_style,
14397                    code_ranges.iter().map(|range| {
14398                        (
14399                            range.clone(),
14400                            HighlightStyle {
14401                                font_weight: Some(FontWeight::BOLD),
14402                                ..Default::default()
14403                            },
14404                        )
14405                    }),
14406                ),
14407            ))
14408            .into_any_element()
14409    })
14410}
14411
14412pub fn highlight_diagnostic_message(
14413    diagnostic: &Diagnostic,
14414    mut max_message_rows: Option<u8>,
14415) -> (SharedString, Vec<Range<usize>>) {
14416    let mut text_without_backticks = String::new();
14417    let mut code_ranges = Vec::new();
14418
14419    if let Some(source) = &diagnostic.source {
14420        text_without_backticks.push_str(source);
14421        code_ranges.push(0..source.len());
14422        text_without_backticks.push_str(": ");
14423    }
14424
14425    let mut prev_offset = 0;
14426    let mut in_code_block = false;
14427    let has_row_limit = max_message_rows.is_some();
14428    let mut newline_indices = diagnostic
14429        .message
14430        .match_indices('\n')
14431        .filter(|_| has_row_limit)
14432        .map(|(ix, _)| ix)
14433        .fuse()
14434        .peekable();
14435
14436    for (quote_ix, _) in diagnostic
14437        .message
14438        .match_indices('`')
14439        .chain([(diagnostic.message.len(), "")])
14440    {
14441        let mut first_newline_ix = None;
14442        let mut last_newline_ix = None;
14443        while let Some(newline_ix) = newline_indices.peek() {
14444            if *newline_ix < quote_ix {
14445                if first_newline_ix.is_none() {
14446                    first_newline_ix = Some(*newline_ix);
14447                }
14448                last_newline_ix = Some(*newline_ix);
14449
14450                if let Some(rows_left) = &mut max_message_rows {
14451                    if *rows_left == 0 {
14452                        break;
14453                    } else {
14454                        *rows_left -= 1;
14455                    }
14456                }
14457                let _ = newline_indices.next();
14458            } else {
14459                break;
14460            }
14461        }
14462        let prev_len = text_without_backticks.len();
14463        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14464        text_without_backticks.push_str(new_text);
14465        if in_code_block {
14466            code_ranges.push(prev_len..text_without_backticks.len());
14467        }
14468        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14469        in_code_block = !in_code_block;
14470        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14471            text_without_backticks.push_str("...");
14472            break;
14473        }
14474    }
14475
14476    (text_without_backticks.into(), code_ranges)
14477}
14478
14479fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14480    match severity {
14481        DiagnosticSeverity::ERROR => colors.error,
14482        DiagnosticSeverity::WARNING => colors.warning,
14483        DiagnosticSeverity::INFORMATION => colors.info,
14484        DiagnosticSeverity::HINT => colors.info,
14485        _ => colors.ignored,
14486    }
14487}
14488
14489pub fn styled_runs_for_code_label<'a>(
14490    label: &'a CodeLabel,
14491    syntax_theme: &'a theme::SyntaxTheme,
14492) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14493    let fade_out = HighlightStyle {
14494        fade_out: Some(0.35),
14495        ..Default::default()
14496    };
14497
14498    let mut prev_end = label.filter_range.end;
14499    label
14500        .runs
14501        .iter()
14502        .enumerate()
14503        .flat_map(move |(ix, (range, highlight_id))| {
14504            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14505                style
14506            } else {
14507                return Default::default();
14508            };
14509            let mut muted_style = style;
14510            muted_style.highlight(fade_out);
14511
14512            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14513            if range.start >= label.filter_range.end {
14514                if range.start > prev_end {
14515                    runs.push((prev_end..range.start, fade_out));
14516                }
14517                runs.push((range.clone(), muted_style));
14518            } else if range.end <= label.filter_range.end {
14519                runs.push((range.clone(), style));
14520            } else {
14521                runs.push((range.start..label.filter_range.end, style));
14522                runs.push((label.filter_range.end..range.end, muted_style));
14523            }
14524            prev_end = cmp::max(prev_end, range.end);
14525
14526            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14527                runs.push((prev_end..label.text.len(), fade_out));
14528            }
14529
14530            runs
14531        })
14532}
14533
14534pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14535    let mut prev_index = 0;
14536    let mut prev_codepoint: Option<char> = None;
14537    text.char_indices()
14538        .chain([(text.len(), '\0')])
14539        .filter_map(move |(index, codepoint)| {
14540            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14541            let is_boundary = index == text.len()
14542                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14543                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14544            if is_boundary {
14545                let chunk = &text[prev_index..index];
14546                prev_index = index;
14547                Some(chunk)
14548            } else {
14549                None
14550            }
14551        })
14552}
14553
14554pub trait RangeToAnchorExt: Sized {
14555    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14556
14557    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14558        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14559        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14560    }
14561}
14562
14563impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14564    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14565        let start_offset = self.start.to_offset(snapshot);
14566        let end_offset = self.end.to_offset(snapshot);
14567        if start_offset == end_offset {
14568            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14569        } else {
14570            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14571        }
14572    }
14573}
14574
14575pub trait RowExt {
14576    fn as_f32(&self) -> f32;
14577
14578    fn next_row(&self) -> Self;
14579
14580    fn previous_row(&self) -> Self;
14581
14582    fn minus(&self, other: Self) -> u32;
14583}
14584
14585impl RowExt for DisplayRow {
14586    fn as_f32(&self) -> f32 {
14587        self.0 as f32
14588    }
14589
14590    fn next_row(&self) -> Self {
14591        Self(self.0 + 1)
14592    }
14593
14594    fn previous_row(&self) -> Self {
14595        Self(self.0.saturating_sub(1))
14596    }
14597
14598    fn minus(&self, other: Self) -> u32 {
14599        self.0 - other.0
14600    }
14601}
14602
14603impl RowExt for MultiBufferRow {
14604    fn as_f32(&self) -> f32 {
14605        self.0 as f32
14606    }
14607
14608    fn next_row(&self) -> Self {
14609        Self(self.0 + 1)
14610    }
14611
14612    fn previous_row(&self) -> Self {
14613        Self(self.0.saturating_sub(1))
14614    }
14615
14616    fn minus(&self, other: Self) -> u32 {
14617        self.0 - other.0
14618    }
14619}
14620
14621trait RowRangeExt {
14622    type Row;
14623
14624    fn len(&self) -> usize;
14625
14626    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14627}
14628
14629impl RowRangeExt for Range<MultiBufferRow> {
14630    type Row = MultiBufferRow;
14631
14632    fn len(&self) -> usize {
14633        (self.end.0 - self.start.0) as usize
14634    }
14635
14636    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14637        (self.start.0..self.end.0).map(MultiBufferRow)
14638    }
14639}
14640
14641impl RowRangeExt for Range<DisplayRow> {
14642    type Row = DisplayRow;
14643
14644    fn len(&self) -> usize {
14645        (self.end.0 - self.start.0) as usize
14646    }
14647
14648    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14649        (self.start.0..self.end.0).map(DisplayRow)
14650    }
14651}
14652
14653fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14654    if hunk.diff_base_byte_range.is_empty() {
14655        DiffHunkStatus::Added
14656    } else if hunk.row_range.is_empty() {
14657        DiffHunkStatus::Removed
14658    } else {
14659        DiffHunkStatus::Modified
14660    }
14661}
14662
14663/// If select range has more than one line, we
14664/// just point the cursor to range.start.
14665fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14666    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14667        range
14668    } else {
14669        range.start..range.start
14670    }
14671}