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;
   51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   52pub(crate) use actions::*;
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use task::{ResolvedTask, TaskTemplate, TaskVariables};
  106
  107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  108pub use lsp::CompletionContext;
  109use lsp::{
  110    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  111    LanguageServerId,
  112};
  113use mouse_context_menu::MouseContextMenu;
  114use movement::TextLayoutDetails;
  115pub use multi_buffer::{
  116    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  117    ToPoint,
  118};
  119use multi_buffer::{
  120    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  121};
  122use ordered_float::OrderedFloat;
  123use parking_lot::{Mutex, RwLock};
  124use project::{
  125    lsp_store::{FormatTarget, FormatTrigger},
  126    project_settings::{GitGutterSetting, ProjectSettings},
  127    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  128    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  129};
  130use rand::prelude::*;
  131use rpc::{proto::*, ErrorExt};
  132use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  133use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  134use serde::{Deserialize, Serialize};
  135use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  136use smallvec::SmallVec;
  137use snippet::Snippet;
  138use std::{
  139    any::TypeId,
  140    borrow::Cow,
  141    cell::RefCell,
  142    cmp::{self, Ordering, Reverse},
  143    mem,
  144    num::NonZeroU32,
  145    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  146    path::{Path, PathBuf},
  147    rc::Rc,
  148    sync::Arc,
  149    time::{Duration, Instant},
  150};
  151pub use sum_tree::Bias;
  152use sum_tree::TreeMap;
  153use text::{BufferId, OffsetUtf16, Rope};
  154use theme::{
  155    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  156    ThemeColors, ThemeSettings,
  157};
  158use ui::{
  159    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  160    ListItem, Popover, PopoverMenuHandle, Tooltip,
  161};
  162use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  163use workspace::item::{ItemHandle, PreviewTabsSettings};
  164use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  165use workspace::{
  166    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  167};
  168use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  169
  170use crate::hover_links::find_url;
  171use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  172
  173pub const FILE_HEADER_HEIGHT: u32 = 1;
  174pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  175pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  176pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  177const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  178const MAX_LINE_LEN: usize = 1024;
  179const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  180const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  181pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  182#[doc(hidden)]
  183pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  184#[doc(hidden)]
  185pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  186
  187pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  188pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  189
  190pub fn render_parsed_markdown(
  191    element_id: impl Into<ElementId>,
  192    parsed: &language::ParsedMarkdown,
  193    editor_style: &EditorStyle,
  194    workspace: Option<WeakView<Workspace>>,
  195    cx: &mut WindowContext,
  196) -> InteractiveText {
  197    let code_span_background_color = cx
  198        .theme()
  199        .colors()
  200        .editor_document_highlight_read_background;
  201
  202    let highlights = gpui::combine_highlights(
  203        parsed.highlights.iter().filter_map(|(range, highlight)| {
  204            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  205            Some((range.clone(), highlight))
  206        }),
  207        parsed
  208            .regions
  209            .iter()
  210            .zip(&parsed.region_ranges)
  211            .filter_map(|(region, range)| {
  212                if region.code {
  213                    Some((
  214                        range.clone(),
  215                        HighlightStyle {
  216                            background_color: Some(code_span_background_color),
  217                            ..Default::default()
  218                        },
  219                    ))
  220                } else {
  221                    None
  222                }
  223            }),
  224    );
  225
  226    let mut links = Vec::new();
  227    let mut link_ranges = Vec::new();
  228    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  229        if let Some(link) = region.link.clone() {
  230            links.push(link);
  231            link_ranges.push(range.clone());
  232        }
  233    }
  234
  235    InteractiveText::new(
  236        element_id,
  237        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  238    )
  239    .on_click(link_ranges, move |clicked_range_ix, cx| {
  240        match &links[clicked_range_ix] {
  241            markdown::Link::Web { url } => cx.open_url(url),
  242            markdown::Link::Path { path } => {
  243                if let Some(workspace) = &workspace {
  244                    _ = workspace.update(cx, |workspace, cx| {
  245                        workspace.open_abs_path(path.clone(), false, cx).detach();
  246                    });
  247                }
  248            }
  249        }
  250    })
  251}
  252
  253#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  254pub(crate) enum InlayId {
  255    Suggestion(usize),
  256    Hint(usize),
  257}
  258
  259impl InlayId {
  260    fn id(&self) -> usize {
  261        match self {
  262            Self::Suggestion(id) => *id,
  263            Self::Hint(id) => *id,
  264        }
  265    }
  266}
  267
  268enum DiffRowHighlight {}
  269enum DocumentHighlightRead {}
  270enum DocumentHighlightWrite {}
  271enum InputComposition {}
  272
  273#[derive(Copy, Clone, PartialEq, Eq)]
  274pub enum Direction {
  275    Prev,
  276    Next,
  277}
  278
  279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  280pub enum Navigated {
  281    Yes,
  282    No,
  283}
  284
  285impl Navigated {
  286    pub fn from_bool(yes: bool) -> Navigated {
  287        if yes {
  288            Navigated::Yes
  289        } else {
  290            Navigated::No
  291        }
  292    }
  293}
  294
  295pub fn init_settings(cx: &mut AppContext) {
  296    EditorSettings::register(cx);
  297}
  298
  299pub fn init(cx: &mut AppContext) {
  300    init_settings(cx);
  301
  302    workspace::register_project_item::<Editor>(cx);
  303    workspace::FollowableViewRegistry::register::<Editor>(cx);
  304    workspace::register_serializable_item::<Editor>(cx);
  305
  306    cx.observe_new_views(
  307        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  308            workspace.register_action(Editor::new_file);
  309            workspace.register_action(Editor::new_file_vertical);
  310            workspace.register_action(Editor::new_file_horizontal);
  311        },
  312    )
  313    .detach();
  314
  315    cx.on_action(move |_: &workspace::NewFile, cx| {
  316        let app_state = workspace::AppState::global(cx);
  317        if let Some(app_state) = app_state.upgrade() {
  318            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  319                Editor::new_file(workspace, &Default::default(), cx)
  320            })
  321            .detach();
  322        }
  323    });
  324    cx.on_action(move |_: &workspace::NewWindow, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  328                Editor::new_file(workspace, &Default::default(), cx)
  329            })
  330            .detach();
  331        }
  332    });
  333}
  334
  335pub struct SearchWithinRange;
  336
  337trait InvalidationRegion {
  338    fn ranges(&self) -> &[Range<Anchor>];
  339}
  340
  341#[derive(Clone, Debug, PartialEq)]
  342pub enum SelectPhase {
  343    Begin {
  344        position: DisplayPoint,
  345        add: bool,
  346        click_count: usize,
  347    },
  348    BeginColumnar {
  349        position: DisplayPoint,
  350        reset: bool,
  351        goal_column: u32,
  352    },
  353    Extend {
  354        position: DisplayPoint,
  355        click_count: usize,
  356    },
  357    Update {
  358        position: DisplayPoint,
  359        goal_column: u32,
  360        scroll_delta: gpui::Point<f32>,
  361    },
  362    End,
  363}
  364
  365#[derive(Clone, Debug)]
  366pub enum SelectMode {
  367    Character,
  368    Word(Range<Anchor>),
  369    Line(Range<Anchor>),
  370    All,
  371}
  372
  373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  374pub enum EditorMode {
  375    SingleLine { auto_width: bool },
  376    AutoHeight { max_lines: usize },
  377    Full,
  378}
  379
  380#[derive(Copy, Clone, Debug)]
  381pub enum SoftWrap {
  382    /// Prefer not to wrap at all.
  383    ///
  384    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  385    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  386    GitDiff,
  387    /// Prefer a single line generally, unless an overly long line is encountered.
  388    None,
  389    /// Soft wrap lines that exceed the editor width.
  390    EditorWidth,
  391    /// Soft wrap lines at the preferred line length.
  392    Column(u32),
  393    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  394    Bounded(u32),
  395}
  396
  397#[derive(Clone)]
  398pub struct EditorStyle {
  399    pub background: Hsla,
  400    pub local_player: PlayerColor,
  401    pub text: TextStyle,
  402    pub scrollbar_width: Pixels,
  403    pub syntax: Arc<SyntaxTheme>,
  404    pub status: StatusColors,
  405    pub inlay_hints_style: HighlightStyle,
  406    pub suggestions_style: HighlightStyle,
  407    pub unnecessary_code_fade: f32,
  408}
  409
  410impl Default for EditorStyle {
  411    fn default() -> Self {
  412        Self {
  413            background: Hsla::default(),
  414            local_player: PlayerColor::default(),
  415            text: TextStyle::default(),
  416            scrollbar_width: Pixels::default(),
  417            syntax: Default::default(),
  418            // HACK: Status colors don't have a real default.
  419            // We should look into removing the status colors from the editor
  420            // style and retrieve them directly from the theme.
  421            status: StatusColors::dark(),
  422            inlay_hints_style: HighlightStyle::default(),
  423            suggestions_style: HighlightStyle::default(),
  424            unnecessary_code_fade: Default::default(),
  425        }
  426    }
  427}
  428
  429pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  430    let show_background = all_language_settings(None, cx)
  431        .language(None)
  432        .inlay_hints
  433        .show_background;
  434
  435    HighlightStyle {
  436        color: Some(cx.theme().status().hint),
  437        background_color: show_background.then(|| cx.theme().status().hint_background),
  438        ..HighlightStyle::default()
  439    }
  440}
  441
  442type CompletionId = usize;
  443
  444#[derive(Clone, Debug)]
  445struct CompletionState {
  446    // render_inlay_ids represents the inlay hints that are inserted
  447    // for rendering the inline completions. They may be discontinuous
  448    // in the event that the completion provider returns some intersection
  449    // with the existing content.
  450    render_inlay_ids: Vec<InlayId>,
  451    // text is the resulting rope that is inserted when the user accepts a completion.
  452    text: Rope,
  453    // position is the position of the cursor when the completion was triggered.
  454    position: multi_buffer::Anchor,
  455    // delete_range is the range of text that this completion state covers.
  456    // if the completion is accepted, this range should be deleted.
  457    delete_range: Option<Range<multi_buffer::Anchor>>,
  458}
  459
  460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  461struct EditorActionId(usize);
  462
  463impl EditorActionId {
  464    pub fn post_inc(&mut self) -> Self {
  465        let answer = self.0;
  466
  467        *self = Self(answer + 1);
  468
  469        Self(answer)
  470    }
  471}
  472
  473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  475
  476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  478
  479#[derive(Default)]
  480struct ScrollbarMarkerState {
  481    scrollbar_size: Size<Pixels>,
  482    dirty: bool,
  483    markers: Arc<[PaintQuad]>,
  484    pending_refresh: Option<Task<Result<()>>>,
  485}
  486
  487impl ScrollbarMarkerState {
  488    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  489        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  490    }
  491}
  492
  493#[derive(Clone, Debug)]
  494struct RunnableTasks {
  495    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  496    offset: MultiBufferOffset,
  497    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  498    column: u32,
  499    // Values of all named captures, including those starting with '_'
  500    extra_variables: HashMap<String, String>,
  501    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  502    context_range: Range<BufferOffset>,
  503}
  504
  505#[derive(Clone)]
  506struct ResolvedTasks {
  507    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  508    position: Anchor,
  509}
  510#[derive(Copy, Clone, Debug)]
  511struct MultiBufferOffset(usize);
  512#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  513struct BufferOffset(usize);
  514
  515// Addons allow storing per-editor state in other crates (e.g. Vim)
  516pub trait Addon: 'static {
  517    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  518
  519    fn to_any(&self) -> &dyn std::any::Any;
  520}
  521
  522/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  523///
  524/// See the [module level documentation](self) for more information.
  525pub struct Editor {
  526    focus_handle: FocusHandle,
  527    last_focused_descendant: Option<WeakFocusHandle>,
  528    /// The text buffer being edited
  529    buffer: Model<MultiBuffer>,
  530    /// Map of how text in the buffer should be displayed.
  531    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  532    pub display_map: Model<DisplayMap>,
  533    pub selections: SelectionsCollection,
  534    pub scroll_manager: ScrollManager,
  535    /// When inline assist editors are linked, they all render cursors because
  536    /// typing enters text into each of them, even the ones that aren't focused.
  537    pub(crate) show_cursor_when_unfocused: bool,
  538    columnar_selection_tail: Option<Anchor>,
  539    add_selections_state: Option<AddSelectionsState>,
  540    select_next_state: Option<SelectNextState>,
  541    select_prev_state: Option<SelectNextState>,
  542    selection_history: SelectionHistory,
  543    autoclose_regions: Vec<AutocloseRegion>,
  544    snippet_stack: InvalidationStack<SnippetState>,
  545    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  546    ime_transaction: Option<TransactionId>,
  547    active_diagnostics: Option<ActiveDiagnosticGroup>,
  548    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  549    project: Option<Model<Project>>,
  550    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  551    completion_provider: Option<Box<dyn CompletionProvider>>,
  552    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  553    blink_manager: Model<BlinkManager>,
  554    show_cursor_names: bool,
  555    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  556    pub show_local_selections: bool,
  557    mode: EditorMode,
  558    show_breadcrumbs: bool,
  559    show_gutter: bool,
  560    show_line_numbers: Option<bool>,
  561    use_relative_line_numbers: Option<bool>,
  562    show_git_diff_gutter: Option<bool>,
  563    show_code_actions: Option<bool>,
  564    show_runnables: Option<bool>,
  565    show_wrap_guides: Option<bool>,
  566    show_indent_guides: Option<bool>,
  567    placeholder_text: Option<Arc<str>>,
  568    highlight_order: usize,
  569    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  570    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  571    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  572    scrollbar_marker_state: ScrollbarMarkerState,
  573    active_indent_guides_state: ActiveIndentGuidesState,
  574    nav_history: Option<ItemNavHistory>,
  575    context_menu: RwLock<Option<ContextMenu>>,
  576    mouse_context_menu: Option<MouseContextMenu>,
  577    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  578    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  579    signature_help_state: SignatureHelpState,
  580    auto_signature_help: Option<bool>,
  581    find_all_references_task_sources: Vec<Anchor>,
  582    next_completion_id: CompletionId,
  583    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  584    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  585    code_actions_task: Option<Task<Result<()>>>,
  586    document_highlights_task: Option<Task<()>>,
  587    linked_editing_range_task: Option<Task<Option<()>>>,
  588    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  589    pending_rename: Option<RenameState>,
  590    searchable: bool,
  591    cursor_shape: CursorShape,
  592    current_line_highlight: Option<CurrentLineHighlight>,
  593    collapse_matches: bool,
  594    autoindent_mode: Option<AutoindentMode>,
  595    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  596    input_enabled: bool,
  597    use_modal_editing: bool,
  598    read_only: bool,
  599    leader_peer_id: Option<PeerId>,
  600    remote_id: Option<ViewId>,
  601    hover_state: HoverState,
  602    gutter_hovered: bool,
  603    hovered_link_state: Option<HoveredLinkState>,
  604    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  605    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  606    active_inline_completion: Option<CompletionState>,
  607    // enable_inline_completions is a switch that Vim can use to disable
  608    // inline completions based on its mode.
  609    enable_inline_completions: bool,
  610    show_inline_completions_override: Option<bool>,
  611    inlay_hint_cache: InlayHintCache,
  612    expanded_hunks: ExpandedHunks,
  613    next_inlay_id: usize,
  614    _subscriptions: Vec<Subscription>,
  615    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  616    gutter_dimensions: GutterDimensions,
  617    style: Option<EditorStyle>,
  618    next_editor_action_id: EditorActionId,
  619    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  620    use_autoclose: bool,
  621    use_auto_surround: bool,
  622    auto_replace_emoji_shortcode: bool,
  623    show_git_blame_gutter: bool,
  624    show_git_blame_inline: bool,
  625    show_git_blame_inline_delay_task: Option<Task<()>>,
  626    git_blame_inline_enabled: bool,
  627    serialize_dirty_buffers: bool,
  628    show_selection_menu: Option<bool>,
  629    blame: Option<Model<GitBlame>>,
  630    blame_subscription: Option<Subscription>,
  631    custom_context_menu: Option<
  632        Box<
  633            dyn 'static
  634                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  635        >,
  636    >,
  637    last_bounds: Option<Bounds<Pixels>>,
  638    expect_bounds_change: Option<Bounds<Pixels>>,
  639    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  640    tasks_update_task: Option<Task<()>>,
  641    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  642    file_header_size: u32,
  643    breadcrumb_header: Option<String>,
  644    focused_block: Option<FocusedBlock>,
  645    next_scroll_position: NextScrollCursorCenterTopBottom,
  646    addons: HashMap<TypeId, Box<dyn Addon>>,
  647    _scroll_cursor_center_top_bottom_task: Task<()>,
  648}
  649
  650#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  651enum NextScrollCursorCenterTopBottom {
  652    #[default]
  653    Center,
  654    Top,
  655    Bottom,
  656}
  657
  658impl NextScrollCursorCenterTopBottom {
  659    fn next(&self) -> Self {
  660        match self {
  661            Self::Center => Self::Top,
  662            Self::Top => Self::Bottom,
  663            Self::Bottom => Self::Center,
  664        }
  665    }
  666}
  667
  668#[derive(Clone)]
  669pub struct EditorSnapshot {
  670    pub mode: EditorMode,
  671    show_gutter: bool,
  672    show_line_numbers: Option<bool>,
  673    show_git_diff_gutter: Option<bool>,
  674    show_code_actions: Option<bool>,
  675    show_runnables: Option<bool>,
  676    git_blame_gutter_max_author_length: Option<usize>,
  677    pub display_snapshot: DisplaySnapshot,
  678    pub placeholder_text: Option<Arc<str>>,
  679    is_focused: bool,
  680    scroll_anchor: ScrollAnchor,
  681    ongoing_scroll: OngoingScroll,
  682    current_line_highlight: CurrentLineHighlight,
  683    gutter_hovered: bool,
  684}
  685
  686const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  687
  688#[derive(Default, Debug, Clone, Copy)]
  689pub struct GutterDimensions {
  690    pub left_padding: Pixels,
  691    pub right_padding: Pixels,
  692    pub width: Pixels,
  693    pub margin: Pixels,
  694    pub git_blame_entries_width: Option<Pixels>,
  695}
  696
  697impl GutterDimensions {
  698    /// The full width of the space taken up by the gutter.
  699    pub fn full_width(&self) -> Pixels {
  700        self.margin + self.width
  701    }
  702
  703    /// The width of the space reserved for the fold indicators,
  704    /// use alongside 'justify_end' and `gutter_width` to
  705    /// right align content with the line numbers
  706    pub fn fold_area_width(&self) -> Pixels {
  707        self.margin + self.right_padding
  708    }
  709}
  710
  711#[derive(Debug)]
  712pub struct RemoteSelection {
  713    pub replica_id: ReplicaId,
  714    pub selection: Selection<Anchor>,
  715    pub cursor_shape: CursorShape,
  716    pub peer_id: PeerId,
  717    pub line_mode: bool,
  718    pub participant_index: Option<ParticipantIndex>,
  719    pub user_name: Option<SharedString>,
  720}
  721
  722#[derive(Clone, Debug)]
  723struct SelectionHistoryEntry {
  724    selections: Arc<[Selection<Anchor>]>,
  725    select_next_state: Option<SelectNextState>,
  726    select_prev_state: Option<SelectNextState>,
  727    add_selections_state: Option<AddSelectionsState>,
  728}
  729
  730enum SelectionHistoryMode {
  731    Normal,
  732    Undoing,
  733    Redoing,
  734}
  735
  736#[derive(Clone, PartialEq, Eq, Hash)]
  737struct HoveredCursor {
  738    replica_id: u16,
  739    selection_id: usize,
  740}
  741
  742impl Default for SelectionHistoryMode {
  743    fn default() -> Self {
  744        Self::Normal
  745    }
  746}
  747
  748#[derive(Default)]
  749struct SelectionHistory {
  750    #[allow(clippy::type_complexity)]
  751    selections_by_transaction:
  752        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  753    mode: SelectionHistoryMode,
  754    undo_stack: VecDeque<SelectionHistoryEntry>,
  755    redo_stack: VecDeque<SelectionHistoryEntry>,
  756}
  757
  758impl SelectionHistory {
  759    fn insert_transaction(
  760        &mut self,
  761        transaction_id: TransactionId,
  762        selections: Arc<[Selection<Anchor>]>,
  763    ) {
  764        self.selections_by_transaction
  765            .insert(transaction_id, (selections, None));
  766    }
  767
  768    #[allow(clippy::type_complexity)]
  769    fn transaction(
  770        &self,
  771        transaction_id: TransactionId,
  772    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  773        self.selections_by_transaction.get(&transaction_id)
  774    }
  775
  776    #[allow(clippy::type_complexity)]
  777    fn transaction_mut(
  778        &mut self,
  779        transaction_id: TransactionId,
  780    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  781        self.selections_by_transaction.get_mut(&transaction_id)
  782    }
  783
  784    fn push(&mut self, entry: SelectionHistoryEntry) {
  785        if !entry.selections.is_empty() {
  786            match self.mode {
  787                SelectionHistoryMode::Normal => {
  788                    self.push_undo(entry);
  789                    self.redo_stack.clear();
  790                }
  791                SelectionHistoryMode::Undoing => self.push_redo(entry),
  792                SelectionHistoryMode::Redoing => self.push_undo(entry),
  793            }
  794        }
  795    }
  796
  797    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  798        if self
  799            .undo_stack
  800            .back()
  801            .map_or(true, |e| e.selections != entry.selections)
  802        {
  803            self.undo_stack.push_back(entry);
  804            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  805                self.undo_stack.pop_front();
  806            }
  807        }
  808    }
  809
  810    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  811        if self
  812            .redo_stack
  813            .back()
  814            .map_or(true, |e| e.selections != entry.selections)
  815        {
  816            self.redo_stack.push_back(entry);
  817            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  818                self.redo_stack.pop_front();
  819            }
  820        }
  821    }
  822}
  823
  824struct RowHighlight {
  825    index: usize,
  826    range: Range<Anchor>,
  827    color: Hsla,
  828    should_autoscroll: bool,
  829}
  830
  831#[derive(Clone, Debug)]
  832struct AddSelectionsState {
  833    above: bool,
  834    stack: Vec<usize>,
  835}
  836
  837#[derive(Clone)]
  838struct SelectNextState {
  839    query: AhoCorasick,
  840    wordwise: bool,
  841    done: bool,
  842}
  843
  844impl std::fmt::Debug for SelectNextState {
  845    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  846        f.debug_struct(std::any::type_name::<Self>())
  847            .field("wordwise", &self.wordwise)
  848            .field("done", &self.done)
  849            .finish()
  850    }
  851}
  852
  853#[derive(Debug)]
  854struct AutocloseRegion {
  855    selection_id: usize,
  856    range: Range<Anchor>,
  857    pair: BracketPair,
  858}
  859
  860#[derive(Debug)]
  861struct SnippetState {
  862    ranges: Vec<Vec<Range<Anchor>>>,
  863    active_index: usize,
  864}
  865
  866#[doc(hidden)]
  867pub struct RenameState {
  868    pub range: Range<Anchor>,
  869    pub old_name: Arc<str>,
  870    pub editor: View<Editor>,
  871    block_id: CustomBlockId,
  872}
  873
  874struct InvalidationStack<T>(Vec<T>);
  875
  876struct RegisteredInlineCompletionProvider {
  877    provider: Arc<dyn InlineCompletionProviderHandle>,
  878    _subscription: Subscription,
  879}
  880
  881enum ContextMenu {
  882    Completions(CompletionsMenu),
  883    CodeActions(CodeActionsMenu),
  884}
  885
  886impl ContextMenu {
  887    fn select_first(
  888        &mut self,
  889        provider: Option<&dyn CompletionProvider>,
  890        cx: &mut ViewContext<Editor>,
  891    ) -> bool {
  892        if self.visible() {
  893            match self {
  894                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  895                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  896            }
  897            true
  898        } else {
  899            false
  900        }
  901    }
  902
  903    fn select_prev(
  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_prev(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_next(
  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_next(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_last(
  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_last(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn visible(&self) -> bool {
  952        match self {
  953            ContextMenu::Completions(menu) => menu.visible(),
  954            ContextMenu::CodeActions(menu) => menu.visible(),
  955        }
  956    }
  957
  958    fn render(
  959        &self,
  960        cursor_position: DisplayPoint,
  961        style: &EditorStyle,
  962        max_height: Pixels,
  963        workspace: Option<WeakView<Workspace>>,
  964        cx: &mut ViewContext<Editor>,
  965    ) -> (ContextMenuOrigin, AnyElement) {
  966        match self {
  967            ContextMenu::Completions(menu) => (
  968                ContextMenuOrigin::EditorPoint(cursor_position),
  969                menu.render(style, max_height, workspace, cx),
  970            ),
  971            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  972        }
  973    }
  974}
  975
  976enum ContextMenuOrigin {
  977    EditorPoint(DisplayPoint),
  978    GutterIndicator(DisplayRow),
  979}
  980
  981#[derive(Clone)]
  982struct CompletionsMenu {
  983    id: CompletionId,
  984    sort_completions: bool,
  985    initial_position: Anchor,
  986    buffer: Model<Buffer>,
  987    completions: Arc<RwLock<Box<[Completion]>>>,
  988    match_candidates: Arc<[StringMatchCandidate]>,
  989    matches: Arc<[StringMatch]>,
  990    selected_item: usize,
  991    scroll_handle: UniformListScrollHandle,
  992    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  993}
  994
  995impl CompletionsMenu {
  996    fn select_first(
  997        &mut self,
  998        provider: Option<&dyn CompletionProvider>,
  999        cx: &mut ViewContext<Editor>,
 1000    ) {
 1001        self.selected_item = 0;
 1002        self.scroll_handle.scroll_to_item(self.selected_item);
 1003        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1004        cx.notify();
 1005    }
 1006
 1007    fn select_prev(
 1008        &mut self,
 1009        provider: Option<&dyn CompletionProvider>,
 1010        cx: &mut ViewContext<Editor>,
 1011    ) {
 1012        if self.selected_item > 0 {
 1013            self.selected_item -= 1;
 1014        } else {
 1015            self.selected_item = self.matches.len() - 1;
 1016        }
 1017        self.scroll_handle.scroll_to_item(self.selected_item);
 1018        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1019        cx.notify();
 1020    }
 1021
 1022    fn select_next(
 1023        &mut self,
 1024        provider: Option<&dyn CompletionProvider>,
 1025        cx: &mut ViewContext<Editor>,
 1026    ) {
 1027        if self.selected_item + 1 < self.matches.len() {
 1028            self.selected_item += 1;
 1029        } else {
 1030            self.selected_item = 0;
 1031        }
 1032        self.scroll_handle.scroll_to_item(self.selected_item);
 1033        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1034        cx.notify();
 1035    }
 1036
 1037    fn select_last(
 1038        &mut self,
 1039        provider: Option<&dyn CompletionProvider>,
 1040        cx: &mut ViewContext<Editor>,
 1041    ) {
 1042        self.selected_item = self.matches.len() - 1;
 1043        self.scroll_handle.scroll_to_item(self.selected_item);
 1044        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1045        cx.notify();
 1046    }
 1047
 1048    fn pre_resolve_completion_documentation(
 1049        buffer: Model<Buffer>,
 1050        completions: Arc<RwLock<Box<[Completion]>>>,
 1051        matches: Arc<[StringMatch]>,
 1052        editor: &Editor,
 1053        cx: &mut ViewContext<Editor>,
 1054    ) -> Task<()> {
 1055        let settings = EditorSettings::get_global(cx);
 1056        if !settings.show_completion_documentation {
 1057            return Task::ready(());
 1058        }
 1059
 1060        let Some(provider) = editor.completion_provider.as_ref() else {
 1061            return Task::ready(());
 1062        };
 1063
 1064        let resolve_task = provider.resolve_completions(
 1065            buffer,
 1066            matches.iter().map(|m| m.candidate_id).collect(),
 1067            completions.clone(),
 1068            cx,
 1069        );
 1070
 1071        cx.spawn(move |this, mut cx| async move {
 1072            if let Some(true) = resolve_task.await.log_err() {
 1073                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1074            }
 1075        })
 1076    }
 1077
 1078    fn attempt_resolve_selected_completion_documentation(
 1079        &mut self,
 1080        provider: Option<&dyn CompletionProvider>,
 1081        cx: &mut ViewContext<Editor>,
 1082    ) {
 1083        let settings = EditorSettings::get_global(cx);
 1084        if !settings.show_completion_documentation {
 1085            return;
 1086        }
 1087
 1088        let completion_index = self.matches[self.selected_item].candidate_id;
 1089        let Some(provider) = provider else {
 1090            return;
 1091        };
 1092
 1093        let resolve_task = provider.resolve_completions(
 1094            self.buffer.clone(),
 1095            vec![completion_index],
 1096            self.completions.clone(),
 1097            cx,
 1098        );
 1099
 1100        let delay_ms =
 1101            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1102        let delay = Duration::from_millis(delay_ms);
 1103
 1104        self.selected_completion_documentation_resolve_debounce
 1105            .lock()
 1106            .fire_new(delay, cx, |_, cx| {
 1107                cx.spawn(move |this, mut cx| async move {
 1108                    if let Some(true) = resolve_task.await.log_err() {
 1109                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1110                    }
 1111                })
 1112            });
 1113    }
 1114
 1115    fn visible(&self) -> bool {
 1116        !self.matches.is_empty()
 1117    }
 1118
 1119    fn render(
 1120        &self,
 1121        style: &EditorStyle,
 1122        max_height: Pixels,
 1123        workspace: Option<WeakView<Workspace>>,
 1124        cx: &mut ViewContext<Editor>,
 1125    ) -> AnyElement {
 1126        let settings = EditorSettings::get_global(cx);
 1127        let show_completion_documentation = settings.show_completion_documentation;
 1128
 1129        let widest_completion_ix = self
 1130            .matches
 1131            .iter()
 1132            .enumerate()
 1133            .max_by_key(|(_, mat)| {
 1134                let completions = self.completions.read();
 1135                let completion = &completions[mat.candidate_id];
 1136                let documentation = &completion.documentation;
 1137
 1138                let mut len = completion.label.text.chars().count();
 1139                if let Some(Documentation::SingleLine(text)) = documentation {
 1140                    if show_completion_documentation {
 1141                        len += text.chars().count();
 1142                    }
 1143                }
 1144
 1145                len
 1146            })
 1147            .map(|(ix, _)| ix);
 1148
 1149        let completions = self.completions.clone();
 1150        let matches = self.matches.clone();
 1151        let selected_item = self.selected_item;
 1152        let style = style.clone();
 1153
 1154        let multiline_docs = if show_completion_documentation {
 1155            let mat = &self.matches[selected_item];
 1156            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1157                Some(Documentation::MultiLinePlainText(text)) => {
 1158                    Some(div().child(SharedString::from(text.clone())))
 1159                }
 1160                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1161                    Some(div().child(render_parsed_markdown(
 1162                        "completions_markdown",
 1163                        parsed,
 1164                        &style,
 1165                        workspace,
 1166                        cx,
 1167                    )))
 1168                }
 1169                _ => None,
 1170            };
 1171            multiline_docs.map(|div| {
 1172                div.id("multiline_docs")
 1173                    .max_h(max_height)
 1174                    .flex_1()
 1175                    .px_1p5()
 1176                    .py_1()
 1177                    .min_w(px(260.))
 1178                    .max_w(px(640.))
 1179                    .w(px(500.))
 1180                    .overflow_y_scroll()
 1181                    .occlude()
 1182            })
 1183        } else {
 1184            None
 1185        };
 1186
 1187        let list = uniform_list(
 1188            cx.view().clone(),
 1189            "completions",
 1190            matches.len(),
 1191            move |_editor, range, cx| {
 1192                let start_ix = range.start;
 1193                let completions_guard = completions.read();
 1194
 1195                matches[range]
 1196                    .iter()
 1197                    .enumerate()
 1198                    .map(|(ix, mat)| {
 1199                        let item_ix = start_ix + ix;
 1200                        let candidate_id = mat.candidate_id;
 1201                        let completion = &completions_guard[candidate_id];
 1202
 1203                        let documentation = if show_completion_documentation {
 1204                            &completion.documentation
 1205                        } else {
 1206                            &None
 1207                        };
 1208
 1209                        let highlights = gpui::combine_highlights(
 1210                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1211                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1212                                |(range, mut highlight)| {
 1213                                    // Ignore font weight for syntax highlighting, as we'll use it
 1214                                    // for fuzzy matches.
 1215                                    highlight.font_weight = None;
 1216
 1217                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1218                                        highlight.strikethrough = Some(StrikethroughStyle {
 1219                                            thickness: 1.0.into(),
 1220                                            ..Default::default()
 1221                                        });
 1222                                        highlight.color = Some(cx.theme().colors().text_muted);
 1223                                    }
 1224
 1225                                    (range, highlight)
 1226                                },
 1227                            ),
 1228                        );
 1229                        let completion_label = StyledText::new(completion.label.text.clone())
 1230                            .with_highlights(&style.text, highlights);
 1231                        let documentation_label =
 1232                            if let Some(Documentation::SingleLine(text)) = documentation {
 1233                                if text.trim().is_empty() {
 1234                                    None
 1235                                } else {
 1236                                    Some(
 1237                                        Label::new(text.clone())
 1238                                            .ml_4()
 1239                                            .size(LabelSize::Small)
 1240                                            .color(Color::Muted),
 1241                                    )
 1242                                }
 1243                            } else {
 1244                                None
 1245                            };
 1246
 1247                        let color_swatch = completion
 1248                            .color()
 1249                            .map(|color| div().size_4().bg(color).rounded_sm());
 1250
 1251                        div().min_w(px(220.)).max_w(px(540.)).child(
 1252                            ListItem::new(mat.candidate_id)
 1253                                .inset(true)
 1254                                .selected(item_ix == selected_item)
 1255                                .on_click(cx.listener(move |editor, _event, cx| {
 1256                                    cx.stop_propagation();
 1257                                    if let Some(task) = editor.confirm_completion(
 1258                                        &ConfirmCompletion {
 1259                                            item_ix: Some(item_ix),
 1260                                        },
 1261                                        cx,
 1262                                    ) {
 1263                                        task.detach_and_log_err(cx)
 1264                                    }
 1265                                }))
 1266                                .start_slot::<Div>(color_swatch)
 1267                                .child(h_flex().overflow_hidden().child(completion_label))
 1268                                .end_slot::<Label>(documentation_label),
 1269                        )
 1270                    })
 1271                    .collect()
 1272            },
 1273        )
 1274        .occlude()
 1275        .max_h(max_height)
 1276        .track_scroll(self.scroll_handle.clone())
 1277        .with_width_from_item(widest_completion_ix)
 1278        .with_sizing_behavior(ListSizingBehavior::Infer);
 1279
 1280        Popover::new()
 1281            .child(list)
 1282            .when_some(multiline_docs, |popover, multiline_docs| {
 1283                popover.aside(multiline_docs)
 1284            })
 1285            .into_any_element()
 1286    }
 1287
 1288    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1289        let mut matches = if let Some(query) = query {
 1290            fuzzy::match_strings(
 1291                &self.match_candidates,
 1292                query,
 1293                query.chars().any(|c| c.is_uppercase()),
 1294                100,
 1295                &Default::default(),
 1296                executor,
 1297            )
 1298            .await
 1299        } else {
 1300            self.match_candidates
 1301                .iter()
 1302                .enumerate()
 1303                .map(|(candidate_id, candidate)| StringMatch {
 1304                    candidate_id,
 1305                    score: Default::default(),
 1306                    positions: Default::default(),
 1307                    string: candidate.string.clone(),
 1308                })
 1309                .collect()
 1310        };
 1311
 1312        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1313        if let Some(query) = query {
 1314            if let Some(query_start) = query.chars().next() {
 1315                matches.retain(|string_match| {
 1316                    split_words(&string_match.string).any(|word| {
 1317                        // Check that the first codepoint of the word as lowercase matches the first
 1318                        // codepoint of the query as lowercase
 1319                        word.chars()
 1320                            .flat_map(|codepoint| codepoint.to_lowercase())
 1321                            .zip(query_start.to_lowercase())
 1322                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1323                    })
 1324                });
 1325            }
 1326        }
 1327
 1328        let completions = self.completions.read();
 1329        if self.sort_completions {
 1330            matches.sort_unstable_by_key(|mat| {
 1331                // We do want to strike a balance here between what the language server tells us
 1332                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1333                // `Creat` and there is a local variable called `CreateComponent`).
 1334                // So what we do is: we bucket all matches into two buckets
 1335                // - Strong matches
 1336                // - Weak matches
 1337                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1338                // and the Weak matches are the rest.
 1339                //
 1340                // For the strong matches, we sort by the language-servers score first and for the weak
 1341                // matches, we prefer our fuzzy finder first.
 1342                //
 1343                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1344                // us into account when it's obviously a bad match.
 1345
 1346                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1347                enum MatchScore<'a> {
 1348                    Strong {
 1349                        sort_text: Option<&'a str>,
 1350                        score: Reverse<OrderedFloat<f64>>,
 1351                        sort_key: (usize, &'a str),
 1352                    },
 1353                    Weak {
 1354                        score: Reverse<OrderedFloat<f64>>,
 1355                        sort_text: Option<&'a str>,
 1356                        sort_key: (usize, &'a str),
 1357                    },
 1358                }
 1359
 1360                let completion = &completions[mat.candidate_id];
 1361                let sort_key = completion.sort_key();
 1362                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1363                let score = Reverse(OrderedFloat(mat.score));
 1364
 1365                if mat.score >= 0.2 {
 1366                    MatchScore::Strong {
 1367                        sort_text,
 1368                        score,
 1369                        sort_key,
 1370                    }
 1371                } else {
 1372                    MatchScore::Weak {
 1373                        score,
 1374                        sort_text,
 1375                        sort_key,
 1376                    }
 1377                }
 1378            });
 1379        }
 1380
 1381        for mat in &mut matches {
 1382            let completion = &completions[mat.candidate_id];
 1383            mat.string.clone_from(&completion.label.text);
 1384            for position in &mut mat.positions {
 1385                *position += completion.label.filter_range.start;
 1386            }
 1387        }
 1388        drop(completions);
 1389
 1390        self.matches = matches.into();
 1391        self.selected_item = 0;
 1392    }
 1393}
 1394
 1395struct AvailableCodeAction {
 1396    excerpt_id: ExcerptId,
 1397    action: CodeAction,
 1398    provider: Arc<dyn CodeActionProvider>,
 1399}
 1400
 1401#[derive(Clone)]
 1402struct CodeActionContents {
 1403    tasks: Option<Arc<ResolvedTasks>>,
 1404    actions: Option<Arc<[AvailableCodeAction]>>,
 1405}
 1406
 1407impl CodeActionContents {
 1408    fn len(&self) -> usize {
 1409        match (&self.tasks, &self.actions) {
 1410            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1411            (Some(tasks), None) => tasks.templates.len(),
 1412            (None, Some(actions)) => actions.len(),
 1413            (None, None) => 0,
 1414        }
 1415    }
 1416
 1417    fn is_empty(&self) -> bool {
 1418        match (&self.tasks, &self.actions) {
 1419            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1420            (Some(tasks), None) => tasks.templates.is_empty(),
 1421            (None, Some(actions)) => actions.is_empty(),
 1422            (None, None) => true,
 1423        }
 1424    }
 1425
 1426    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1427        self.tasks
 1428            .iter()
 1429            .flat_map(|tasks| {
 1430                tasks
 1431                    .templates
 1432                    .iter()
 1433                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1434            })
 1435            .chain(self.actions.iter().flat_map(|actions| {
 1436                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1437                    excerpt_id: available.excerpt_id,
 1438                    action: available.action.clone(),
 1439                    provider: available.provider.clone(),
 1440                })
 1441            }))
 1442    }
 1443    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1444        match (&self.tasks, &self.actions) {
 1445            (Some(tasks), Some(actions)) => {
 1446                if index < tasks.templates.len() {
 1447                    tasks
 1448                        .templates
 1449                        .get(index)
 1450                        .cloned()
 1451                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1452                } else {
 1453                    actions.get(index - tasks.templates.len()).map(|available| {
 1454                        CodeActionsItem::CodeAction {
 1455                            excerpt_id: available.excerpt_id,
 1456                            action: available.action.clone(),
 1457                            provider: available.provider.clone(),
 1458                        }
 1459                    })
 1460                }
 1461            }
 1462            (Some(tasks), None) => tasks
 1463                .templates
 1464                .get(index)
 1465                .cloned()
 1466                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1467            (None, Some(actions)) => {
 1468                actions
 1469                    .get(index)
 1470                    .map(|available| CodeActionsItem::CodeAction {
 1471                        excerpt_id: available.excerpt_id,
 1472                        action: available.action.clone(),
 1473                        provider: available.provider.clone(),
 1474                    })
 1475            }
 1476            (None, None) => None,
 1477        }
 1478    }
 1479}
 1480
 1481#[allow(clippy::large_enum_variant)]
 1482#[derive(Clone)]
 1483enum CodeActionsItem {
 1484    Task(TaskSourceKind, ResolvedTask),
 1485    CodeAction {
 1486        excerpt_id: ExcerptId,
 1487        action: CodeAction,
 1488        provider: Arc<dyn CodeActionProvider>,
 1489    },
 1490}
 1491
 1492impl CodeActionsItem {
 1493    fn as_task(&self) -> Option<&ResolvedTask> {
 1494        let Self::Task(_, task) = self else {
 1495            return None;
 1496        };
 1497        Some(task)
 1498    }
 1499    fn as_code_action(&self) -> Option<&CodeAction> {
 1500        let Self::CodeAction { action, .. } = self else {
 1501            return None;
 1502        };
 1503        Some(action)
 1504    }
 1505    fn label(&self) -> String {
 1506        match self {
 1507            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1508            Self::Task(_, task) => task.resolved_label.clone(),
 1509        }
 1510    }
 1511}
 1512
 1513struct CodeActionsMenu {
 1514    actions: CodeActionContents,
 1515    buffer: Model<Buffer>,
 1516    selected_item: usize,
 1517    scroll_handle: UniformListScrollHandle,
 1518    deployed_from_indicator: Option<DisplayRow>,
 1519}
 1520
 1521impl CodeActionsMenu {
 1522    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1523        self.selected_item = 0;
 1524        self.scroll_handle.scroll_to_item(self.selected_item);
 1525        cx.notify()
 1526    }
 1527
 1528    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1529        if self.selected_item > 0 {
 1530            self.selected_item -= 1;
 1531        } else {
 1532            self.selected_item = self.actions.len() - 1;
 1533        }
 1534        self.scroll_handle.scroll_to_item(self.selected_item);
 1535        cx.notify();
 1536    }
 1537
 1538    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1539        if self.selected_item + 1 < self.actions.len() {
 1540            self.selected_item += 1;
 1541        } else {
 1542            self.selected_item = 0;
 1543        }
 1544        self.scroll_handle.scroll_to_item(self.selected_item);
 1545        cx.notify();
 1546    }
 1547
 1548    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1549        self.selected_item = self.actions.len() - 1;
 1550        self.scroll_handle.scroll_to_item(self.selected_item);
 1551        cx.notify()
 1552    }
 1553
 1554    fn visible(&self) -> bool {
 1555        !self.actions.is_empty()
 1556    }
 1557
 1558    fn render(
 1559        &self,
 1560        cursor_position: DisplayPoint,
 1561        _style: &EditorStyle,
 1562        max_height: Pixels,
 1563        cx: &mut ViewContext<Editor>,
 1564    ) -> (ContextMenuOrigin, AnyElement) {
 1565        let actions = self.actions.clone();
 1566        let selected_item = self.selected_item;
 1567        let element = uniform_list(
 1568            cx.view().clone(),
 1569            "code_actions_menu",
 1570            self.actions.len(),
 1571            move |_this, range, cx| {
 1572                actions
 1573                    .iter()
 1574                    .skip(range.start)
 1575                    .take(range.end - range.start)
 1576                    .enumerate()
 1577                    .map(|(ix, action)| {
 1578                        let item_ix = range.start + ix;
 1579                        let selected = selected_item == item_ix;
 1580                        let colors = cx.theme().colors();
 1581                        div()
 1582                            .px_1()
 1583                            .rounded_md()
 1584                            .text_color(colors.text)
 1585                            .when(selected, |style| {
 1586                                style
 1587                                    .bg(colors.element_active)
 1588                                    .text_color(colors.text_accent)
 1589                            })
 1590                            .hover(|style| {
 1591                                style
 1592                                    .bg(colors.element_hover)
 1593                                    .text_color(colors.text_accent)
 1594                            })
 1595                            .whitespace_nowrap()
 1596                            .when_some(action.as_code_action(), |this, action| {
 1597                                this.on_mouse_down(
 1598                                    MouseButton::Left,
 1599                                    cx.listener(move |editor, _, cx| {
 1600                                        cx.stop_propagation();
 1601                                        if let Some(task) = editor.confirm_code_action(
 1602                                            &ConfirmCodeAction {
 1603                                                item_ix: Some(item_ix),
 1604                                            },
 1605                                            cx,
 1606                                        ) {
 1607                                            task.detach_and_log_err(cx)
 1608                                        }
 1609                                    }),
 1610                                )
 1611                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1612                                .child(SharedString::from(action.lsp_action.title.clone()))
 1613                            })
 1614                            .when_some(action.as_task(), |this, task| {
 1615                                this.on_mouse_down(
 1616                                    MouseButton::Left,
 1617                                    cx.listener(move |editor, _, cx| {
 1618                                        cx.stop_propagation();
 1619                                        if let Some(task) = editor.confirm_code_action(
 1620                                            &ConfirmCodeAction {
 1621                                                item_ix: Some(item_ix),
 1622                                            },
 1623                                            cx,
 1624                                        ) {
 1625                                            task.detach_and_log_err(cx)
 1626                                        }
 1627                                    }),
 1628                                )
 1629                                .child(SharedString::from(task.resolved_label.clone()))
 1630                            })
 1631                    })
 1632                    .collect()
 1633            },
 1634        )
 1635        .elevation_1(cx)
 1636        .p_1()
 1637        .max_h(max_height)
 1638        .occlude()
 1639        .track_scroll(self.scroll_handle.clone())
 1640        .with_width_from_item(
 1641            self.actions
 1642                .iter()
 1643                .enumerate()
 1644                .max_by_key(|(_, action)| match action {
 1645                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1646                    CodeActionsItem::CodeAction { action, .. } => {
 1647                        action.lsp_action.title.chars().count()
 1648                    }
 1649                })
 1650                .map(|(ix, _)| ix),
 1651        )
 1652        .with_sizing_behavior(ListSizingBehavior::Infer)
 1653        .into_any_element();
 1654
 1655        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1656            ContextMenuOrigin::GutterIndicator(row)
 1657        } else {
 1658            ContextMenuOrigin::EditorPoint(cursor_position)
 1659        };
 1660
 1661        (cursor_position, element)
 1662    }
 1663}
 1664
 1665#[derive(Debug)]
 1666struct ActiveDiagnosticGroup {
 1667    primary_range: Range<Anchor>,
 1668    primary_message: String,
 1669    group_id: usize,
 1670    blocks: HashMap<CustomBlockId, Diagnostic>,
 1671    is_valid: bool,
 1672}
 1673
 1674#[derive(Serialize, Deserialize, Clone, Debug)]
 1675pub struct ClipboardSelection {
 1676    pub len: usize,
 1677    pub is_entire_line: bool,
 1678    pub first_line_indent: u32,
 1679}
 1680
 1681#[derive(Debug)]
 1682pub(crate) struct NavigationData {
 1683    cursor_anchor: Anchor,
 1684    cursor_position: Point,
 1685    scroll_anchor: ScrollAnchor,
 1686    scroll_top_row: u32,
 1687}
 1688
 1689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1690pub enum GotoDefinitionKind {
 1691    Symbol,
 1692    Declaration,
 1693    Type,
 1694    Implementation,
 1695}
 1696
 1697#[derive(Debug, Clone)]
 1698enum InlayHintRefreshReason {
 1699    Toggle(bool),
 1700    SettingsChange(InlayHintSettings),
 1701    NewLinesShown,
 1702    BufferEdited(HashSet<Arc<Language>>),
 1703    RefreshRequested,
 1704    ExcerptsRemoved(Vec<ExcerptId>),
 1705}
 1706
 1707impl InlayHintRefreshReason {
 1708    fn description(&self) -> &'static str {
 1709        match self {
 1710            Self::Toggle(_) => "toggle",
 1711            Self::SettingsChange(_) => "settings change",
 1712            Self::NewLinesShown => "new lines shown",
 1713            Self::BufferEdited(_) => "buffer edited",
 1714            Self::RefreshRequested => "refresh requested",
 1715            Self::ExcerptsRemoved(_) => "excerpts removed",
 1716        }
 1717    }
 1718}
 1719
 1720pub(crate) struct FocusedBlock {
 1721    id: BlockId,
 1722    focus_handle: WeakFocusHandle,
 1723}
 1724
 1725impl Editor {
 1726    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1727        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1728        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1729        Self::new(
 1730            EditorMode::SingleLine { auto_width: false },
 1731            buffer,
 1732            None,
 1733            false,
 1734            cx,
 1735        )
 1736    }
 1737
 1738    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1739        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1740        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1741        Self::new(EditorMode::Full, buffer, None, false, cx)
 1742    }
 1743
 1744    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1745        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1746        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1747        Self::new(
 1748            EditorMode::SingleLine { auto_width: true },
 1749            buffer,
 1750            None,
 1751            false,
 1752            cx,
 1753        )
 1754    }
 1755
 1756    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1757        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1758        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1759        Self::new(
 1760            EditorMode::AutoHeight { max_lines },
 1761            buffer,
 1762            None,
 1763            false,
 1764            cx,
 1765        )
 1766    }
 1767
 1768    pub fn for_buffer(
 1769        buffer: Model<Buffer>,
 1770        project: Option<Model<Project>>,
 1771        cx: &mut ViewContext<Self>,
 1772    ) -> Self {
 1773        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1774        Self::new(EditorMode::Full, buffer, project, false, cx)
 1775    }
 1776
 1777    pub fn for_multibuffer(
 1778        buffer: Model<MultiBuffer>,
 1779        project: Option<Model<Project>>,
 1780        show_excerpt_controls: bool,
 1781        cx: &mut ViewContext<Self>,
 1782    ) -> Self {
 1783        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1784    }
 1785
 1786    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1787        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1788        let mut clone = Self::new(
 1789            self.mode,
 1790            self.buffer.clone(),
 1791            self.project.clone(),
 1792            show_excerpt_controls,
 1793            cx,
 1794        );
 1795        self.display_map.update(cx, |display_map, cx| {
 1796            let snapshot = display_map.snapshot(cx);
 1797            clone.display_map.update(cx, |display_map, cx| {
 1798                display_map.set_state(&snapshot, cx);
 1799            });
 1800        });
 1801        clone.selections.clone_state(&self.selections);
 1802        clone.scroll_manager.clone_state(&self.scroll_manager);
 1803        clone.searchable = self.searchable;
 1804        clone
 1805    }
 1806
 1807    pub fn new(
 1808        mode: EditorMode,
 1809        buffer: Model<MultiBuffer>,
 1810        project: Option<Model<Project>>,
 1811        show_excerpt_controls: bool,
 1812        cx: &mut ViewContext<Self>,
 1813    ) -> Self {
 1814        let style = cx.text_style();
 1815        let font_size = style.font_size.to_pixels(cx.rem_size());
 1816        let editor = cx.view().downgrade();
 1817        let fold_placeholder = FoldPlaceholder {
 1818            constrain_width: true,
 1819            render: Arc::new(move |fold_id, fold_range, cx| {
 1820                let editor = editor.clone();
 1821                div()
 1822                    .id(fold_id)
 1823                    .bg(cx.theme().colors().ghost_element_background)
 1824                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1825                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1826                    .rounded_sm()
 1827                    .size_full()
 1828                    .cursor_pointer()
 1829                    .child("")
 1830                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1831                    .on_click(move |_, cx| {
 1832                        editor
 1833                            .update(cx, |editor, cx| {
 1834                                editor.unfold_ranges(
 1835                                    [fold_range.start..fold_range.end],
 1836                                    true,
 1837                                    false,
 1838                                    cx,
 1839                                );
 1840                                cx.stop_propagation();
 1841                            })
 1842                            .ok();
 1843                    })
 1844                    .into_any()
 1845            }),
 1846            merge_adjacent: true,
 1847        };
 1848        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1849        let display_map = cx.new_model(|cx| {
 1850            DisplayMap::new(
 1851                buffer.clone(),
 1852                style.font(),
 1853                font_size,
 1854                None,
 1855                show_excerpt_controls,
 1856                file_header_size,
 1857                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1858                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1859                fold_placeholder,
 1860                cx,
 1861            )
 1862        });
 1863
 1864        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1865
 1866        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1867
 1868        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1869            .then(|| language_settings::SoftWrap::None);
 1870
 1871        let mut project_subscriptions = Vec::new();
 1872        if mode == EditorMode::Full {
 1873            if let Some(project) = project.as_ref() {
 1874                if buffer.read(cx).is_singleton() {
 1875                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1876                        cx.emit(EditorEvent::TitleChanged);
 1877                    }));
 1878                }
 1879                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1880                    if let project::Event::RefreshInlayHints = event {
 1881                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1882                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1883                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1884                            let focus_handle = editor.focus_handle(cx);
 1885                            if focus_handle.is_focused(cx) {
 1886                                let snapshot = buffer.read(cx).snapshot();
 1887                                for (range, snippet) in snippet_edits {
 1888                                    let editor_range =
 1889                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1890                                    editor
 1891                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1892                                        .ok();
 1893                                }
 1894                            }
 1895                        }
 1896                    }
 1897                }));
 1898                if let Some(task_inventory) = project
 1899                    .read(cx)
 1900                    .task_store()
 1901                    .read(cx)
 1902                    .task_inventory()
 1903                    .cloned()
 1904                {
 1905                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1906                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1907                    }));
 1908                }
 1909            }
 1910        }
 1911
 1912        let inlay_hint_settings = inlay_hint_settings(
 1913            selections.newest_anchor().head(),
 1914            &buffer.read(cx).snapshot(cx),
 1915            cx,
 1916        );
 1917        let focus_handle = cx.focus_handle();
 1918        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1919        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1920            .detach();
 1921        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1922            .detach();
 1923        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1924
 1925        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1926            Some(false)
 1927        } else {
 1928            None
 1929        };
 1930
 1931        let mut code_action_providers = Vec::new();
 1932        if let Some(project) = project.clone() {
 1933            code_action_providers.push(Arc::new(project) as Arc<_>);
 1934        }
 1935
 1936        let mut this = Self {
 1937            focus_handle,
 1938            show_cursor_when_unfocused: false,
 1939            last_focused_descendant: None,
 1940            buffer: buffer.clone(),
 1941            display_map: display_map.clone(),
 1942            selections,
 1943            scroll_manager: ScrollManager::new(cx),
 1944            columnar_selection_tail: None,
 1945            add_selections_state: None,
 1946            select_next_state: None,
 1947            select_prev_state: None,
 1948            selection_history: Default::default(),
 1949            autoclose_regions: Default::default(),
 1950            snippet_stack: Default::default(),
 1951            select_larger_syntax_node_stack: Vec::new(),
 1952            ime_transaction: Default::default(),
 1953            active_diagnostics: None,
 1954            soft_wrap_mode_override,
 1955            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1956            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1957            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1958            project,
 1959            blink_manager: blink_manager.clone(),
 1960            show_local_selections: true,
 1961            mode,
 1962            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1963            show_gutter: mode == EditorMode::Full,
 1964            show_line_numbers: None,
 1965            use_relative_line_numbers: None,
 1966            show_git_diff_gutter: None,
 1967            show_code_actions: None,
 1968            show_runnables: None,
 1969            show_wrap_guides: None,
 1970            show_indent_guides,
 1971            placeholder_text: None,
 1972            highlight_order: 0,
 1973            highlighted_rows: HashMap::default(),
 1974            background_highlights: Default::default(),
 1975            gutter_highlights: TreeMap::default(),
 1976            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1977            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1978            nav_history: None,
 1979            context_menu: RwLock::new(None),
 1980            mouse_context_menu: None,
 1981            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1982            completion_tasks: Default::default(),
 1983            signature_help_state: SignatureHelpState::default(),
 1984            auto_signature_help: None,
 1985            find_all_references_task_sources: Vec::new(),
 1986            next_completion_id: 0,
 1987            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1988            next_inlay_id: 0,
 1989            code_action_providers,
 1990            available_code_actions: Default::default(),
 1991            code_actions_task: Default::default(),
 1992            document_highlights_task: Default::default(),
 1993            linked_editing_range_task: Default::default(),
 1994            pending_rename: Default::default(),
 1995            searchable: true,
 1996            cursor_shape: EditorSettings::get_global(cx)
 1997                .cursor_shape
 1998                .unwrap_or_default(),
 1999            current_line_highlight: None,
 2000            autoindent_mode: Some(AutoindentMode::EachLine),
 2001            collapse_matches: false,
 2002            workspace: None,
 2003            input_enabled: true,
 2004            use_modal_editing: mode == EditorMode::Full,
 2005            read_only: false,
 2006            use_autoclose: true,
 2007            use_auto_surround: true,
 2008            auto_replace_emoji_shortcode: false,
 2009            leader_peer_id: None,
 2010            remote_id: None,
 2011            hover_state: Default::default(),
 2012            hovered_link_state: Default::default(),
 2013            inline_completion_provider: None,
 2014            active_inline_completion: None,
 2015            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2016            expanded_hunks: ExpandedHunks::default(),
 2017            gutter_hovered: false,
 2018            pixel_position_of_newest_cursor: None,
 2019            last_bounds: None,
 2020            expect_bounds_change: None,
 2021            gutter_dimensions: GutterDimensions::default(),
 2022            style: None,
 2023            show_cursor_names: false,
 2024            hovered_cursors: Default::default(),
 2025            next_editor_action_id: EditorActionId::default(),
 2026            editor_actions: Rc::default(),
 2027            show_inline_completions_override: None,
 2028            enable_inline_completions: true,
 2029            custom_context_menu: None,
 2030            show_git_blame_gutter: false,
 2031            show_git_blame_inline: false,
 2032            show_selection_menu: None,
 2033            show_git_blame_inline_delay_task: None,
 2034            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2035            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2036                .session
 2037                .restore_unsaved_buffers,
 2038            blame: None,
 2039            blame_subscription: None,
 2040            file_header_size,
 2041            tasks: Default::default(),
 2042            _subscriptions: vec![
 2043                cx.observe(&buffer, Self::on_buffer_changed),
 2044                cx.subscribe(&buffer, Self::on_buffer_event),
 2045                cx.observe(&display_map, Self::on_display_map_changed),
 2046                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2047                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2048                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2049                cx.observe_window_activation(|editor, cx| {
 2050                    let active = cx.is_window_active();
 2051                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2052                        if active {
 2053                            blink_manager.enable(cx);
 2054                        } else {
 2055                            blink_manager.disable(cx);
 2056                        }
 2057                    });
 2058                }),
 2059            ],
 2060            tasks_update_task: None,
 2061            linked_edit_ranges: Default::default(),
 2062            previous_search_ranges: None,
 2063            breadcrumb_header: None,
 2064            focused_block: None,
 2065            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2066            addons: HashMap::default(),
 2067            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2068        };
 2069        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2070        this._subscriptions.extend(project_subscriptions);
 2071
 2072        this.end_selection(cx);
 2073        this.scroll_manager.show_scrollbar(cx);
 2074
 2075        if mode == EditorMode::Full {
 2076            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2077            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2078
 2079            if this.git_blame_inline_enabled {
 2080                this.git_blame_inline_enabled = true;
 2081                this.start_git_blame_inline(false, cx);
 2082            }
 2083        }
 2084
 2085        this.report_editor_event("open", None, cx);
 2086        this
 2087    }
 2088
 2089    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2090        self.mouse_context_menu
 2091            .as_ref()
 2092            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2093    }
 2094
 2095    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2096        let mut key_context = KeyContext::new_with_defaults();
 2097        key_context.add("Editor");
 2098        let mode = match self.mode {
 2099            EditorMode::SingleLine { .. } => "single_line",
 2100            EditorMode::AutoHeight { .. } => "auto_height",
 2101            EditorMode::Full => "full",
 2102        };
 2103
 2104        if EditorSettings::jupyter_enabled(cx) {
 2105            key_context.add("jupyter");
 2106        }
 2107
 2108        key_context.set("mode", mode);
 2109        if self.pending_rename.is_some() {
 2110            key_context.add("renaming");
 2111        }
 2112        if self.context_menu_visible() {
 2113            match self.context_menu.read().as_ref() {
 2114                Some(ContextMenu::Completions(_)) => {
 2115                    key_context.add("menu");
 2116                    key_context.add("showing_completions")
 2117                }
 2118                Some(ContextMenu::CodeActions(_)) => {
 2119                    key_context.add("menu");
 2120                    key_context.add("showing_code_actions")
 2121                }
 2122                None => {}
 2123            }
 2124        }
 2125
 2126        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2127        if !self.focus_handle(cx).contains_focused(cx)
 2128            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2129        {
 2130            for addon in self.addons.values() {
 2131                addon.extend_key_context(&mut key_context, cx)
 2132            }
 2133        }
 2134
 2135        if let Some(extension) = self
 2136            .buffer
 2137            .read(cx)
 2138            .as_singleton()
 2139            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2140        {
 2141            key_context.set("extension", extension.to_string());
 2142        }
 2143
 2144        if self.has_active_inline_completion(cx) {
 2145            key_context.add("copilot_suggestion");
 2146            key_context.add("inline_completion");
 2147        }
 2148
 2149        key_context
 2150    }
 2151
 2152    pub fn new_file(
 2153        workspace: &mut Workspace,
 2154        _: &workspace::NewFile,
 2155        cx: &mut ViewContext<Workspace>,
 2156    ) {
 2157        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2158            "Failed to create buffer",
 2159            cx,
 2160            |e, _| match e.error_code() {
 2161                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2162                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2163                e.error_tag("required").unwrap_or("the latest version")
 2164            )),
 2165                _ => None,
 2166            },
 2167        );
 2168    }
 2169
 2170    pub fn new_in_workspace(
 2171        workspace: &mut Workspace,
 2172        cx: &mut ViewContext<Workspace>,
 2173    ) -> Task<Result<View<Editor>>> {
 2174        let project = workspace.project().clone();
 2175        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2176
 2177        cx.spawn(|workspace, mut cx| async move {
 2178            let buffer = create.await?;
 2179            workspace.update(&mut cx, |workspace, cx| {
 2180                let editor =
 2181                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2182                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2183                editor
 2184            })
 2185        })
 2186    }
 2187
 2188    fn new_file_vertical(
 2189        workspace: &mut Workspace,
 2190        _: &workspace::NewFileSplitVertical,
 2191        cx: &mut ViewContext<Workspace>,
 2192    ) {
 2193        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2194    }
 2195
 2196    fn new_file_horizontal(
 2197        workspace: &mut Workspace,
 2198        _: &workspace::NewFileSplitHorizontal,
 2199        cx: &mut ViewContext<Workspace>,
 2200    ) {
 2201        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2202    }
 2203
 2204    fn new_file_in_direction(
 2205        workspace: &mut Workspace,
 2206        direction: SplitDirection,
 2207        cx: &mut ViewContext<Workspace>,
 2208    ) {
 2209        let project = workspace.project().clone();
 2210        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2211
 2212        cx.spawn(|workspace, mut cx| async move {
 2213            let buffer = create.await?;
 2214            workspace.update(&mut cx, move |workspace, cx| {
 2215                workspace.split_item(
 2216                    direction,
 2217                    Box::new(
 2218                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2219                    ),
 2220                    cx,
 2221                )
 2222            })?;
 2223            anyhow::Ok(())
 2224        })
 2225        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2226            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2227                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2228                e.error_tag("required").unwrap_or("the latest version")
 2229            )),
 2230            _ => None,
 2231        });
 2232    }
 2233
 2234    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2235        self.leader_peer_id
 2236    }
 2237
 2238    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2239        &self.buffer
 2240    }
 2241
 2242    pub fn workspace(&self) -> Option<View<Workspace>> {
 2243        self.workspace.as_ref()?.0.upgrade()
 2244    }
 2245
 2246    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2247        self.buffer().read(cx).title(cx)
 2248    }
 2249
 2250    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2251        let git_blame_gutter_max_author_length = self
 2252            .render_git_blame_gutter(cx)
 2253            .then(|| {
 2254                if let Some(blame) = self.blame.as_ref() {
 2255                    let max_author_length =
 2256                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2257                    Some(max_author_length)
 2258                } else {
 2259                    None
 2260                }
 2261            })
 2262            .flatten();
 2263
 2264        EditorSnapshot {
 2265            mode: self.mode,
 2266            show_gutter: self.show_gutter,
 2267            show_line_numbers: self.show_line_numbers,
 2268            show_git_diff_gutter: self.show_git_diff_gutter,
 2269            show_code_actions: self.show_code_actions,
 2270            show_runnables: self.show_runnables,
 2271            git_blame_gutter_max_author_length,
 2272            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2273            scroll_anchor: self.scroll_manager.anchor(),
 2274            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2275            placeholder_text: self.placeholder_text.clone(),
 2276            is_focused: self.focus_handle.is_focused(cx),
 2277            current_line_highlight: self
 2278                .current_line_highlight
 2279                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2280            gutter_hovered: self.gutter_hovered,
 2281        }
 2282    }
 2283
 2284    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2285        self.buffer.read(cx).language_at(point, cx)
 2286    }
 2287
 2288    pub fn file_at<T: ToOffset>(
 2289        &self,
 2290        point: T,
 2291        cx: &AppContext,
 2292    ) -> Option<Arc<dyn language::File>> {
 2293        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2294    }
 2295
 2296    pub fn active_excerpt(
 2297        &self,
 2298        cx: &AppContext,
 2299    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2300        self.buffer
 2301            .read(cx)
 2302            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2303    }
 2304
 2305    pub fn mode(&self) -> EditorMode {
 2306        self.mode
 2307    }
 2308
 2309    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2310        self.collaboration_hub.as_deref()
 2311    }
 2312
 2313    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2314        self.collaboration_hub = Some(hub);
 2315    }
 2316
 2317    pub fn set_custom_context_menu(
 2318        &mut self,
 2319        f: impl 'static
 2320            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2321    ) {
 2322        self.custom_context_menu = Some(Box::new(f))
 2323    }
 2324
 2325    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2326        self.completion_provider = provider;
 2327    }
 2328
 2329    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2330        self.semantics_provider.clone()
 2331    }
 2332
 2333    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2334        self.semantics_provider = provider;
 2335    }
 2336
 2337    pub fn set_inline_completion_provider<T>(
 2338        &mut self,
 2339        provider: Option<Model<T>>,
 2340        cx: &mut ViewContext<Self>,
 2341    ) where
 2342        T: InlineCompletionProvider,
 2343    {
 2344        self.inline_completion_provider =
 2345            provider.map(|provider| RegisteredInlineCompletionProvider {
 2346                _subscription: cx.observe(&provider, |this, _, cx| {
 2347                    if this.focus_handle.is_focused(cx) {
 2348                        this.update_visible_inline_completion(cx);
 2349                    }
 2350                }),
 2351                provider: Arc::new(provider),
 2352            });
 2353        self.refresh_inline_completion(false, false, cx);
 2354    }
 2355
 2356    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2357        self.placeholder_text.as_deref()
 2358    }
 2359
 2360    pub fn set_placeholder_text(
 2361        &mut self,
 2362        placeholder_text: impl Into<Arc<str>>,
 2363        cx: &mut ViewContext<Self>,
 2364    ) {
 2365        let placeholder_text = Some(placeholder_text.into());
 2366        if self.placeholder_text != placeholder_text {
 2367            self.placeholder_text = placeholder_text;
 2368            cx.notify();
 2369        }
 2370    }
 2371
 2372    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2373        self.cursor_shape = cursor_shape;
 2374
 2375        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2376        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2377
 2378        cx.notify();
 2379    }
 2380
 2381    pub fn set_current_line_highlight(
 2382        &mut self,
 2383        current_line_highlight: Option<CurrentLineHighlight>,
 2384    ) {
 2385        self.current_line_highlight = current_line_highlight;
 2386    }
 2387
 2388    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2389        self.collapse_matches = collapse_matches;
 2390    }
 2391
 2392    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2393        if self.collapse_matches {
 2394            return range.start..range.start;
 2395        }
 2396        range.clone()
 2397    }
 2398
 2399    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2400        if self.display_map.read(cx).clip_at_line_ends != clip {
 2401            self.display_map
 2402                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2403        }
 2404    }
 2405
 2406    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2407        self.input_enabled = input_enabled;
 2408    }
 2409
 2410    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2411        self.enable_inline_completions = enabled;
 2412    }
 2413
 2414    pub fn set_autoindent(&mut self, autoindent: bool) {
 2415        if autoindent {
 2416            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2417        } else {
 2418            self.autoindent_mode = None;
 2419        }
 2420    }
 2421
 2422    pub fn read_only(&self, cx: &AppContext) -> bool {
 2423        self.read_only || self.buffer.read(cx).read_only()
 2424    }
 2425
 2426    pub fn set_read_only(&mut self, read_only: bool) {
 2427        self.read_only = read_only;
 2428    }
 2429
 2430    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2431        self.use_autoclose = autoclose;
 2432    }
 2433
 2434    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2435        self.use_auto_surround = auto_surround;
 2436    }
 2437
 2438    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2439        self.auto_replace_emoji_shortcode = auto_replace;
 2440    }
 2441
 2442    pub fn toggle_inline_completions(
 2443        &mut self,
 2444        _: &ToggleInlineCompletions,
 2445        cx: &mut ViewContext<Self>,
 2446    ) {
 2447        if self.show_inline_completions_override.is_some() {
 2448            self.set_show_inline_completions(None, cx);
 2449        } else {
 2450            let cursor = self.selections.newest_anchor().head();
 2451            if let Some((buffer, cursor_buffer_position)) =
 2452                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2453            {
 2454                let show_inline_completions =
 2455                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2456                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2457            }
 2458        }
 2459    }
 2460
 2461    pub fn set_show_inline_completions(
 2462        &mut self,
 2463        show_inline_completions: Option<bool>,
 2464        cx: &mut ViewContext<Self>,
 2465    ) {
 2466        self.show_inline_completions_override = show_inline_completions;
 2467        self.refresh_inline_completion(false, true, cx);
 2468    }
 2469
 2470    fn should_show_inline_completions(
 2471        &self,
 2472        buffer: &Model<Buffer>,
 2473        buffer_position: language::Anchor,
 2474        cx: &AppContext,
 2475    ) -> bool {
 2476        if let Some(provider) = self.inline_completion_provider() {
 2477            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2478                show_inline_completions
 2479            } else {
 2480                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2481            }
 2482        } else {
 2483            false
 2484        }
 2485    }
 2486
 2487    pub fn set_use_modal_editing(&mut self, to: bool) {
 2488        self.use_modal_editing = to;
 2489    }
 2490
 2491    pub fn use_modal_editing(&self) -> bool {
 2492        self.use_modal_editing
 2493    }
 2494
 2495    fn selections_did_change(
 2496        &mut self,
 2497        local: bool,
 2498        old_cursor_position: &Anchor,
 2499        show_completions: bool,
 2500        cx: &mut ViewContext<Self>,
 2501    ) {
 2502        cx.invalidate_character_coordinates();
 2503
 2504        // Copy selections to primary selection buffer
 2505        #[cfg(target_os = "linux")]
 2506        if local {
 2507            let selections = self.selections.all::<usize>(cx);
 2508            let buffer_handle = self.buffer.read(cx).read(cx);
 2509
 2510            let mut text = String::new();
 2511            for (index, selection) in selections.iter().enumerate() {
 2512                let text_for_selection = buffer_handle
 2513                    .text_for_range(selection.start..selection.end)
 2514                    .collect::<String>();
 2515
 2516                text.push_str(&text_for_selection);
 2517                if index != selections.len() - 1 {
 2518                    text.push('\n');
 2519                }
 2520            }
 2521
 2522            if !text.is_empty() {
 2523                cx.write_to_primary(ClipboardItem::new_string(text));
 2524            }
 2525        }
 2526
 2527        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2528            self.buffer.update(cx, |buffer, cx| {
 2529                buffer.set_active_selections(
 2530                    &self.selections.disjoint_anchors(),
 2531                    self.selections.line_mode,
 2532                    self.cursor_shape,
 2533                    cx,
 2534                )
 2535            });
 2536        }
 2537        let display_map = self
 2538            .display_map
 2539            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2540        let buffer = &display_map.buffer_snapshot;
 2541        self.add_selections_state = None;
 2542        self.select_next_state = None;
 2543        self.select_prev_state = None;
 2544        self.select_larger_syntax_node_stack.clear();
 2545        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2546        self.snippet_stack
 2547            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2548        self.take_rename(false, cx);
 2549
 2550        let new_cursor_position = self.selections.newest_anchor().head();
 2551
 2552        self.push_to_nav_history(
 2553            *old_cursor_position,
 2554            Some(new_cursor_position.to_point(buffer)),
 2555            cx,
 2556        );
 2557
 2558        if local {
 2559            let new_cursor_position = self.selections.newest_anchor().head();
 2560            let mut context_menu = self.context_menu.write();
 2561            let completion_menu = match context_menu.as_ref() {
 2562                Some(ContextMenu::Completions(menu)) => Some(menu),
 2563
 2564                _ => {
 2565                    *context_menu = None;
 2566                    None
 2567                }
 2568            };
 2569
 2570            if let Some(completion_menu) = completion_menu {
 2571                let cursor_position = new_cursor_position.to_offset(buffer);
 2572                let (word_range, kind) =
 2573                    buffer.surrounding_word(completion_menu.initial_position, true);
 2574                if kind == Some(CharKind::Word)
 2575                    && word_range.to_inclusive().contains(&cursor_position)
 2576                {
 2577                    let mut completion_menu = completion_menu.clone();
 2578                    drop(context_menu);
 2579
 2580                    let query = Self::completion_query(buffer, cursor_position);
 2581                    cx.spawn(move |this, mut cx| async move {
 2582                        completion_menu
 2583                            .filter(query.as_deref(), cx.background_executor().clone())
 2584                            .await;
 2585
 2586                        this.update(&mut cx, |this, cx| {
 2587                            let mut context_menu = this.context_menu.write();
 2588                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2589                                return;
 2590                            };
 2591
 2592                            if menu.id > completion_menu.id {
 2593                                return;
 2594                            }
 2595
 2596                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2597                            drop(context_menu);
 2598                            cx.notify();
 2599                        })
 2600                    })
 2601                    .detach();
 2602
 2603                    if show_completions {
 2604                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2605                    }
 2606                } else {
 2607                    drop(context_menu);
 2608                    self.hide_context_menu(cx);
 2609                }
 2610            } else {
 2611                drop(context_menu);
 2612            }
 2613
 2614            hide_hover(self, cx);
 2615
 2616            if old_cursor_position.to_display_point(&display_map).row()
 2617                != new_cursor_position.to_display_point(&display_map).row()
 2618            {
 2619                self.available_code_actions.take();
 2620            }
 2621            self.refresh_code_actions(cx);
 2622            self.refresh_document_highlights(cx);
 2623            refresh_matching_bracket_highlights(self, cx);
 2624            self.discard_inline_completion(false, cx);
 2625            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2626            if self.git_blame_inline_enabled {
 2627                self.start_inline_blame_timer(cx);
 2628            }
 2629        }
 2630
 2631        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2632        cx.emit(EditorEvent::SelectionsChanged { local });
 2633
 2634        if self.selections.disjoint_anchors().len() == 1 {
 2635            cx.emit(SearchEvent::ActiveMatchChanged)
 2636        }
 2637        cx.notify();
 2638    }
 2639
 2640    pub fn change_selections<R>(
 2641        &mut self,
 2642        autoscroll: Option<Autoscroll>,
 2643        cx: &mut ViewContext<Self>,
 2644        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2645    ) -> R {
 2646        self.change_selections_inner(autoscroll, true, cx, change)
 2647    }
 2648
 2649    pub fn change_selections_inner<R>(
 2650        &mut self,
 2651        autoscroll: Option<Autoscroll>,
 2652        request_completions: bool,
 2653        cx: &mut ViewContext<Self>,
 2654        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2655    ) -> R {
 2656        let old_cursor_position = self.selections.newest_anchor().head();
 2657        self.push_to_selection_history();
 2658
 2659        let (changed, result) = self.selections.change_with(cx, change);
 2660
 2661        if changed {
 2662            if let Some(autoscroll) = autoscroll {
 2663                self.request_autoscroll(autoscroll, cx);
 2664            }
 2665            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2666
 2667            if self.should_open_signature_help_automatically(
 2668                &old_cursor_position,
 2669                self.signature_help_state.backspace_pressed(),
 2670                cx,
 2671            ) {
 2672                self.show_signature_help(&ShowSignatureHelp, cx);
 2673            }
 2674            self.signature_help_state.set_backspace_pressed(false);
 2675        }
 2676
 2677        result
 2678    }
 2679
 2680    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2681    where
 2682        I: IntoIterator<Item = (Range<S>, T)>,
 2683        S: ToOffset,
 2684        T: Into<Arc<str>>,
 2685    {
 2686        if self.read_only(cx) {
 2687            return;
 2688        }
 2689
 2690        self.buffer
 2691            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2692    }
 2693
 2694    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2695    where
 2696        I: IntoIterator<Item = (Range<S>, T)>,
 2697        S: ToOffset,
 2698        T: Into<Arc<str>>,
 2699    {
 2700        if self.read_only(cx) {
 2701            return;
 2702        }
 2703
 2704        self.buffer.update(cx, |buffer, cx| {
 2705            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2706        });
 2707    }
 2708
 2709    pub fn edit_with_block_indent<I, S, T>(
 2710        &mut self,
 2711        edits: I,
 2712        original_indent_columns: Vec<u32>,
 2713        cx: &mut ViewContext<Self>,
 2714    ) where
 2715        I: IntoIterator<Item = (Range<S>, T)>,
 2716        S: ToOffset,
 2717        T: Into<Arc<str>>,
 2718    {
 2719        if self.read_only(cx) {
 2720            return;
 2721        }
 2722
 2723        self.buffer.update(cx, |buffer, cx| {
 2724            buffer.edit(
 2725                edits,
 2726                Some(AutoindentMode::Block {
 2727                    original_indent_columns,
 2728                }),
 2729                cx,
 2730            )
 2731        });
 2732    }
 2733
 2734    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2735        self.hide_context_menu(cx);
 2736
 2737        match phase {
 2738            SelectPhase::Begin {
 2739                position,
 2740                add,
 2741                click_count,
 2742            } => self.begin_selection(position, add, click_count, cx),
 2743            SelectPhase::BeginColumnar {
 2744                position,
 2745                goal_column,
 2746                reset,
 2747            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2748            SelectPhase::Extend {
 2749                position,
 2750                click_count,
 2751            } => self.extend_selection(position, click_count, cx),
 2752            SelectPhase::Update {
 2753                position,
 2754                goal_column,
 2755                scroll_delta,
 2756            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2757            SelectPhase::End => self.end_selection(cx),
 2758        }
 2759    }
 2760
 2761    fn extend_selection(
 2762        &mut self,
 2763        position: DisplayPoint,
 2764        click_count: usize,
 2765        cx: &mut ViewContext<Self>,
 2766    ) {
 2767        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2768        let tail = self.selections.newest::<usize>(cx).tail();
 2769        self.begin_selection(position, false, click_count, cx);
 2770
 2771        let position = position.to_offset(&display_map, Bias::Left);
 2772        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2773
 2774        let mut pending_selection = self
 2775            .selections
 2776            .pending_anchor()
 2777            .expect("extend_selection not called with pending selection");
 2778        if position >= tail {
 2779            pending_selection.start = tail_anchor;
 2780        } else {
 2781            pending_selection.end = tail_anchor;
 2782            pending_selection.reversed = true;
 2783        }
 2784
 2785        let mut pending_mode = self.selections.pending_mode().unwrap();
 2786        match &mut pending_mode {
 2787            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2788            _ => {}
 2789        }
 2790
 2791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2792            s.set_pending(pending_selection, pending_mode)
 2793        });
 2794    }
 2795
 2796    fn begin_selection(
 2797        &mut self,
 2798        position: DisplayPoint,
 2799        add: bool,
 2800        click_count: usize,
 2801        cx: &mut ViewContext<Self>,
 2802    ) {
 2803        if !self.focus_handle.is_focused(cx) {
 2804            self.last_focused_descendant = None;
 2805            cx.focus(&self.focus_handle);
 2806        }
 2807
 2808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2809        let buffer = &display_map.buffer_snapshot;
 2810        let newest_selection = self.selections.newest_anchor().clone();
 2811        let position = display_map.clip_point(position, Bias::Left);
 2812
 2813        let start;
 2814        let end;
 2815        let mode;
 2816        let auto_scroll;
 2817        match click_count {
 2818            1 => {
 2819                start = buffer.anchor_before(position.to_point(&display_map));
 2820                end = start;
 2821                mode = SelectMode::Character;
 2822                auto_scroll = true;
 2823            }
 2824            2 => {
 2825                let range = movement::surrounding_word(&display_map, position);
 2826                start = buffer.anchor_before(range.start.to_point(&display_map));
 2827                end = buffer.anchor_before(range.end.to_point(&display_map));
 2828                mode = SelectMode::Word(start..end);
 2829                auto_scroll = true;
 2830            }
 2831            3 => {
 2832                let position = display_map
 2833                    .clip_point(position, Bias::Left)
 2834                    .to_point(&display_map);
 2835                let line_start = display_map.prev_line_boundary(position).0;
 2836                let next_line_start = buffer.clip_point(
 2837                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2838                    Bias::Left,
 2839                );
 2840                start = buffer.anchor_before(line_start);
 2841                end = buffer.anchor_before(next_line_start);
 2842                mode = SelectMode::Line(start..end);
 2843                auto_scroll = true;
 2844            }
 2845            _ => {
 2846                start = buffer.anchor_before(0);
 2847                end = buffer.anchor_before(buffer.len());
 2848                mode = SelectMode::All;
 2849                auto_scroll = false;
 2850            }
 2851        }
 2852
 2853        let point_to_delete: Option<usize> = {
 2854            let selected_points: Vec<Selection<Point>> =
 2855                self.selections.disjoint_in_range(start..end, cx);
 2856
 2857            if !add || click_count > 1 {
 2858                None
 2859            } else if !selected_points.is_empty() {
 2860                Some(selected_points[0].id)
 2861            } else {
 2862                let clicked_point_already_selected =
 2863                    self.selections.disjoint.iter().find(|selection| {
 2864                        selection.start.to_point(buffer) == start.to_point(buffer)
 2865                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2866                    });
 2867
 2868                clicked_point_already_selected.map(|selection| selection.id)
 2869            }
 2870        };
 2871
 2872        let selections_count = self.selections.count();
 2873
 2874        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2875            if let Some(point_to_delete) = point_to_delete {
 2876                s.delete(point_to_delete);
 2877
 2878                if selections_count == 1 {
 2879                    s.set_pending_anchor_range(start..end, mode);
 2880                }
 2881            } else {
 2882                if !add {
 2883                    s.clear_disjoint();
 2884                } else if click_count > 1 {
 2885                    s.delete(newest_selection.id)
 2886                }
 2887
 2888                s.set_pending_anchor_range(start..end, mode);
 2889            }
 2890        });
 2891    }
 2892
 2893    fn begin_columnar_selection(
 2894        &mut self,
 2895        position: DisplayPoint,
 2896        goal_column: u32,
 2897        reset: bool,
 2898        cx: &mut ViewContext<Self>,
 2899    ) {
 2900        if !self.focus_handle.is_focused(cx) {
 2901            self.last_focused_descendant = None;
 2902            cx.focus(&self.focus_handle);
 2903        }
 2904
 2905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2906
 2907        if reset {
 2908            let pointer_position = display_map
 2909                .buffer_snapshot
 2910                .anchor_before(position.to_point(&display_map));
 2911
 2912            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2913                s.clear_disjoint();
 2914                s.set_pending_anchor_range(
 2915                    pointer_position..pointer_position,
 2916                    SelectMode::Character,
 2917                );
 2918            });
 2919        }
 2920
 2921        let tail = self.selections.newest::<Point>(cx).tail();
 2922        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2923
 2924        if !reset {
 2925            self.select_columns(
 2926                tail.to_display_point(&display_map),
 2927                position,
 2928                goal_column,
 2929                &display_map,
 2930                cx,
 2931            );
 2932        }
 2933    }
 2934
 2935    fn update_selection(
 2936        &mut self,
 2937        position: DisplayPoint,
 2938        goal_column: u32,
 2939        scroll_delta: gpui::Point<f32>,
 2940        cx: &mut ViewContext<Self>,
 2941    ) {
 2942        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2943
 2944        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2945            let tail = tail.to_display_point(&display_map);
 2946            self.select_columns(tail, position, goal_column, &display_map, cx);
 2947        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2948            let buffer = self.buffer.read(cx).snapshot(cx);
 2949            let head;
 2950            let tail;
 2951            let mode = self.selections.pending_mode().unwrap();
 2952            match &mode {
 2953                SelectMode::Character => {
 2954                    head = position.to_point(&display_map);
 2955                    tail = pending.tail().to_point(&buffer);
 2956                }
 2957                SelectMode::Word(original_range) => {
 2958                    let original_display_range = original_range.start.to_display_point(&display_map)
 2959                        ..original_range.end.to_display_point(&display_map);
 2960                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2961                        ..original_display_range.end.to_point(&display_map);
 2962                    if movement::is_inside_word(&display_map, position)
 2963                        || original_display_range.contains(&position)
 2964                    {
 2965                        let word_range = movement::surrounding_word(&display_map, position);
 2966                        if word_range.start < original_display_range.start {
 2967                            head = word_range.start.to_point(&display_map);
 2968                        } else {
 2969                            head = word_range.end.to_point(&display_map);
 2970                        }
 2971                    } else {
 2972                        head = position.to_point(&display_map);
 2973                    }
 2974
 2975                    if head <= original_buffer_range.start {
 2976                        tail = original_buffer_range.end;
 2977                    } else {
 2978                        tail = original_buffer_range.start;
 2979                    }
 2980                }
 2981                SelectMode::Line(original_range) => {
 2982                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2983
 2984                    let position = display_map
 2985                        .clip_point(position, Bias::Left)
 2986                        .to_point(&display_map);
 2987                    let line_start = display_map.prev_line_boundary(position).0;
 2988                    let next_line_start = buffer.clip_point(
 2989                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2990                        Bias::Left,
 2991                    );
 2992
 2993                    if line_start < original_range.start {
 2994                        head = line_start
 2995                    } else {
 2996                        head = next_line_start
 2997                    }
 2998
 2999                    if head <= original_range.start {
 3000                        tail = original_range.end;
 3001                    } else {
 3002                        tail = original_range.start;
 3003                    }
 3004                }
 3005                SelectMode::All => {
 3006                    return;
 3007                }
 3008            };
 3009
 3010            if head < tail {
 3011                pending.start = buffer.anchor_before(head);
 3012                pending.end = buffer.anchor_before(tail);
 3013                pending.reversed = true;
 3014            } else {
 3015                pending.start = buffer.anchor_before(tail);
 3016                pending.end = buffer.anchor_before(head);
 3017                pending.reversed = false;
 3018            }
 3019
 3020            self.change_selections(None, cx, |s| {
 3021                s.set_pending(pending, mode);
 3022            });
 3023        } else {
 3024            log::error!("update_selection dispatched with no pending selection");
 3025            return;
 3026        }
 3027
 3028        self.apply_scroll_delta(scroll_delta, cx);
 3029        cx.notify();
 3030    }
 3031
 3032    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3033        self.columnar_selection_tail.take();
 3034        if self.selections.pending_anchor().is_some() {
 3035            let selections = self.selections.all::<usize>(cx);
 3036            self.change_selections(None, cx, |s| {
 3037                s.select(selections);
 3038                s.clear_pending();
 3039            });
 3040        }
 3041    }
 3042
 3043    fn select_columns(
 3044        &mut self,
 3045        tail: DisplayPoint,
 3046        head: DisplayPoint,
 3047        goal_column: u32,
 3048        display_map: &DisplaySnapshot,
 3049        cx: &mut ViewContext<Self>,
 3050    ) {
 3051        let start_row = cmp::min(tail.row(), head.row());
 3052        let end_row = cmp::max(tail.row(), head.row());
 3053        let start_column = cmp::min(tail.column(), goal_column);
 3054        let end_column = cmp::max(tail.column(), goal_column);
 3055        let reversed = start_column < tail.column();
 3056
 3057        let selection_ranges = (start_row.0..=end_row.0)
 3058            .map(DisplayRow)
 3059            .filter_map(|row| {
 3060                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3061                    let start = display_map
 3062                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3063                        .to_point(display_map);
 3064                    let end = display_map
 3065                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3066                        .to_point(display_map);
 3067                    if reversed {
 3068                        Some(end..start)
 3069                    } else {
 3070                        Some(start..end)
 3071                    }
 3072                } else {
 3073                    None
 3074                }
 3075            })
 3076            .collect::<Vec<_>>();
 3077
 3078        self.change_selections(None, cx, |s| {
 3079            s.select_ranges(selection_ranges);
 3080        });
 3081        cx.notify();
 3082    }
 3083
 3084    pub fn has_pending_nonempty_selection(&self) -> bool {
 3085        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3086            Some(Selection { start, end, .. }) => start != end,
 3087            None => false,
 3088        };
 3089
 3090        pending_nonempty_selection
 3091            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3092    }
 3093
 3094    pub fn has_pending_selection(&self) -> bool {
 3095        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3096    }
 3097
 3098    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3099        if self.clear_expanded_diff_hunks(cx) {
 3100            cx.notify();
 3101            return;
 3102        }
 3103        if self.dismiss_menus_and_popups(true, cx) {
 3104            return;
 3105        }
 3106
 3107        if self.mode == EditorMode::Full
 3108            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3109        {
 3110            return;
 3111        }
 3112
 3113        cx.propagate();
 3114    }
 3115
 3116    pub fn dismiss_menus_and_popups(
 3117        &mut self,
 3118        should_report_inline_completion_event: bool,
 3119        cx: &mut ViewContext<Self>,
 3120    ) -> bool {
 3121        if self.take_rename(false, cx).is_some() {
 3122            return true;
 3123        }
 3124
 3125        if hide_hover(self, cx) {
 3126            return true;
 3127        }
 3128
 3129        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3130            return true;
 3131        }
 3132
 3133        if self.hide_context_menu(cx).is_some() {
 3134            return true;
 3135        }
 3136
 3137        if self.mouse_context_menu.take().is_some() {
 3138            return true;
 3139        }
 3140
 3141        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3142            return true;
 3143        }
 3144
 3145        if self.snippet_stack.pop().is_some() {
 3146            return true;
 3147        }
 3148
 3149        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3150            self.dismiss_diagnostics(cx);
 3151            return true;
 3152        }
 3153
 3154        false
 3155    }
 3156
 3157    fn linked_editing_ranges_for(
 3158        &self,
 3159        selection: Range<text::Anchor>,
 3160        cx: &AppContext,
 3161    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3162        if self.linked_edit_ranges.is_empty() {
 3163            return None;
 3164        }
 3165        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3166            selection.end.buffer_id.and_then(|end_buffer_id| {
 3167                if selection.start.buffer_id != Some(end_buffer_id) {
 3168                    return None;
 3169                }
 3170                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3171                let snapshot = buffer.read(cx).snapshot();
 3172                self.linked_edit_ranges
 3173                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3174                    .map(|ranges| (ranges, snapshot, buffer))
 3175            })?;
 3176        use text::ToOffset as TO;
 3177        // find offset from the start of current range to current cursor position
 3178        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3179
 3180        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3181        let start_difference = start_offset - start_byte_offset;
 3182        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3183        let end_difference = end_offset - start_byte_offset;
 3184        // Current range has associated linked ranges.
 3185        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3186        for range in linked_ranges.iter() {
 3187            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3188            let end_offset = start_offset + end_difference;
 3189            let start_offset = start_offset + start_difference;
 3190            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3191                continue;
 3192            }
 3193            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3194                if s.start.buffer_id != selection.start.buffer_id
 3195                    || s.end.buffer_id != selection.end.buffer_id
 3196                {
 3197                    return false;
 3198                }
 3199                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3200                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3201            }) {
 3202                continue;
 3203            }
 3204            let start = buffer_snapshot.anchor_after(start_offset);
 3205            let end = buffer_snapshot.anchor_after(end_offset);
 3206            linked_edits
 3207                .entry(buffer.clone())
 3208                .or_default()
 3209                .push(start..end);
 3210        }
 3211        Some(linked_edits)
 3212    }
 3213
 3214    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3215        let text: Arc<str> = text.into();
 3216
 3217        if self.read_only(cx) {
 3218            return;
 3219        }
 3220
 3221        let selections = self.selections.all_adjusted(cx);
 3222        let mut bracket_inserted = false;
 3223        let mut edits = Vec::new();
 3224        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3225        let mut new_selections = Vec::with_capacity(selections.len());
 3226        let mut new_autoclose_regions = Vec::new();
 3227        let snapshot = self.buffer.read(cx).read(cx);
 3228
 3229        for (selection, autoclose_region) in
 3230            self.selections_with_autoclose_regions(selections, &snapshot)
 3231        {
 3232            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3233                // Determine if the inserted text matches the opening or closing
 3234                // bracket of any of this language's bracket pairs.
 3235                let mut bracket_pair = None;
 3236                let mut is_bracket_pair_start = false;
 3237                let mut is_bracket_pair_end = false;
 3238                if !text.is_empty() {
 3239                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3240                    //  and they are removing the character that triggered IME popup.
 3241                    for (pair, enabled) in scope.brackets() {
 3242                        if !pair.close && !pair.surround {
 3243                            continue;
 3244                        }
 3245
 3246                        if enabled && pair.start.ends_with(text.as_ref()) {
 3247                            bracket_pair = Some(pair.clone());
 3248                            is_bracket_pair_start = true;
 3249                            break;
 3250                        }
 3251                        if pair.end.as_str() == text.as_ref() {
 3252                            bracket_pair = Some(pair.clone());
 3253                            is_bracket_pair_end = true;
 3254                            break;
 3255                        }
 3256                    }
 3257                }
 3258
 3259                if let Some(bracket_pair) = bracket_pair {
 3260                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3261                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3262                    let auto_surround =
 3263                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3264                    if selection.is_empty() {
 3265                        if is_bracket_pair_start {
 3266                            let prefix_len = bracket_pair.start.len() - text.len();
 3267
 3268                            // If the inserted text is a suffix of an opening bracket and the
 3269                            // selection is preceded by the rest of the opening bracket, then
 3270                            // insert the closing bracket.
 3271                            let following_text_allows_autoclose = snapshot
 3272                                .chars_at(selection.start)
 3273                                .next()
 3274                                .map_or(true, |c| scope.should_autoclose_before(c));
 3275                            let preceding_text_matches_prefix = prefix_len == 0
 3276                                || (selection.start.column >= (prefix_len as u32)
 3277                                    && snapshot.contains_str_at(
 3278                                        Point::new(
 3279                                            selection.start.row,
 3280                                            selection.start.column - (prefix_len as u32),
 3281                                        ),
 3282                                        &bracket_pair.start[..prefix_len],
 3283                                    ));
 3284
 3285                            if autoclose
 3286                                && bracket_pair.close
 3287                                && following_text_allows_autoclose
 3288                                && preceding_text_matches_prefix
 3289                            {
 3290                                let anchor = snapshot.anchor_before(selection.end);
 3291                                new_selections.push((selection.map(|_| anchor), text.len()));
 3292                                new_autoclose_regions.push((
 3293                                    anchor,
 3294                                    text.len(),
 3295                                    selection.id,
 3296                                    bracket_pair.clone(),
 3297                                ));
 3298                                edits.push((
 3299                                    selection.range(),
 3300                                    format!("{}{}", text, bracket_pair.end).into(),
 3301                                ));
 3302                                bracket_inserted = true;
 3303                                continue;
 3304                            }
 3305                        }
 3306
 3307                        if let Some(region) = autoclose_region {
 3308                            // If the selection is followed by an auto-inserted closing bracket,
 3309                            // then don't insert that closing bracket again; just move the selection
 3310                            // past the closing bracket.
 3311                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3312                                && text.as_ref() == region.pair.end.as_str();
 3313                            if should_skip {
 3314                                let anchor = snapshot.anchor_after(selection.end);
 3315                                new_selections
 3316                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3317                                continue;
 3318                            }
 3319                        }
 3320
 3321                        let always_treat_brackets_as_autoclosed = snapshot
 3322                            .settings_at(selection.start, cx)
 3323                            .always_treat_brackets_as_autoclosed;
 3324                        if always_treat_brackets_as_autoclosed
 3325                            && is_bracket_pair_end
 3326                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3327                        {
 3328                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3329                            // and the inserted text is a closing bracket and the selection is followed
 3330                            // by the closing bracket then move the selection past the closing bracket.
 3331                            let anchor = snapshot.anchor_after(selection.end);
 3332                            new_selections.push((selection.map(|_| anchor), text.len()));
 3333                            continue;
 3334                        }
 3335                    }
 3336                    // If an opening bracket is 1 character long and is typed while
 3337                    // text is selected, then surround that text with the bracket pair.
 3338                    else if auto_surround
 3339                        && bracket_pair.surround
 3340                        && is_bracket_pair_start
 3341                        && bracket_pair.start.chars().count() == 1
 3342                    {
 3343                        edits.push((selection.start..selection.start, text.clone()));
 3344                        edits.push((
 3345                            selection.end..selection.end,
 3346                            bracket_pair.end.as_str().into(),
 3347                        ));
 3348                        bracket_inserted = true;
 3349                        new_selections.push((
 3350                            Selection {
 3351                                id: selection.id,
 3352                                start: snapshot.anchor_after(selection.start),
 3353                                end: snapshot.anchor_before(selection.end),
 3354                                reversed: selection.reversed,
 3355                                goal: selection.goal,
 3356                            },
 3357                            0,
 3358                        ));
 3359                        continue;
 3360                    }
 3361                }
 3362            }
 3363
 3364            if self.auto_replace_emoji_shortcode
 3365                && selection.is_empty()
 3366                && text.as_ref().ends_with(':')
 3367            {
 3368                if let Some(possible_emoji_short_code) =
 3369                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3370                {
 3371                    if !possible_emoji_short_code.is_empty() {
 3372                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3373                            let emoji_shortcode_start = Point::new(
 3374                                selection.start.row,
 3375                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3376                            );
 3377
 3378                            // Remove shortcode from buffer
 3379                            edits.push((
 3380                                emoji_shortcode_start..selection.start,
 3381                                "".to_string().into(),
 3382                            ));
 3383                            new_selections.push((
 3384                                Selection {
 3385                                    id: selection.id,
 3386                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3387                                    end: snapshot.anchor_before(selection.start),
 3388                                    reversed: selection.reversed,
 3389                                    goal: selection.goal,
 3390                                },
 3391                                0,
 3392                            ));
 3393
 3394                            // Insert emoji
 3395                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3396                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3397                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3398
 3399                            continue;
 3400                        }
 3401                    }
 3402                }
 3403            }
 3404
 3405            // If not handling any auto-close operation, then just replace the selected
 3406            // text with the given input and move the selection to the end of the
 3407            // newly inserted text.
 3408            let anchor = snapshot.anchor_after(selection.end);
 3409            if !self.linked_edit_ranges.is_empty() {
 3410                let start_anchor = snapshot.anchor_before(selection.start);
 3411
 3412                let is_word_char = text.chars().next().map_or(true, |char| {
 3413                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3414                    classifier.is_word(char)
 3415                });
 3416
 3417                if is_word_char {
 3418                    if let Some(ranges) = self
 3419                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3420                    {
 3421                        for (buffer, edits) in ranges {
 3422                            linked_edits
 3423                                .entry(buffer.clone())
 3424                                .or_default()
 3425                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3426                        }
 3427                    }
 3428                }
 3429            }
 3430
 3431            new_selections.push((selection.map(|_| anchor), 0));
 3432            edits.push((selection.start..selection.end, text.clone()));
 3433        }
 3434
 3435        drop(snapshot);
 3436
 3437        self.transact(cx, |this, cx| {
 3438            this.buffer.update(cx, |buffer, cx| {
 3439                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3440            });
 3441            for (buffer, edits) in linked_edits {
 3442                buffer.update(cx, |buffer, cx| {
 3443                    let snapshot = buffer.snapshot();
 3444                    let edits = edits
 3445                        .into_iter()
 3446                        .map(|(range, text)| {
 3447                            use text::ToPoint as TP;
 3448                            let end_point = TP::to_point(&range.end, &snapshot);
 3449                            let start_point = TP::to_point(&range.start, &snapshot);
 3450                            (start_point..end_point, text)
 3451                        })
 3452                        .sorted_by_key(|(range, _)| range.start)
 3453                        .collect::<Vec<_>>();
 3454                    buffer.edit(edits, None, cx);
 3455                })
 3456            }
 3457            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3458            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3459            let snapshot = this.buffer.read(cx).read(cx);
 3460            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3461                .zip(new_selection_deltas)
 3462                .map(|(selection, delta)| Selection {
 3463                    id: selection.id,
 3464                    start: selection.start + delta,
 3465                    end: selection.end + delta,
 3466                    reversed: selection.reversed,
 3467                    goal: SelectionGoal::None,
 3468                })
 3469                .collect::<Vec<_>>();
 3470
 3471            let mut i = 0;
 3472            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3473                let position = position.to_offset(&snapshot) + delta;
 3474                let start = snapshot.anchor_before(position);
 3475                let end = snapshot.anchor_after(position);
 3476                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3477                    match existing_state.range.start.cmp(&start, &snapshot) {
 3478                        Ordering::Less => i += 1,
 3479                        Ordering::Greater => break,
 3480                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3481                            Ordering::Less => i += 1,
 3482                            Ordering::Equal => break,
 3483                            Ordering::Greater => break,
 3484                        },
 3485                    }
 3486                }
 3487                this.autoclose_regions.insert(
 3488                    i,
 3489                    AutocloseRegion {
 3490                        selection_id,
 3491                        range: start..end,
 3492                        pair,
 3493                    },
 3494                );
 3495            }
 3496
 3497            drop(snapshot);
 3498            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3499            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3500                s.select(new_selections)
 3501            });
 3502
 3503            if !bracket_inserted {
 3504                if let Some(on_type_format_task) =
 3505                    this.trigger_on_type_formatting(text.to_string(), cx)
 3506                {
 3507                    on_type_format_task.detach_and_log_err(cx);
 3508                }
 3509            }
 3510
 3511            let editor_settings = EditorSettings::get_global(cx);
 3512            if bracket_inserted
 3513                && (editor_settings.auto_signature_help
 3514                    || editor_settings.show_signature_help_after_edits)
 3515            {
 3516                this.show_signature_help(&ShowSignatureHelp, cx);
 3517            }
 3518
 3519            let trigger_in_words = !had_active_inline_completion;
 3520            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3521            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3522            this.refresh_inline_completion(true, false, cx);
 3523        });
 3524    }
 3525
 3526    fn find_possible_emoji_shortcode_at_position(
 3527        snapshot: &MultiBufferSnapshot,
 3528        position: Point,
 3529    ) -> Option<String> {
 3530        let mut chars = Vec::new();
 3531        let mut found_colon = false;
 3532        for char in snapshot.reversed_chars_at(position).take(100) {
 3533            // Found a possible emoji shortcode in the middle of the buffer
 3534            if found_colon {
 3535                if char.is_whitespace() {
 3536                    chars.reverse();
 3537                    return Some(chars.iter().collect());
 3538                }
 3539                // If the previous character is not a whitespace, we are in the middle of a word
 3540                // and we only want to complete the shortcode if the word is made up of other emojis
 3541                let mut containing_word = String::new();
 3542                for ch in snapshot
 3543                    .reversed_chars_at(position)
 3544                    .skip(chars.len() + 1)
 3545                    .take(100)
 3546                {
 3547                    if ch.is_whitespace() {
 3548                        break;
 3549                    }
 3550                    containing_word.push(ch);
 3551                }
 3552                let containing_word = containing_word.chars().rev().collect::<String>();
 3553                if util::word_consists_of_emojis(containing_word.as_str()) {
 3554                    chars.reverse();
 3555                    return Some(chars.iter().collect());
 3556                }
 3557            }
 3558
 3559            if char.is_whitespace() || !char.is_ascii() {
 3560                return None;
 3561            }
 3562            if char == ':' {
 3563                found_colon = true;
 3564            } else {
 3565                chars.push(char);
 3566            }
 3567        }
 3568        // Found a possible emoji shortcode at the beginning of the buffer
 3569        chars.reverse();
 3570        Some(chars.iter().collect())
 3571    }
 3572
 3573    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3574        self.transact(cx, |this, cx| {
 3575            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3576                let selections = this.selections.all::<usize>(cx);
 3577                let multi_buffer = this.buffer.read(cx);
 3578                let buffer = multi_buffer.snapshot(cx);
 3579                selections
 3580                    .iter()
 3581                    .map(|selection| {
 3582                        let start_point = selection.start.to_point(&buffer);
 3583                        let mut indent =
 3584                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3585                        indent.len = cmp::min(indent.len, start_point.column);
 3586                        let start = selection.start;
 3587                        let end = selection.end;
 3588                        let selection_is_empty = start == end;
 3589                        let language_scope = buffer.language_scope_at(start);
 3590                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3591                            &language_scope
 3592                        {
 3593                            let leading_whitespace_len = buffer
 3594                                .reversed_chars_at(start)
 3595                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3596                                .map(|c| c.len_utf8())
 3597                                .sum::<usize>();
 3598
 3599                            let trailing_whitespace_len = buffer
 3600                                .chars_at(end)
 3601                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3602                                .map(|c| c.len_utf8())
 3603                                .sum::<usize>();
 3604
 3605                            let insert_extra_newline =
 3606                                language.brackets().any(|(pair, enabled)| {
 3607                                    let pair_start = pair.start.trim_end();
 3608                                    let pair_end = pair.end.trim_start();
 3609
 3610                                    enabled
 3611                                        && pair.newline
 3612                                        && buffer.contains_str_at(
 3613                                            end + trailing_whitespace_len,
 3614                                            pair_end,
 3615                                        )
 3616                                        && buffer.contains_str_at(
 3617                                            (start - leading_whitespace_len)
 3618                                                .saturating_sub(pair_start.len()),
 3619                                            pair_start,
 3620                                        )
 3621                                });
 3622
 3623                            // Comment extension on newline is allowed only for cursor selections
 3624                            let comment_delimiter = maybe!({
 3625                                if !selection_is_empty {
 3626                                    return None;
 3627                                }
 3628
 3629                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3630                                    return None;
 3631                                }
 3632
 3633                                let delimiters = language.line_comment_prefixes();
 3634                                let max_len_of_delimiter =
 3635                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3636                                let (snapshot, range) =
 3637                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3638
 3639                                let mut index_of_first_non_whitespace = 0;
 3640                                let comment_candidate = snapshot
 3641                                    .chars_for_range(range)
 3642                                    .skip_while(|c| {
 3643                                        let should_skip = c.is_whitespace();
 3644                                        if should_skip {
 3645                                            index_of_first_non_whitespace += 1;
 3646                                        }
 3647                                        should_skip
 3648                                    })
 3649                                    .take(max_len_of_delimiter)
 3650                                    .collect::<String>();
 3651                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3652                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3653                                })?;
 3654                                let cursor_is_placed_after_comment_marker =
 3655                                    index_of_first_non_whitespace + comment_prefix.len()
 3656                                        <= start_point.column as usize;
 3657                                if cursor_is_placed_after_comment_marker {
 3658                                    Some(comment_prefix.clone())
 3659                                } else {
 3660                                    None
 3661                                }
 3662                            });
 3663                            (comment_delimiter, insert_extra_newline)
 3664                        } else {
 3665                            (None, false)
 3666                        };
 3667
 3668                        let capacity_for_delimiter = comment_delimiter
 3669                            .as_deref()
 3670                            .map(str::len)
 3671                            .unwrap_or_default();
 3672                        let mut new_text =
 3673                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3674                        new_text.push('\n');
 3675                        new_text.extend(indent.chars());
 3676                        if let Some(delimiter) = &comment_delimiter {
 3677                            new_text.push_str(delimiter);
 3678                        }
 3679                        if insert_extra_newline {
 3680                            new_text = new_text.repeat(2);
 3681                        }
 3682
 3683                        let anchor = buffer.anchor_after(end);
 3684                        let new_selection = selection.map(|_| anchor);
 3685                        (
 3686                            (start..end, new_text),
 3687                            (insert_extra_newline, new_selection),
 3688                        )
 3689                    })
 3690                    .unzip()
 3691            };
 3692
 3693            this.edit_with_autoindent(edits, cx);
 3694            let buffer = this.buffer.read(cx).snapshot(cx);
 3695            let new_selections = selection_fixup_info
 3696                .into_iter()
 3697                .map(|(extra_newline_inserted, new_selection)| {
 3698                    let mut cursor = new_selection.end.to_point(&buffer);
 3699                    if extra_newline_inserted {
 3700                        cursor.row -= 1;
 3701                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3702                    }
 3703                    new_selection.map(|_| cursor)
 3704                })
 3705                .collect();
 3706
 3707            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3708            this.refresh_inline_completion(true, false, cx);
 3709        });
 3710    }
 3711
 3712    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3713        let buffer = self.buffer.read(cx);
 3714        let snapshot = buffer.snapshot(cx);
 3715
 3716        let mut edits = Vec::new();
 3717        let mut rows = Vec::new();
 3718
 3719        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3720            let cursor = selection.head();
 3721            let row = cursor.row;
 3722
 3723            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3724
 3725            let newline = "\n".to_string();
 3726            edits.push((start_of_line..start_of_line, newline));
 3727
 3728            rows.push(row + rows_inserted as u32);
 3729        }
 3730
 3731        self.transact(cx, |editor, cx| {
 3732            editor.edit(edits, cx);
 3733
 3734            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3735                let mut index = 0;
 3736                s.move_cursors_with(|map, _, _| {
 3737                    let row = rows[index];
 3738                    index += 1;
 3739
 3740                    let point = Point::new(row, 0);
 3741                    let boundary = map.next_line_boundary(point).1;
 3742                    let clipped = map.clip_point(boundary, Bias::Left);
 3743
 3744                    (clipped, SelectionGoal::None)
 3745                });
 3746            });
 3747
 3748            let mut indent_edits = Vec::new();
 3749            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3750            for row in rows {
 3751                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3752                for (row, indent) in indents {
 3753                    if indent.len == 0 {
 3754                        continue;
 3755                    }
 3756
 3757                    let text = match indent.kind {
 3758                        IndentKind::Space => " ".repeat(indent.len as usize),
 3759                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3760                    };
 3761                    let point = Point::new(row.0, 0);
 3762                    indent_edits.push((point..point, text));
 3763                }
 3764            }
 3765            editor.edit(indent_edits, cx);
 3766        });
 3767    }
 3768
 3769    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3770        let buffer = self.buffer.read(cx);
 3771        let snapshot = buffer.snapshot(cx);
 3772
 3773        let mut edits = Vec::new();
 3774        let mut rows = Vec::new();
 3775        let mut rows_inserted = 0;
 3776
 3777        for selection in self.selections.all_adjusted(cx) {
 3778            let cursor = selection.head();
 3779            let row = cursor.row;
 3780
 3781            let point = Point::new(row + 1, 0);
 3782            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3783
 3784            let newline = "\n".to_string();
 3785            edits.push((start_of_line..start_of_line, newline));
 3786
 3787            rows_inserted += 1;
 3788            rows.push(row + rows_inserted);
 3789        }
 3790
 3791        self.transact(cx, |editor, cx| {
 3792            editor.edit(edits, cx);
 3793
 3794            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3795                let mut index = 0;
 3796                s.move_cursors_with(|map, _, _| {
 3797                    let row = rows[index];
 3798                    index += 1;
 3799
 3800                    let point = Point::new(row, 0);
 3801                    let boundary = map.next_line_boundary(point).1;
 3802                    let clipped = map.clip_point(boundary, Bias::Left);
 3803
 3804                    (clipped, SelectionGoal::None)
 3805                });
 3806            });
 3807
 3808            let mut indent_edits = Vec::new();
 3809            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3810            for row in rows {
 3811                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3812                for (row, indent) in indents {
 3813                    if indent.len == 0 {
 3814                        continue;
 3815                    }
 3816
 3817                    let text = match indent.kind {
 3818                        IndentKind::Space => " ".repeat(indent.len as usize),
 3819                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3820                    };
 3821                    let point = Point::new(row.0, 0);
 3822                    indent_edits.push((point..point, text));
 3823                }
 3824            }
 3825            editor.edit(indent_edits, cx);
 3826        });
 3827    }
 3828
 3829    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3830        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3831            original_indent_columns: Vec::new(),
 3832        });
 3833        self.insert_with_autoindent_mode(text, autoindent, cx);
 3834    }
 3835
 3836    fn insert_with_autoindent_mode(
 3837        &mut self,
 3838        text: &str,
 3839        autoindent_mode: Option<AutoindentMode>,
 3840        cx: &mut ViewContext<Self>,
 3841    ) {
 3842        if self.read_only(cx) {
 3843            return;
 3844        }
 3845
 3846        let text: Arc<str> = text.into();
 3847        self.transact(cx, |this, cx| {
 3848            let old_selections = this.selections.all_adjusted(cx);
 3849            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3850                let anchors = {
 3851                    let snapshot = buffer.read(cx);
 3852                    old_selections
 3853                        .iter()
 3854                        .map(|s| {
 3855                            let anchor = snapshot.anchor_after(s.head());
 3856                            s.map(|_| anchor)
 3857                        })
 3858                        .collect::<Vec<_>>()
 3859                };
 3860                buffer.edit(
 3861                    old_selections
 3862                        .iter()
 3863                        .map(|s| (s.start..s.end, text.clone())),
 3864                    autoindent_mode,
 3865                    cx,
 3866                );
 3867                anchors
 3868            });
 3869
 3870            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3871                s.select_anchors(selection_anchors);
 3872            })
 3873        });
 3874    }
 3875
 3876    fn trigger_completion_on_input(
 3877        &mut self,
 3878        text: &str,
 3879        trigger_in_words: bool,
 3880        cx: &mut ViewContext<Self>,
 3881    ) {
 3882        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3883            self.show_completions(
 3884                &ShowCompletions {
 3885                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3886                },
 3887                cx,
 3888            );
 3889        } else {
 3890            self.hide_context_menu(cx);
 3891        }
 3892    }
 3893
 3894    fn is_completion_trigger(
 3895        &self,
 3896        text: &str,
 3897        trigger_in_words: bool,
 3898        cx: &mut ViewContext<Self>,
 3899    ) -> bool {
 3900        let position = self.selections.newest_anchor().head();
 3901        let multibuffer = self.buffer.read(cx);
 3902        let Some(buffer) = position
 3903            .buffer_id
 3904            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3905        else {
 3906            return false;
 3907        };
 3908
 3909        if let Some(completion_provider) = &self.completion_provider {
 3910            completion_provider.is_completion_trigger(
 3911                &buffer,
 3912                position.text_anchor,
 3913                text,
 3914                trigger_in_words,
 3915                cx,
 3916            )
 3917        } else {
 3918            false
 3919        }
 3920    }
 3921
 3922    /// If any empty selections is touching the start of its innermost containing autoclose
 3923    /// region, expand it to select the brackets.
 3924    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3925        let selections = self.selections.all::<usize>(cx);
 3926        let buffer = self.buffer.read(cx).read(cx);
 3927        let new_selections = self
 3928            .selections_with_autoclose_regions(selections, &buffer)
 3929            .map(|(mut selection, region)| {
 3930                if !selection.is_empty() {
 3931                    return selection;
 3932                }
 3933
 3934                if let Some(region) = region {
 3935                    let mut range = region.range.to_offset(&buffer);
 3936                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3937                        range.start -= region.pair.start.len();
 3938                        if buffer.contains_str_at(range.start, &region.pair.start)
 3939                            && buffer.contains_str_at(range.end, &region.pair.end)
 3940                        {
 3941                            range.end += region.pair.end.len();
 3942                            selection.start = range.start;
 3943                            selection.end = range.end;
 3944
 3945                            return selection;
 3946                        }
 3947                    }
 3948                }
 3949
 3950                let always_treat_brackets_as_autoclosed = buffer
 3951                    .settings_at(selection.start, cx)
 3952                    .always_treat_brackets_as_autoclosed;
 3953
 3954                if !always_treat_brackets_as_autoclosed {
 3955                    return selection;
 3956                }
 3957
 3958                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3959                    for (pair, enabled) in scope.brackets() {
 3960                        if !enabled || !pair.close {
 3961                            continue;
 3962                        }
 3963
 3964                        if buffer.contains_str_at(selection.start, &pair.end) {
 3965                            let pair_start_len = pair.start.len();
 3966                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3967                            {
 3968                                selection.start -= pair_start_len;
 3969                                selection.end += pair.end.len();
 3970
 3971                                return selection;
 3972                            }
 3973                        }
 3974                    }
 3975                }
 3976
 3977                selection
 3978            })
 3979            .collect();
 3980
 3981        drop(buffer);
 3982        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3983    }
 3984
 3985    /// Iterate the given selections, and for each one, find the smallest surrounding
 3986    /// autoclose region. This uses the ordering of the selections and the autoclose
 3987    /// regions to avoid repeated comparisons.
 3988    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3989        &'a self,
 3990        selections: impl IntoIterator<Item = Selection<D>>,
 3991        buffer: &'a MultiBufferSnapshot,
 3992    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3993        let mut i = 0;
 3994        let mut regions = self.autoclose_regions.as_slice();
 3995        selections.into_iter().map(move |selection| {
 3996            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3997
 3998            let mut enclosing = None;
 3999            while let Some(pair_state) = regions.get(i) {
 4000                if pair_state.range.end.to_offset(buffer) < range.start {
 4001                    regions = &regions[i + 1..];
 4002                    i = 0;
 4003                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4004                    break;
 4005                } else {
 4006                    if pair_state.selection_id == selection.id {
 4007                        enclosing = Some(pair_state);
 4008                    }
 4009                    i += 1;
 4010                }
 4011            }
 4012
 4013            (selection.clone(), enclosing)
 4014        })
 4015    }
 4016
 4017    /// Remove any autoclose regions that no longer contain their selection.
 4018    fn invalidate_autoclose_regions(
 4019        &mut self,
 4020        mut selections: &[Selection<Anchor>],
 4021        buffer: &MultiBufferSnapshot,
 4022    ) {
 4023        self.autoclose_regions.retain(|state| {
 4024            let mut i = 0;
 4025            while let Some(selection) = selections.get(i) {
 4026                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4027                    selections = &selections[1..];
 4028                    continue;
 4029                }
 4030                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4031                    break;
 4032                }
 4033                if selection.id == state.selection_id {
 4034                    return true;
 4035                } else {
 4036                    i += 1;
 4037                }
 4038            }
 4039            false
 4040        });
 4041    }
 4042
 4043    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4044        let offset = position.to_offset(buffer);
 4045        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4046        if offset > word_range.start && kind == Some(CharKind::Word) {
 4047            Some(
 4048                buffer
 4049                    .text_for_range(word_range.start..offset)
 4050                    .collect::<String>(),
 4051            )
 4052        } else {
 4053            None
 4054        }
 4055    }
 4056
 4057    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4058        self.refresh_inlay_hints(
 4059            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4060            cx,
 4061        );
 4062    }
 4063
 4064    pub fn inlay_hints_enabled(&self) -> bool {
 4065        self.inlay_hint_cache.enabled
 4066    }
 4067
 4068    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4069        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4070            return;
 4071        }
 4072
 4073        let reason_description = reason.description();
 4074        let ignore_debounce = matches!(
 4075            reason,
 4076            InlayHintRefreshReason::SettingsChange(_)
 4077                | InlayHintRefreshReason::Toggle(_)
 4078                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4079        );
 4080        let (invalidate_cache, required_languages) = match reason {
 4081            InlayHintRefreshReason::Toggle(enabled) => {
 4082                self.inlay_hint_cache.enabled = enabled;
 4083                if enabled {
 4084                    (InvalidationStrategy::RefreshRequested, None)
 4085                } else {
 4086                    self.inlay_hint_cache.clear();
 4087                    self.splice_inlays(
 4088                        self.visible_inlay_hints(cx)
 4089                            .iter()
 4090                            .map(|inlay| inlay.id)
 4091                            .collect(),
 4092                        Vec::new(),
 4093                        cx,
 4094                    );
 4095                    return;
 4096                }
 4097            }
 4098            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4099                match self.inlay_hint_cache.update_settings(
 4100                    &self.buffer,
 4101                    new_settings,
 4102                    self.visible_inlay_hints(cx),
 4103                    cx,
 4104                ) {
 4105                    ControlFlow::Break(Some(InlaySplice {
 4106                        to_remove,
 4107                        to_insert,
 4108                    })) => {
 4109                        self.splice_inlays(to_remove, to_insert, cx);
 4110                        return;
 4111                    }
 4112                    ControlFlow::Break(None) => return,
 4113                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4114                }
 4115            }
 4116            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4117                if let Some(InlaySplice {
 4118                    to_remove,
 4119                    to_insert,
 4120                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4121                {
 4122                    self.splice_inlays(to_remove, to_insert, cx);
 4123                }
 4124                return;
 4125            }
 4126            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4127            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4128                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4129            }
 4130            InlayHintRefreshReason::RefreshRequested => {
 4131                (InvalidationStrategy::RefreshRequested, None)
 4132            }
 4133        };
 4134
 4135        if let Some(InlaySplice {
 4136            to_remove,
 4137            to_insert,
 4138        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4139            reason_description,
 4140            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4141            invalidate_cache,
 4142            ignore_debounce,
 4143            cx,
 4144        ) {
 4145            self.splice_inlays(to_remove, to_insert, cx);
 4146        }
 4147    }
 4148
 4149    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4150        self.display_map
 4151            .read(cx)
 4152            .current_inlays()
 4153            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4154            .cloned()
 4155            .collect()
 4156    }
 4157
 4158    pub fn excerpts_for_inlay_hints_query(
 4159        &self,
 4160        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4161        cx: &mut ViewContext<Editor>,
 4162    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4163        let Some(project) = self.project.as_ref() else {
 4164            return HashMap::default();
 4165        };
 4166        let project = project.read(cx);
 4167        let multi_buffer = self.buffer().read(cx);
 4168        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4169        let multi_buffer_visible_start = self
 4170            .scroll_manager
 4171            .anchor()
 4172            .anchor
 4173            .to_point(&multi_buffer_snapshot);
 4174        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4175            multi_buffer_visible_start
 4176                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4177            Bias::Left,
 4178        );
 4179        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4180        multi_buffer
 4181            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4182            .into_iter()
 4183            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4184            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4185                let buffer = buffer_handle.read(cx);
 4186                let buffer_file = project::File::from_dyn(buffer.file())?;
 4187                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4188                let worktree_entry = buffer_worktree
 4189                    .read(cx)
 4190                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4191                if worktree_entry.is_ignored {
 4192                    return None;
 4193                }
 4194
 4195                let language = buffer.language()?;
 4196                if let Some(restrict_to_languages) = restrict_to_languages {
 4197                    if !restrict_to_languages.contains(language) {
 4198                        return None;
 4199                    }
 4200                }
 4201                Some((
 4202                    excerpt_id,
 4203                    (
 4204                        buffer_handle,
 4205                        buffer.version().clone(),
 4206                        excerpt_visible_range,
 4207                    ),
 4208                ))
 4209            })
 4210            .collect()
 4211    }
 4212
 4213    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4214        TextLayoutDetails {
 4215            text_system: cx.text_system().clone(),
 4216            editor_style: self.style.clone().unwrap(),
 4217            rem_size: cx.rem_size(),
 4218            scroll_anchor: self.scroll_manager.anchor(),
 4219            visible_rows: self.visible_line_count(),
 4220            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4221        }
 4222    }
 4223
 4224    fn splice_inlays(
 4225        &self,
 4226        to_remove: Vec<InlayId>,
 4227        to_insert: Vec<Inlay>,
 4228        cx: &mut ViewContext<Self>,
 4229    ) {
 4230        self.display_map.update(cx, |display_map, cx| {
 4231            display_map.splice_inlays(to_remove, to_insert, cx);
 4232        });
 4233        cx.notify();
 4234    }
 4235
 4236    fn trigger_on_type_formatting(
 4237        &self,
 4238        input: String,
 4239        cx: &mut ViewContext<Self>,
 4240    ) -> Option<Task<Result<()>>> {
 4241        if input.len() != 1 {
 4242            return None;
 4243        }
 4244
 4245        let project = self.project.as_ref()?;
 4246        let position = self.selections.newest_anchor().head();
 4247        let (buffer, buffer_position) = self
 4248            .buffer
 4249            .read(cx)
 4250            .text_anchor_for_position(position, cx)?;
 4251
 4252        let settings = language_settings::language_settings(
 4253            buffer.read(cx).language_at(buffer_position).as_ref(),
 4254            buffer.read(cx).file(),
 4255            cx,
 4256        );
 4257        if !settings.use_on_type_format {
 4258            return None;
 4259        }
 4260
 4261        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4262        // hence we do LSP request & edit on host side only — add formats to host's history.
 4263        let push_to_lsp_host_history = true;
 4264        // If this is not the host, append its history with new edits.
 4265        let push_to_client_history = project.read(cx).is_via_collab();
 4266
 4267        let on_type_formatting = project.update(cx, |project, cx| {
 4268            project.on_type_format(
 4269                buffer.clone(),
 4270                buffer_position,
 4271                input,
 4272                push_to_lsp_host_history,
 4273                cx,
 4274            )
 4275        });
 4276        Some(cx.spawn(|editor, mut cx| async move {
 4277            if let Some(transaction) = on_type_formatting.await? {
 4278                if push_to_client_history {
 4279                    buffer
 4280                        .update(&mut cx, |buffer, _| {
 4281                            buffer.push_transaction(transaction, Instant::now());
 4282                        })
 4283                        .ok();
 4284                }
 4285                editor.update(&mut cx, |editor, cx| {
 4286                    editor.refresh_document_highlights(cx);
 4287                })?;
 4288            }
 4289            Ok(())
 4290        }))
 4291    }
 4292
 4293    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4294        if self.pending_rename.is_some() {
 4295            return;
 4296        }
 4297
 4298        let Some(provider) = self.completion_provider.as_ref() else {
 4299            return;
 4300        };
 4301
 4302        let position = self.selections.newest_anchor().head();
 4303        let (buffer, buffer_position) =
 4304            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4305                output
 4306            } else {
 4307                return;
 4308            };
 4309
 4310        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4311        let is_followup_invoke = {
 4312            let context_menu_state = self.context_menu.read();
 4313            matches!(
 4314                context_menu_state.deref(),
 4315                Some(ContextMenu::Completions(_))
 4316            )
 4317        };
 4318        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4319            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4320            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4321                CompletionTriggerKind::TRIGGER_CHARACTER
 4322            }
 4323
 4324            _ => CompletionTriggerKind::INVOKED,
 4325        };
 4326        let completion_context = CompletionContext {
 4327            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4328                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4329                    Some(String::from(trigger))
 4330                } else {
 4331                    None
 4332                }
 4333            }),
 4334            trigger_kind,
 4335        };
 4336        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4337        let sort_completions = provider.sort_completions();
 4338
 4339        let id = post_inc(&mut self.next_completion_id);
 4340        let task = cx.spawn(|this, mut cx| {
 4341            async move {
 4342                this.update(&mut cx, |this, _| {
 4343                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4344                })?;
 4345                let completions = completions.await.log_err();
 4346                let menu = if let Some(completions) = completions {
 4347                    let mut menu = CompletionsMenu {
 4348                        id,
 4349                        sort_completions,
 4350                        initial_position: position,
 4351                        match_candidates: completions
 4352                            .iter()
 4353                            .enumerate()
 4354                            .map(|(id, completion)| {
 4355                                StringMatchCandidate::new(
 4356                                    id,
 4357                                    completion.label.text[completion.label.filter_range.clone()]
 4358                                        .into(),
 4359                                )
 4360                            })
 4361                            .collect(),
 4362                        buffer: buffer.clone(),
 4363                        completions: Arc::new(RwLock::new(completions.into())),
 4364                        matches: Vec::new().into(),
 4365                        selected_item: 0,
 4366                        scroll_handle: UniformListScrollHandle::new(),
 4367                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4368                            DebouncedDelay::new(),
 4369                        )),
 4370                    };
 4371                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4372                        .await;
 4373
 4374                    if menu.matches.is_empty() {
 4375                        None
 4376                    } else {
 4377                        this.update(&mut cx, |editor, cx| {
 4378                            let completions = menu.completions.clone();
 4379                            let matches = menu.matches.clone();
 4380
 4381                            let delay_ms = EditorSettings::get_global(cx)
 4382                                .completion_documentation_secondary_query_debounce;
 4383                            let delay = Duration::from_millis(delay_ms);
 4384                            editor
 4385                                .completion_documentation_pre_resolve_debounce
 4386                                .fire_new(delay, cx, |editor, cx| {
 4387                                    CompletionsMenu::pre_resolve_completion_documentation(
 4388                                        buffer,
 4389                                        completions,
 4390                                        matches,
 4391                                        editor,
 4392                                        cx,
 4393                                    )
 4394                                });
 4395                        })
 4396                        .ok();
 4397                        Some(menu)
 4398                    }
 4399                } else {
 4400                    None
 4401                };
 4402
 4403                this.update(&mut cx, |this, cx| {
 4404                    let mut context_menu = this.context_menu.write();
 4405                    match context_menu.as_ref() {
 4406                        None => {}
 4407
 4408                        Some(ContextMenu::Completions(prev_menu)) => {
 4409                            if prev_menu.id > id {
 4410                                return;
 4411                            }
 4412                        }
 4413
 4414                        _ => return,
 4415                    }
 4416
 4417                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4418                        let menu = menu.unwrap();
 4419                        *context_menu = Some(ContextMenu::Completions(menu));
 4420                        drop(context_menu);
 4421                        this.discard_inline_completion(false, cx);
 4422                        cx.notify();
 4423                    } else if this.completion_tasks.len() <= 1 {
 4424                        // If there are no more completion tasks and the last menu was
 4425                        // empty, we should hide it. If it was already hidden, we should
 4426                        // also show the copilot completion when available.
 4427                        drop(context_menu);
 4428                        if this.hide_context_menu(cx).is_none() {
 4429                            this.update_visible_inline_completion(cx);
 4430                        }
 4431                    }
 4432                })?;
 4433
 4434                Ok::<_, anyhow::Error>(())
 4435            }
 4436            .log_err()
 4437        });
 4438
 4439        self.completion_tasks.push((id, task));
 4440    }
 4441
 4442    pub fn confirm_completion(
 4443        &mut self,
 4444        action: &ConfirmCompletion,
 4445        cx: &mut ViewContext<Self>,
 4446    ) -> Option<Task<Result<()>>> {
 4447        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4448    }
 4449
 4450    pub fn compose_completion(
 4451        &mut self,
 4452        action: &ComposeCompletion,
 4453        cx: &mut ViewContext<Self>,
 4454    ) -> Option<Task<Result<()>>> {
 4455        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4456    }
 4457
 4458    fn do_completion(
 4459        &mut self,
 4460        item_ix: Option<usize>,
 4461        intent: CompletionIntent,
 4462        cx: &mut ViewContext<Editor>,
 4463    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4464        use language::ToOffset as _;
 4465
 4466        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4467            menu
 4468        } else {
 4469            return None;
 4470        };
 4471
 4472        let mat = completions_menu
 4473            .matches
 4474            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4475        let buffer_handle = completions_menu.buffer;
 4476        let completions = completions_menu.completions.read();
 4477        let completion = completions.get(mat.candidate_id)?;
 4478        cx.stop_propagation();
 4479
 4480        let snippet;
 4481        let text;
 4482
 4483        if completion.is_snippet() {
 4484            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4485            text = snippet.as_ref().unwrap().text.clone();
 4486        } else {
 4487            snippet = None;
 4488            text = completion.new_text.clone();
 4489        };
 4490        let selections = self.selections.all::<usize>(cx);
 4491        let buffer = buffer_handle.read(cx);
 4492        let old_range = completion.old_range.to_offset(buffer);
 4493        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4494
 4495        let newest_selection = self.selections.newest_anchor();
 4496        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4497            return None;
 4498        }
 4499
 4500        let lookbehind = newest_selection
 4501            .start
 4502            .text_anchor
 4503            .to_offset(buffer)
 4504            .saturating_sub(old_range.start);
 4505        let lookahead = old_range
 4506            .end
 4507            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4508        let mut common_prefix_len = old_text
 4509            .bytes()
 4510            .zip(text.bytes())
 4511            .take_while(|(a, b)| a == b)
 4512            .count();
 4513
 4514        let snapshot = self.buffer.read(cx).snapshot(cx);
 4515        let mut range_to_replace: Option<Range<isize>> = None;
 4516        let mut ranges = Vec::new();
 4517        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4518        for selection in &selections {
 4519            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4520                let start = selection.start.saturating_sub(lookbehind);
 4521                let end = selection.end + lookahead;
 4522                if selection.id == newest_selection.id {
 4523                    range_to_replace = Some(
 4524                        ((start + common_prefix_len) as isize - selection.start as isize)
 4525                            ..(end as isize - selection.start as isize),
 4526                    );
 4527                }
 4528                ranges.push(start + common_prefix_len..end);
 4529            } else {
 4530                common_prefix_len = 0;
 4531                ranges.clear();
 4532                ranges.extend(selections.iter().map(|s| {
 4533                    if s.id == newest_selection.id {
 4534                        range_to_replace = Some(
 4535                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4536                                - selection.start as isize
 4537                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4538                                    - selection.start as isize,
 4539                        );
 4540                        old_range.clone()
 4541                    } else {
 4542                        s.start..s.end
 4543                    }
 4544                }));
 4545                break;
 4546            }
 4547            if !self.linked_edit_ranges.is_empty() {
 4548                let start_anchor = snapshot.anchor_before(selection.head());
 4549                let end_anchor = snapshot.anchor_after(selection.tail());
 4550                if let Some(ranges) = self
 4551                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4552                {
 4553                    for (buffer, edits) in ranges {
 4554                        linked_edits.entry(buffer.clone()).or_default().extend(
 4555                            edits
 4556                                .into_iter()
 4557                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4558                        );
 4559                    }
 4560                }
 4561            }
 4562        }
 4563        let text = &text[common_prefix_len..];
 4564
 4565        cx.emit(EditorEvent::InputHandled {
 4566            utf16_range_to_replace: range_to_replace,
 4567            text: text.into(),
 4568        });
 4569
 4570        self.transact(cx, |this, cx| {
 4571            if let Some(mut snippet) = snippet {
 4572                snippet.text = text.to_string();
 4573                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4574                    tabstop.start -= common_prefix_len as isize;
 4575                    tabstop.end -= common_prefix_len as isize;
 4576                }
 4577
 4578                this.insert_snippet(&ranges, snippet, cx).log_err();
 4579            } else {
 4580                this.buffer.update(cx, |buffer, cx| {
 4581                    buffer.edit(
 4582                        ranges.iter().map(|range| (range.clone(), text)),
 4583                        this.autoindent_mode.clone(),
 4584                        cx,
 4585                    );
 4586                });
 4587            }
 4588            for (buffer, edits) in linked_edits {
 4589                buffer.update(cx, |buffer, cx| {
 4590                    let snapshot = buffer.snapshot();
 4591                    let edits = edits
 4592                        .into_iter()
 4593                        .map(|(range, text)| {
 4594                            use text::ToPoint as TP;
 4595                            let end_point = TP::to_point(&range.end, &snapshot);
 4596                            let start_point = TP::to_point(&range.start, &snapshot);
 4597                            (start_point..end_point, text)
 4598                        })
 4599                        .sorted_by_key(|(range, _)| range.start)
 4600                        .collect::<Vec<_>>();
 4601                    buffer.edit(edits, None, cx);
 4602                })
 4603            }
 4604
 4605            this.refresh_inline_completion(true, false, cx);
 4606        });
 4607
 4608        let show_new_completions_on_confirm = completion
 4609            .confirm
 4610            .as_ref()
 4611            .map_or(false, |confirm| confirm(intent, cx));
 4612        if show_new_completions_on_confirm {
 4613            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4614        }
 4615
 4616        let provider = self.completion_provider.as_ref()?;
 4617        let apply_edits = provider.apply_additional_edits_for_completion(
 4618            buffer_handle,
 4619            completion.clone(),
 4620            true,
 4621            cx,
 4622        );
 4623
 4624        let editor_settings = EditorSettings::get_global(cx);
 4625        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4626            // After the code completion is finished, users often want to know what signatures are needed.
 4627            // so we should automatically call signature_help
 4628            self.show_signature_help(&ShowSignatureHelp, cx);
 4629        }
 4630
 4631        Some(cx.foreground_executor().spawn(async move {
 4632            apply_edits.await?;
 4633            Ok(())
 4634        }))
 4635    }
 4636
 4637    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4638        let mut context_menu = self.context_menu.write();
 4639        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4640            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4641                // Toggle if we're selecting the same one
 4642                *context_menu = None;
 4643                cx.notify();
 4644                return;
 4645            } else {
 4646                // Otherwise, clear it and start a new one
 4647                *context_menu = None;
 4648                cx.notify();
 4649            }
 4650        }
 4651        drop(context_menu);
 4652        let snapshot = self.snapshot(cx);
 4653        let deployed_from_indicator = action.deployed_from_indicator;
 4654        let mut task = self.code_actions_task.take();
 4655        let action = action.clone();
 4656        cx.spawn(|editor, mut cx| async move {
 4657            while let Some(prev_task) = task {
 4658                prev_task.await.log_err();
 4659                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4660            }
 4661
 4662            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4663                if editor.focus_handle.is_focused(cx) {
 4664                    let multibuffer_point = action
 4665                        .deployed_from_indicator
 4666                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4667                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4668                    let (buffer, buffer_row) = snapshot
 4669                        .buffer_snapshot
 4670                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4671                        .and_then(|(buffer_snapshot, range)| {
 4672                            editor
 4673                                .buffer
 4674                                .read(cx)
 4675                                .buffer(buffer_snapshot.remote_id())
 4676                                .map(|buffer| (buffer, range.start.row))
 4677                        })?;
 4678                    let (_, code_actions) = editor
 4679                        .available_code_actions
 4680                        .clone()
 4681                        .and_then(|(location, code_actions)| {
 4682                            let snapshot = location.buffer.read(cx).snapshot();
 4683                            let point_range = location.range.to_point(&snapshot);
 4684                            let point_range = point_range.start.row..=point_range.end.row;
 4685                            if point_range.contains(&buffer_row) {
 4686                                Some((location, code_actions))
 4687                            } else {
 4688                                None
 4689                            }
 4690                        })
 4691                        .unzip();
 4692                    let buffer_id = buffer.read(cx).remote_id();
 4693                    let tasks = editor
 4694                        .tasks
 4695                        .get(&(buffer_id, buffer_row))
 4696                        .map(|t| Arc::new(t.to_owned()));
 4697                    if tasks.is_none() && code_actions.is_none() {
 4698                        return None;
 4699                    }
 4700
 4701                    editor.completion_tasks.clear();
 4702                    editor.discard_inline_completion(false, cx);
 4703                    let task_context =
 4704                        tasks
 4705                            .as_ref()
 4706                            .zip(editor.project.clone())
 4707                            .map(|(tasks, project)| {
 4708                                let position = Point::new(buffer_row, tasks.column);
 4709                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4710                                let location = Location {
 4711                                    buffer: buffer.clone(),
 4712                                    range: range_start..range_start,
 4713                                };
 4714                                // Fill in the environmental variables from the tree-sitter captures
 4715                                let mut captured_task_variables = TaskVariables::default();
 4716                                for (capture_name, value) in tasks.extra_variables.clone() {
 4717                                    captured_task_variables.insert(
 4718                                        task::VariableName::Custom(capture_name.into()),
 4719                                        value.clone(),
 4720                                    );
 4721                                }
 4722                                project.update(cx, |project, cx| {
 4723                                    project.task_store().update(cx, |task_store, cx| {
 4724                                        task_store.task_context_for_location(
 4725                                            captured_task_variables,
 4726                                            location,
 4727                                            cx,
 4728                                        )
 4729                                    })
 4730                                })
 4731                            });
 4732
 4733                    Some(cx.spawn(|editor, mut cx| async move {
 4734                        let task_context = match task_context {
 4735                            Some(task_context) => task_context.await,
 4736                            None => None,
 4737                        };
 4738                        let resolved_tasks =
 4739                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4740                                Arc::new(ResolvedTasks {
 4741                                    templates: tasks
 4742                                        .templates
 4743                                        .iter()
 4744                                        .filter_map(|(kind, template)| {
 4745                                            template
 4746                                                .resolve_task(&kind.to_id_base(), &task_context)
 4747                                                .map(|task| (kind.clone(), task))
 4748                                        })
 4749                                        .collect(),
 4750                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4751                                        multibuffer_point.row,
 4752                                        tasks.column,
 4753                                    )),
 4754                                })
 4755                            });
 4756                        let spawn_straight_away = resolved_tasks
 4757                            .as_ref()
 4758                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4759                            && code_actions
 4760                                .as_ref()
 4761                                .map_or(true, |actions| actions.is_empty());
 4762                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4763                            *editor.context_menu.write() =
 4764                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4765                                    buffer,
 4766                                    actions: CodeActionContents {
 4767                                        tasks: resolved_tasks,
 4768                                        actions: code_actions,
 4769                                    },
 4770                                    selected_item: Default::default(),
 4771                                    scroll_handle: UniformListScrollHandle::default(),
 4772                                    deployed_from_indicator,
 4773                                }));
 4774                            if spawn_straight_away {
 4775                                if let Some(task) = editor.confirm_code_action(
 4776                                    &ConfirmCodeAction { item_ix: Some(0) },
 4777                                    cx,
 4778                                ) {
 4779                                    cx.notify();
 4780                                    return task;
 4781                                }
 4782                            }
 4783                            cx.notify();
 4784                            Task::ready(Ok(()))
 4785                        }) {
 4786                            task.await
 4787                        } else {
 4788                            Ok(())
 4789                        }
 4790                    }))
 4791                } else {
 4792                    Some(Task::ready(Ok(())))
 4793                }
 4794            })?;
 4795            if let Some(task) = spawned_test_task {
 4796                task.await?;
 4797            }
 4798
 4799            Ok::<_, anyhow::Error>(())
 4800        })
 4801        .detach_and_log_err(cx);
 4802    }
 4803
 4804    pub fn confirm_code_action(
 4805        &mut self,
 4806        action: &ConfirmCodeAction,
 4807        cx: &mut ViewContext<Self>,
 4808    ) -> Option<Task<Result<()>>> {
 4809        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4810            menu
 4811        } else {
 4812            return None;
 4813        };
 4814        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4815        let action = actions_menu.actions.get(action_ix)?;
 4816        let title = action.label();
 4817        let buffer = actions_menu.buffer;
 4818        let workspace = self.workspace()?;
 4819
 4820        match action {
 4821            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4822                workspace.update(cx, |workspace, cx| {
 4823                    workspace::tasks::schedule_resolved_task(
 4824                        workspace,
 4825                        task_source_kind,
 4826                        resolved_task,
 4827                        false,
 4828                        cx,
 4829                    );
 4830
 4831                    Some(Task::ready(Ok(())))
 4832                })
 4833            }
 4834            CodeActionsItem::CodeAction {
 4835                excerpt_id,
 4836                action,
 4837                provider,
 4838            } => {
 4839                let apply_code_action =
 4840                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4841                let workspace = workspace.downgrade();
 4842                Some(cx.spawn(|editor, cx| async move {
 4843                    let project_transaction = apply_code_action.await?;
 4844                    Self::open_project_transaction(
 4845                        &editor,
 4846                        workspace,
 4847                        project_transaction,
 4848                        title,
 4849                        cx,
 4850                    )
 4851                    .await
 4852                }))
 4853            }
 4854        }
 4855    }
 4856
 4857    pub async fn open_project_transaction(
 4858        this: &WeakView<Editor>,
 4859        workspace: WeakView<Workspace>,
 4860        transaction: ProjectTransaction,
 4861        title: String,
 4862        mut cx: AsyncWindowContext,
 4863    ) -> Result<()> {
 4864        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4865        cx.update(|cx| {
 4866            entries.sort_unstable_by_key(|(buffer, _)| {
 4867                buffer.read(cx).file().map(|f| f.path().clone())
 4868            });
 4869        })?;
 4870
 4871        // If the project transaction's edits are all contained within this editor, then
 4872        // avoid opening a new editor to display them.
 4873
 4874        if let Some((buffer, transaction)) = entries.first() {
 4875            if entries.len() == 1 {
 4876                let excerpt = this.update(&mut cx, |editor, cx| {
 4877                    editor
 4878                        .buffer()
 4879                        .read(cx)
 4880                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4881                })?;
 4882                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4883                    if excerpted_buffer == *buffer {
 4884                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4885                            let excerpt_range = excerpt_range.to_offset(buffer);
 4886                            buffer
 4887                                .edited_ranges_for_transaction::<usize>(transaction)
 4888                                .all(|range| {
 4889                                    excerpt_range.start <= range.start
 4890                                        && excerpt_range.end >= range.end
 4891                                })
 4892                        })?;
 4893
 4894                        if all_edits_within_excerpt {
 4895                            return Ok(());
 4896                        }
 4897                    }
 4898                }
 4899            }
 4900        } else {
 4901            return Ok(());
 4902        }
 4903
 4904        let mut ranges_to_highlight = Vec::new();
 4905        let excerpt_buffer = cx.new_model(|cx| {
 4906            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4907            for (buffer_handle, transaction) in &entries {
 4908                let buffer = buffer_handle.read(cx);
 4909                ranges_to_highlight.extend(
 4910                    multibuffer.push_excerpts_with_context_lines(
 4911                        buffer_handle.clone(),
 4912                        buffer
 4913                            .edited_ranges_for_transaction::<usize>(transaction)
 4914                            .collect(),
 4915                        DEFAULT_MULTIBUFFER_CONTEXT,
 4916                        cx,
 4917                    ),
 4918                );
 4919            }
 4920            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4921            multibuffer
 4922        })?;
 4923
 4924        workspace.update(&mut cx, |workspace, cx| {
 4925            let project = workspace.project().clone();
 4926            let editor =
 4927                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4928            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4929            editor.update(cx, |editor, cx| {
 4930                editor.highlight_background::<Self>(
 4931                    &ranges_to_highlight,
 4932                    |theme| theme.editor_highlighted_line_background,
 4933                    cx,
 4934                );
 4935            });
 4936        })?;
 4937
 4938        Ok(())
 4939    }
 4940
 4941    pub fn clear_code_action_providers(&mut self) {
 4942        self.code_action_providers.clear();
 4943        self.available_code_actions.take();
 4944    }
 4945
 4946    pub fn push_code_action_provider(
 4947        &mut self,
 4948        provider: Arc<dyn CodeActionProvider>,
 4949        cx: &mut ViewContext<Self>,
 4950    ) {
 4951        self.code_action_providers.push(provider);
 4952        self.refresh_code_actions(cx);
 4953    }
 4954
 4955    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4956        let buffer = self.buffer.read(cx);
 4957        let newest_selection = self.selections.newest_anchor().clone();
 4958        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4959        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4960        if start_buffer != end_buffer {
 4961            return None;
 4962        }
 4963
 4964        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4965            cx.background_executor()
 4966                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4967                .await;
 4968
 4969            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4970                let providers = this.code_action_providers.clone();
 4971                let tasks = this
 4972                    .code_action_providers
 4973                    .iter()
 4974                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4975                    .collect::<Vec<_>>();
 4976                (providers, tasks)
 4977            })?;
 4978
 4979            let mut actions = Vec::new();
 4980            for (provider, provider_actions) in
 4981                providers.into_iter().zip(future::join_all(tasks).await)
 4982            {
 4983                if let Some(provider_actions) = provider_actions.log_err() {
 4984                    actions.extend(provider_actions.into_iter().map(|action| {
 4985                        AvailableCodeAction {
 4986                            excerpt_id: newest_selection.start.excerpt_id,
 4987                            action,
 4988                            provider: provider.clone(),
 4989                        }
 4990                    }));
 4991                }
 4992            }
 4993
 4994            this.update(&mut cx, |this, cx| {
 4995                this.available_code_actions = if actions.is_empty() {
 4996                    None
 4997                } else {
 4998                    Some((
 4999                        Location {
 5000                            buffer: start_buffer,
 5001                            range: start..end,
 5002                        },
 5003                        actions.into(),
 5004                    ))
 5005                };
 5006                cx.notify();
 5007            })
 5008        }));
 5009        None
 5010    }
 5011
 5012    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5013        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5014            self.show_git_blame_inline = false;
 5015
 5016            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5017                cx.background_executor().timer(delay).await;
 5018
 5019                this.update(&mut cx, |this, cx| {
 5020                    this.show_git_blame_inline = true;
 5021                    cx.notify();
 5022                })
 5023                .log_err();
 5024            }));
 5025        }
 5026    }
 5027
 5028    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5029        if self.pending_rename.is_some() {
 5030            return None;
 5031        }
 5032
 5033        let provider = self.semantics_provider.clone()?;
 5034        let buffer = self.buffer.read(cx);
 5035        let newest_selection = self.selections.newest_anchor().clone();
 5036        let cursor_position = newest_selection.head();
 5037        let (cursor_buffer, cursor_buffer_position) =
 5038            buffer.text_anchor_for_position(cursor_position, cx)?;
 5039        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5040        if cursor_buffer != tail_buffer {
 5041            return None;
 5042        }
 5043
 5044        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5045            cx.background_executor()
 5046                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5047                .await;
 5048
 5049            let highlights = if let Some(highlights) = cx
 5050                .update(|cx| {
 5051                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5052                })
 5053                .ok()
 5054                .flatten()
 5055            {
 5056                highlights.await.log_err()
 5057            } else {
 5058                None
 5059            };
 5060
 5061            if let Some(highlights) = highlights {
 5062                this.update(&mut cx, |this, cx| {
 5063                    if this.pending_rename.is_some() {
 5064                        return;
 5065                    }
 5066
 5067                    let buffer_id = cursor_position.buffer_id;
 5068                    let buffer = this.buffer.read(cx);
 5069                    if !buffer
 5070                        .text_anchor_for_position(cursor_position, cx)
 5071                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5072                    {
 5073                        return;
 5074                    }
 5075
 5076                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5077                    let mut write_ranges = Vec::new();
 5078                    let mut read_ranges = Vec::new();
 5079                    for highlight in highlights {
 5080                        for (excerpt_id, excerpt_range) in
 5081                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5082                        {
 5083                            let start = highlight
 5084                                .range
 5085                                .start
 5086                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5087                            let end = highlight
 5088                                .range
 5089                                .end
 5090                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5091                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5092                                continue;
 5093                            }
 5094
 5095                            let range = Anchor {
 5096                                buffer_id,
 5097                                excerpt_id,
 5098                                text_anchor: start,
 5099                            }..Anchor {
 5100                                buffer_id,
 5101                                excerpt_id,
 5102                                text_anchor: end,
 5103                            };
 5104                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5105                                write_ranges.push(range);
 5106                            } else {
 5107                                read_ranges.push(range);
 5108                            }
 5109                        }
 5110                    }
 5111
 5112                    this.highlight_background::<DocumentHighlightRead>(
 5113                        &read_ranges,
 5114                        |theme| theme.editor_document_highlight_read_background,
 5115                        cx,
 5116                    );
 5117                    this.highlight_background::<DocumentHighlightWrite>(
 5118                        &write_ranges,
 5119                        |theme| theme.editor_document_highlight_write_background,
 5120                        cx,
 5121                    );
 5122                    cx.notify();
 5123                })
 5124                .log_err();
 5125            }
 5126        }));
 5127        None
 5128    }
 5129
 5130    pub fn refresh_inline_completion(
 5131        &mut self,
 5132        debounce: bool,
 5133        user_requested: bool,
 5134        cx: &mut ViewContext<Self>,
 5135    ) -> Option<()> {
 5136        let provider = self.inline_completion_provider()?;
 5137        let cursor = self.selections.newest_anchor().head();
 5138        let (buffer, cursor_buffer_position) =
 5139            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5140
 5141        if !user_requested
 5142            && (!self.enable_inline_completions
 5143                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5144        {
 5145            self.discard_inline_completion(false, cx);
 5146            return None;
 5147        }
 5148
 5149        self.update_visible_inline_completion(cx);
 5150        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5151        Some(())
 5152    }
 5153
 5154    fn cycle_inline_completion(
 5155        &mut self,
 5156        direction: Direction,
 5157        cx: &mut ViewContext<Self>,
 5158    ) -> Option<()> {
 5159        let provider = self.inline_completion_provider()?;
 5160        let cursor = self.selections.newest_anchor().head();
 5161        let (buffer, cursor_buffer_position) =
 5162            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5163        if !self.enable_inline_completions
 5164            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5165        {
 5166            return None;
 5167        }
 5168
 5169        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5170        self.update_visible_inline_completion(cx);
 5171
 5172        Some(())
 5173    }
 5174
 5175    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5176        if !self.has_active_inline_completion(cx) {
 5177            self.refresh_inline_completion(false, true, cx);
 5178            return;
 5179        }
 5180
 5181        self.update_visible_inline_completion(cx);
 5182    }
 5183
 5184    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5185        self.show_cursor_names(cx);
 5186    }
 5187
 5188    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5189        self.show_cursor_names = true;
 5190        cx.notify();
 5191        cx.spawn(|this, mut cx| async move {
 5192            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5193            this.update(&mut cx, |this, cx| {
 5194                this.show_cursor_names = false;
 5195                cx.notify()
 5196            })
 5197            .ok()
 5198        })
 5199        .detach();
 5200    }
 5201
 5202    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5203        if self.has_active_inline_completion(cx) {
 5204            self.cycle_inline_completion(Direction::Next, cx);
 5205        } else {
 5206            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5207            if is_copilot_disabled {
 5208                cx.propagate();
 5209            }
 5210        }
 5211    }
 5212
 5213    pub fn previous_inline_completion(
 5214        &mut self,
 5215        _: &PreviousInlineCompletion,
 5216        cx: &mut ViewContext<Self>,
 5217    ) {
 5218        if self.has_active_inline_completion(cx) {
 5219            self.cycle_inline_completion(Direction::Prev, cx);
 5220        } else {
 5221            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5222            if is_copilot_disabled {
 5223                cx.propagate();
 5224            }
 5225        }
 5226    }
 5227
 5228    pub fn accept_inline_completion(
 5229        &mut self,
 5230        _: &AcceptInlineCompletion,
 5231        cx: &mut ViewContext<Self>,
 5232    ) {
 5233        let Some(completion) = self.take_active_inline_completion(cx) else {
 5234            return;
 5235        };
 5236        if let Some(provider) = self.inline_completion_provider() {
 5237            provider.accept(cx);
 5238        }
 5239
 5240        cx.emit(EditorEvent::InputHandled {
 5241            utf16_range_to_replace: None,
 5242            text: completion.text.to_string().into(),
 5243        });
 5244
 5245        if let Some(range) = completion.delete_range {
 5246            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5247        }
 5248        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5249        self.refresh_inline_completion(true, true, cx);
 5250        cx.notify();
 5251    }
 5252
 5253    pub fn accept_partial_inline_completion(
 5254        &mut self,
 5255        _: &AcceptPartialInlineCompletion,
 5256        cx: &mut ViewContext<Self>,
 5257    ) {
 5258        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5259            if let Some(completion) = self.take_active_inline_completion(cx) {
 5260                let mut partial_completion = completion
 5261                    .text
 5262                    .chars()
 5263                    .by_ref()
 5264                    .take_while(|c| c.is_alphabetic())
 5265                    .collect::<String>();
 5266                if partial_completion.is_empty() {
 5267                    partial_completion = completion
 5268                        .text
 5269                        .chars()
 5270                        .by_ref()
 5271                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5272                        .collect::<String>();
 5273                }
 5274
 5275                cx.emit(EditorEvent::InputHandled {
 5276                    utf16_range_to_replace: None,
 5277                    text: partial_completion.clone().into(),
 5278                });
 5279
 5280                if let Some(range) = completion.delete_range {
 5281                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5282                }
 5283                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5284
 5285                self.refresh_inline_completion(true, true, cx);
 5286                cx.notify();
 5287            }
 5288        }
 5289    }
 5290
 5291    fn discard_inline_completion(
 5292        &mut self,
 5293        should_report_inline_completion_event: bool,
 5294        cx: &mut ViewContext<Self>,
 5295    ) -> bool {
 5296        if let Some(provider) = self.inline_completion_provider() {
 5297            provider.discard(should_report_inline_completion_event, cx);
 5298        }
 5299
 5300        self.take_active_inline_completion(cx).is_some()
 5301    }
 5302
 5303    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5304        if let Some(completion) = self.active_inline_completion.as_ref() {
 5305            let buffer = self.buffer.read(cx).read(cx);
 5306            completion.position.is_valid(&buffer)
 5307        } else {
 5308            false
 5309        }
 5310    }
 5311
 5312    fn take_active_inline_completion(
 5313        &mut self,
 5314        cx: &mut ViewContext<Self>,
 5315    ) -> Option<CompletionState> {
 5316        let completion = self.active_inline_completion.take()?;
 5317        let render_inlay_ids = completion.render_inlay_ids.clone();
 5318        self.display_map.update(cx, |map, cx| {
 5319            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5320        });
 5321        let buffer = self.buffer.read(cx).read(cx);
 5322
 5323        if completion.position.is_valid(&buffer) {
 5324            Some(completion)
 5325        } else {
 5326            None
 5327        }
 5328    }
 5329
 5330    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5331        let selection = self.selections.newest_anchor();
 5332        let cursor = selection.head();
 5333
 5334        let excerpt_id = cursor.excerpt_id;
 5335
 5336        if self.context_menu.read().is_none()
 5337            && self.completion_tasks.is_empty()
 5338            && selection.start == selection.end
 5339        {
 5340            if let Some(provider) = self.inline_completion_provider() {
 5341                if let Some((buffer, cursor_buffer_position)) =
 5342                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5343                {
 5344                    if let Some(proposal) =
 5345                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5346                    {
 5347                        let mut to_remove = Vec::new();
 5348                        if let Some(completion) = self.active_inline_completion.take() {
 5349                            to_remove.extend(completion.render_inlay_ids.iter());
 5350                        }
 5351
 5352                        let to_add = proposal
 5353                            .inlays
 5354                            .iter()
 5355                            .filter_map(|inlay| {
 5356                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5357                                let id = post_inc(&mut self.next_inlay_id);
 5358                                match inlay {
 5359                                    InlayProposal::Hint(position, hint) => {
 5360                                        let position =
 5361                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5362                                        Some(Inlay::hint(id, position, hint))
 5363                                    }
 5364                                    InlayProposal::Suggestion(position, text) => {
 5365                                        let position =
 5366                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5367                                        Some(Inlay::suggestion(id, position, text.clone()))
 5368                                    }
 5369                                }
 5370                            })
 5371                            .collect_vec();
 5372
 5373                        self.active_inline_completion = Some(CompletionState {
 5374                            position: cursor,
 5375                            text: proposal.text,
 5376                            delete_range: proposal.delete_range.and_then(|range| {
 5377                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5378                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5379                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5380                                Some(start?..end?)
 5381                            }),
 5382                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5383                        });
 5384
 5385                        self.display_map
 5386                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5387
 5388                        cx.notify();
 5389                        return;
 5390                    }
 5391                }
 5392            }
 5393        }
 5394
 5395        self.discard_inline_completion(false, cx);
 5396    }
 5397
 5398    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5399        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5400    }
 5401
 5402    fn render_code_actions_indicator(
 5403        &self,
 5404        _style: &EditorStyle,
 5405        row: DisplayRow,
 5406        is_active: bool,
 5407        cx: &mut ViewContext<Self>,
 5408    ) -> Option<IconButton> {
 5409        if self.available_code_actions.is_some() {
 5410            Some(
 5411                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5412                    .shape(ui::IconButtonShape::Square)
 5413                    .icon_size(IconSize::XSmall)
 5414                    .icon_color(Color::Muted)
 5415                    .selected(is_active)
 5416                    .tooltip({
 5417                        let focus_handle = self.focus_handle.clone();
 5418                        move |cx| {
 5419                            Tooltip::for_action_in(
 5420                                "Toggle Code Actions",
 5421                                &ToggleCodeActions {
 5422                                    deployed_from_indicator: None,
 5423                                },
 5424                                &focus_handle,
 5425                                cx,
 5426                            )
 5427                        }
 5428                    })
 5429                    .on_click(cx.listener(move |editor, _e, cx| {
 5430                        editor.focus(cx);
 5431                        editor.toggle_code_actions(
 5432                            &ToggleCodeActions {
 5433                                deployed_from_indicator: Some(row),
 5434                            },
 5435                            cx,
 5436                        );
 5437                    })),
 5438            )
 5439        } else {
 5440            None
 5441        }
 5442    }
 5443
 5444    fn clear_tasks(&mut self) {
 5445        self.tasks.clear()
 5446    }
 5447
 5448    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5449        if self.tasks.insert(key, value).is_some() {
 5450            // This case should hopefully be rare, but just in case...
 5451            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5452        }
 5453    }
 5454
 5455    fn render_run_indicator(
 5456        &self,
 5457        _style: &EditorStyle,
 5458        is_active: bool,
 5459        row: DisplayRow,
 5460        cx: &mut ViewContext<Self>,
 5461    ) -> IconButton {
 5462        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5463            .shape(ui::IconButtonShape::Square)
 5464            .icon_size(IconSize::XSmall)
 5465            .icon_color(Color::Muted)
 5466            .selected(is_active)
 5467            .on_click(cx.listener(move |editor, _e, cx| {
 5468                editor.focus(cx);
 5469                editor.toggle_code_actions(
 5470                    &ToggleCodeActions {
 5471                        deployed_from_indicator: Some(row),
 5472                    },
 5473                    cx,
 5474                );
 5475            }))
 5476    }
 5477
 5478    pub fn context_menu_visible(&self) -> bool {
 5479        self.context_menu
 5480            .read()
 5481            .as_ref()
 5482            .map_or(false, |menu| menu.visible())
 5483    }
 5484
 5485    fn render_context_menu(
 5486        &self,
 5487        cursor_position: DisplayPoint,
 5488        style: &EditorStyle,
 5489        max_height: Pixels,
 5490        cx: &mut ViewContext<Editor>,
 5491    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5492        self.context_menu.read().as_ref().map(|menu| {
 5493            menu.render(
 5494                cursor_position,
 5495                style,
 5496                max_height,
 5497                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5498                cx,
 5499            )
 5500        })
 5501    }
 5502
 5503    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5504        cx.notify();
 5505        self.completion_tasks.clear();
 5506        let context_menu = self.context_menu.write().take();
 5507        if context_menu.is_some() {
 5508            self.update_visible_inline_completion(cx);
 5509        }
 5510        context_menu
 5511    }
 5512
 5513    pub fn insert_snippet(
 5514        &mut self,
 5515        insertion_ranges: &[Range<usize>],
 5516        snippet: Snippet,
 5517        cx: &mut ViewContext<Self>,
 5518    ) -> Result<()> {
 5519        struct Tabstop<T> {
 5520            is_end_tabstop: bool,
 5521            ranges: Vec<Range<T>>,
 5522        }
 5523
 5524        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5525            let snippet_text: Arc<str> = snippet.text.clone().into();
 5526            buffer.edit(
 5527                insertion_ranges
 5528                    .iter()
 5529                    .cloned()
 5530                    .map(|range| (range, snippet_text.clone())),
 5531                Some(AutoindentMode::EachLine),
 5532                cx,
 5533            );
 5534
 5535            let snapshot = &*buffer.read(cx);
 5536            let snippet = &snippet;
 5537            snippet
 5538                .tabstops
 5539                .iter()
 5540                .map(|tabstop| {
 5541                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5542                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5543                    });
 5544                    let mut tabstop_ranges = tabstop
 5545                        .iter()
 5546                        .flat_map(|tabstop_range| {
 5547                            let mut delta = 0_isize;
 5548                            insertion_ranges.iter().map(move |insertion_range| {
 5549                                let insertion_start = insertion_range.start as isize + delta;
 5550                                delta +=
 5551                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5552
 5553                                let start = ((insertion_start + tabstop_range.start) as usize)
 5554                                    .min(snapshot.len());
 5555                                let end = ((insertion_start + tabstop_range.end) as usize)
 5556                                    .min(snapshot.len());
 5557                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5558                            })
 5559                        })
 5560                        .collect::<Vec<_>>();
 5561                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5562
 5563                    Tabstop {
 5564                        is_end_tabstop,
 5565                        ranges: tabstop_ranges,
 5566                    }
 5567                })
 5568                .collect::<Vec<_>>()
 5569        });
 5570        if let Some(tabstop) = tabstops.first() {
 5571            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5572                s.select_ranges(tabstop.ranges.iter().cloned());
 5573            });
 5574
 5575            // If we're already at the last tabstop and it's at the end of the snippet,
 5576            // we're done, we don't need to keep the state around.
 5577            if !tabstop.is_end_tabstop {
 5578                let ranges = tabstops
 5579                    .into_iter()
 5580                    .map(|tabstop| tabstop.ranges)
 5581                    .collect::<Vec<_>>();
 5582                self.snippet_stack.push(SnippetState {
 5583                    active_index: 0,
 5584                    ranges,
 5585                });
 5586            }
 5587
 5588            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5589            if self.autoclose_regions.is_empty() {
 5590                let snapshot = self.buffer.read(cx).snapshot(cx);
 5591                for selection in &mut self.selections.all::<Point>(cx) {
 5592                    let selection_head = selection.head();
 5593                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5594                        continue;
 5595                    };
 5596
 5597                    let mut bracket_pair = None;
 5598                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5599                    let prev_chars = snapshot
 5600                        .reversed_chars_at(selection_head)
 5601                        .collect::<String>();
 5602                    for (pair, enabled) in scope.brackets() {
 5603                        if enabled
 5604                            && pair.close
 5605                            && prev_chars.starts_with(pair.start.as_str())
 5606                            && next_chars.starts_with(pair.end.as_str())
 5607                        {
 5608                            bracket_pair = Some(pair.clone());
 5609                            break;
 5610                        }
 5611                    }
 5612                    if let Some(pair) = bracket_pair {
 5613                        let start = snapshot.anchor_after(selection_head);
 5614                        let end = snapshot.anchor_after(selection_head);
 5615                        self.autoclose_regions.push(AutocloseRegion {
 5616                            selection_id: selection.id,
 5617                            range: start..end,
 5618                            pair,
 5619                        });
 5620                    }
 5621                }
 5622            }
 5623        }
 5624        Ok(())
 5625    }
 5626
 5627    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5628        self.move_to_snippet_tabstop(Bias::Right, cx)
 5629    }
 5630
 5631    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5632        self.move_to_snippet_tabstop(Bias::Left, cx)
 5633    }
 5634
 5635    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5636        if let Some(mut snippet) = self.snippet_stack.pop() {
 5637            match bias {
 5638                Bias::Left => {
 5639                    if snippet.active_index > 0 {
 5640                        snippet.active_index -= 1;
 5641                    } else {
 5642                        self.snippet_stack.push(snippet);
 5643                        return false;
 5644                    }
 5645                }
 5646                Bias::Right => {
 5647                    if snippet.active_index + 1 < snippet.ranges.len() {
 5648                        snippet.active_index += 1;
 5649                    } else {
 5650                        self.snippet_stack.push(snippet);
 5651                        return false;
 5652                    }
 5653                }
 5654            }
 5655            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5656                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5657                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5658                });
 5659                // If snippet state is not at the last tabstop, push it back on the stack
 5660                if snippet.active_index + 1 < snippet.ranges.len() {
 5661                    self.snippet_stack.push(snippet);
 5662                }
 5663                return true;
 5664            }
 5665        }
 5666
 5667        false
 5668    }
 5669
 5670    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5671        self.transact(cx, |this, cx| {
 5672            this.select_all(&SelectAll, cx);
 5673            this.insert("", cx);
 5674        });
 5675    }
 5676
 5677    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5678        self.transact(cx, |this, cx| {
 5679            this.select_autoclose_pair(cx);
 5680            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5681            if !this.linked_edit_ranges.is_empty() {
 5682                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5683                let snapshot = this.buffer.read(cx).snapshot(cx);
 5684
 5685                for selection in selections.iter() {
 5686                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5687                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5688                    if selection_start.buffer_id != selection_end.buffer_id {
 5689                        continue;
 5690                    }
 5691                    if let Some(ranges) =
 5692                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5693                    {
 5694                        for (buffer, entries) in ranges {
 5695                            linked_ranges.entry(buffer).or_default().extend(entries);
 5696                        }
 5697                    }
 5698                }
 5699            }
 5700
 5701            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5702            if !this.selections.line_mode {
 5703                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5704                for selection in &mut selections {
 5705                    if selection.is_empty() {
 5706                        let old_head = selection.head();
 5707                        let mut new_head =
 5708                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5709                                .to_point(&display_map);
 5710                        if let Some((buffer, line_buffer_range)) = display_map
 5711                            .buffer_snapshot
 5712                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5713                        {
 5714                            let indent_size =
 5715                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5716                            let indent_len = match indent_size.kind {
 5717                                IndentKind::Space => {
 5718                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5719                                }
 5720                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5721                            };
 5722                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5723                                let indent_len = indent_len.get();
 5724                                new_head = cmp::min(
 5725                                    new_head,
 5726                                    MultiBufferPoint::new(
 5727                                        old_head.row,
 5728                                        ((old_head.column - 1) / indent_len) * indent_len,
 5729                                    ),
 5730                                );
 5731                            }
 5732                        }
 5733
 5734                        selection.set_head(new_head, SelectionGoal::None);
 5735                    }
 5736                }
 5737            }
 5738
 5739            this.signature_help_state.set_backspace_pressed(true);
 5740            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5741            this.insert("", cx);
 5742            let empty_str: Arc<str> = Arc::from("");
 5743            for (buffer, edits) in linked_ranges {
 5744                let snapshot = buffer.read(cx).snapshot();
 5745                use text::ToPoint as TP;
 5746
 5747                let edits = edits
 5748                    .into_iter()
 5749                    .map(|range| {
 5750                        let end_point = TP::to_point(&range.end, &snapshot);
 5751                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5752
 5753                        if end_point == start_point {
 5754                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5755                                .saturating_sub(1);
 5756                            start_point = TP::to_point(&offset, &snapshot);
 5757                        };
 5758
 5759                        (start_point..end_point, empty_str.clone())
 5760                    })
 5761                    .sorted_by_key(|(range, _)| range.start)
 5762                    .collect::<Vec<_>>();
 5763                buffer.update(cx, |this, cx| {
 5764                    this.edit(edits, None, cx);
 5765                })
 5766            }
 5767            this.refresh_inline_completion(true, false, cx);
 5768            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5769        });
 5770    }
 5771
 5772    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5773        self.transact(cx, |this, cx| {
 5774            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5775                let line_mode = s.line_mode;
 5776                s.move_with(|map, selection| {
 5777                    if selection.is_empty() && !line_mode {
 5778                        let cursor = movement::right(map, selection.head());
 5779                        selection.end = cursor;
 5780                        selection.reversed = true;
 5781                        selection.goal = SelectionGoal::None;
 5782                    }
 5783                })
 5784            });
 5785            this.insert("", cx);
 5786            this.refresh_inline_completion(true, false, cx);
 5787        });
 5788    }
 5789
 5790    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5791        if self.move_to_prev_snippet_tabstop(cx) {
 5792            return;
 5793        }
 5794
 5795        self.outdent(&Outdent, cx);
 5796    }
 5797
 5798    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5799        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5800            return;
 5801        }
 5802
 5803        let mut selections = self.selections.all_adjusted(cx);
 5804        let buffer = self.buffer.read(cx);
 5805        let snapshot = buffer.snapshot(cx);
 5806        let rows_iter = selections.iter().map(|s| s.head().row);
 5807        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5808
 5809        let mut edits = Vec::new();
 5810        let mut prev_edited_row = 0;
 5811        let mut row_delta = 0;
 5812        for selection in &mut selections {
 5813            if selection.start.row != prev_edited_row {
 5814                row_delta = 0;
 5815            }
 5816            prev_edited_row = selection.end.row;
 5817
 5818            // If the selection is non-empty, then increase the indentation of the selected lines.
 5819            if !selection.is_empty() {
 5820                row_delta =
 5821                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5822                continue;
 5823            }
 5824
 5825            // If the selection is empty and the cursor is in the leading whitespace before the
 5826            // suggested indentation, then auto-indent the line.
 5827            let cursor = selection.head();
 5828            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5829            if let Some(suggested_indent) =
 5830                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5831            {
 5832                if cursor.column < suggested_indent.len
 5833                    && cursor.column <= current_indent.len
 5834                    && current_indent.len <= suggested_indent.len
 5835                {
 5836                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5837                    selection.end = selection.start;
 5838                    if row_delta == 0 {
 5839                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5840                            cursor.row,
 5841                            current_indent,
 5842                            suggested_indent,
 5843                        ));
 5844                        row_delta = suggested_indent.len - current_indent.len;
 5845                    }
 5846                    continue;
 5847                }
 5848            }
 5849
 5850            // Otherwise, insert a hard or soft tab.
 5851            let settings = buffer.settings_at(cursor, cx);
 5852            let tab_size = if settings.hard_tabs {
 5853                IndentSize::tab()
 5854            } else {
 5855                let tab_size = settings.tab_size.get();
 5856                let char_column = snapshot
 5857                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5858                    .flat_map(str::chars)
 5859                    .count()
 5860                    + row_delta as usize;
 5861                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5862                IndentSize::spaces(chars_to_next_tab_stop)
 5863            };
 5864            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5865            selection.end = selection.start;
 5866            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5867            row_delta += tab_size.len;
 5868        }
 5869
 5870        self.transact(cx, |this, cx| {
 5871            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5872            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5873            this.refresh_inline_completion(true, false, cx);
 5874        });
 5875    }
 5876
 5877    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5878        if self.read_only(cx) {
 5879            return;
 5880        }
 5881        let mut selections = self.selections.all::<Point>(cx);
 5882        let mut prev_edited_row = 0;
 5883        let mut row_delta = 0;
 5884        let mut edits = Vec::new();
 5885        let buffer = self.buffer.read(cx);
 5886        let snapshot = buffer.snapshot(cx);
 5887        for selection in &mut selections {
 5888            if selection.start.row != prev_edited_row {
 5889                row_delta = 0;
 5890            }
 5891            prev_edited_row = selection.end.row;
 5892
 5893            row_delta =
 5894                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5895        }
 5896
 5897        self.transact(cx, |this, cx| {
 5898            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5899            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5900        });
 5901    }
 5902
 5903    fn indent_selection(
 5904        buffer: &MultiBuffer,
 5905        snapshot: &MultiBufferSnapshot,
 5906        selection: &mut Selection<Point>,
 5907        edits: &mut Vec<(Range<Point>, String)>,
 5908        delta_for_start_row: u32,
 5909        cx: &AppContext,
 5910    ) -> u32 {
 5911        let settings = buffer.settings_at(selection.start, cx);
 5912        let tab_size = settings.tab_size.get();
 5913        let indent_kind = if settings.hard_tabs {
 5914            IndentKind::Tab
 5915        } else {
 5916            IndentKind::Space
 5917        };
 5918        let mut start_row = selection.start.row;
 5919        let mut end_row = selection.end.row + 1;
 5920
 5921        // If a selection ends at the beginning of a line, don't indent
 5922        // that last line.
 5923        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5924            end_row -= 1;
 5925        }
 5926
 5927        // Avoid re-indenting a row that has already been indented by a
 5928        // previous selection, but still update this selection's column
 5929        // to reflect that indentation.
 5930        if delta_for_start_row > 0 {
 5931            start_row += 1;
 5932            selection.start.column += delta_for_start_row;
 5933            if selection.end.row == selection.start.row {
 5934                selection.end.column += delta_for_start_row;
 5935            }
 5936        }
 5937
 5938        let mut delta_for_end_row = 0;
 5939        let has_multiple_rows = start_row + 1 != end_row;
 5940        for row in start_row..end_row {
 5941            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5942            let indent_delta = match (current_indent.kind, indent_kind) {
 5943                (IndentKind::Space, IndentKind::Space) => {
 5944                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5945                    IndentSize::spaces(columns_to_next_tab_stop)
 5946                }
 5947                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5948                (_, IndentKind::Tab) => IndentSize::tab(),
 5949            };
 5950
 5951            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5952                0
 5953            } else {
 5954                selection.start.column
 5955            };
 5956            let row_start = Point::new(row, start);
 5957            edits.push((
 5958                row_start..row_start,
 5959                indent_delta.chars().collect::<String>(),
 5960            ));
 5961
 5962            // Update this selection's endpoints to reflect the indentation.
 5963            if row == selection.start.row {
 5964                selection.start.column += indent_delta.len;
 5965            }
 5966            if row == selection.end.row {
 5967                selection.end.column += indent_delta.len;
 5968                delta_for_end_row = indent_delta.len;
 5969            }
 5970        }
 5971
 5972        if selection.start.row == selection.end.row {
 5973            delta_for_start_row + delta_for_end_row
 5974        } else {
 5975            delta_for_end_row
 5976        }
 5977    }
 5978
 5979    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5980        if self.read_only(cx) {
 5981            return;
 5982        }
 5983        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5984        let selections = self.selections.all::<Point>(cx);
 5985        let mut deletion_ranges = Vec::new();
 5986        let mut last_outdent = None;
 5987        {
 5988            let buffer = self.buffer.read(cx);
 5989            let snapshot = buffer.snapshot(cx);
 5990            for selection in &selections {
 5991                let settings = buffer.settings_at(selection.start, cx);
 5992                let tab_size = settings.tab_size.get();
 5993                let mut rows = selection.spanned_rows(false, &display_map);
 5994
 5995                // Avoid re-outdenting a row that has already been outdented by a
 5996                // previous selection.
 5997                if let Some(last_row) = last_outdent {
 5998                    if last_row == rows.start {
 5999                        rows.start = rows.start.next_row();
 6000                    }
 6001                }
 6002                let has_multiple_rows = rows.len() > 1;
 6003                for row in rows.iter_rows() {
 6004                    let indent_size = snapshot.indent_size_for_line(row);
 6005                    if indent_size.len > 0 {
 6006                        let deletion_len = match indent_size.kind {
 6007                            IndentKind::Space => {
 6008                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6009                                if columns_to_prev_tab_stop == 0 {
 6010                                    tab_size
 6011                                } else {
 6012                                    columns_to_prev_tab_stop
 6013                                }
 6014                            }
 6015                            IndentKind::Tab => 1,
 6016                        };
 6017                        let start = if has_multiple_rows
 6018                            || deletion_len > selection.start.column
 6019                            || indent_size.len < selection.start.column
 6020                        {
 6021                            0
 6022                        } else {
 6023                            selection.start.column - deletion_len
 6024                        };
 6025                        deletion_ranges.push(
 6026                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6027                        );
 6028                        last_outdent = Some(row);
 6029                    }
 6030                }
 6031            }
 6032        }
 6033
 6034        self.transact(cx, |this, cx| {
 6035            this.buffer.update(cx, |buffer, cx| {
 6036                let empty_str: Arc<str> = Arc::default();
 6037                buffer.edit(
 6038                    deletion_ranges
 6039                        .into_iter()
 6040                        .map(|range| (range, empty_str.clone())),
 6041                    None,
 6042                    cx,
 6043                );
 6044            });
 6045            let selections = this.selections.all::<usize>(cx);
 6046            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6047        });
 6048    }
 6049
 6050    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6051        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6052        let selections = self.selections.all::<Point>(cx);
 6053
 6054        let mut new_cursors = Vec::new();
 6055        let mut edit_ranges = Vec::new();
 6056        let mut selections = selections.iter().peekable();
 6057        while let Some(selection) = selections.next() {
 6058            let mut rows = selection.spanned_rows(false, &display_map);
 6059            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6060
 6061            // Accumulate contiguous regions of rows that we want to delete.
 6062            while let Some(next_selection) = selections.peek() {
 6063                let next_rows = next_selection.spanned_rows(false, &display_map);
 6064                if next_rows.start <= rows.end {
 6065                    rows.end = next_rows.end;
 6066                    selections.next().unwrap();
 6067                } else {
 6068                    break;
 6069                }
 6070            }
 6071
 6072            let buffer = &display_map.buffer_snapshot;
 6073            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6074            let edit_end;
 6075            let cursor_buffer_row;
 6076            if buffer.max_point().row >= rows.end.0 {
 6077                // If there's a line after the range, delete the \n from the end of the row range
 6078                // and position the cursor on the next line.
 6079                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6080                cursor_buffer_row = rows.end;
 6081            } else {
 6082                // If there isn't a line after the range, delete the \n from the line before the
 6083                // start of the row range and position the cursor there.
 6084                edit_start = edit_start.saturating_sub(1);
 6085                edit_end = buffer.len();
 6086                cursor_buffer_row = rows.start.previous_row();
 6087            }
 6088
 6089            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6090            *cursor.column_mut() =
 6091                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6092
 6093            new_cursors.push((
 6094                selection.id,
 6095                buffer.anchor_after(cursor.to_point(&display_map)),
 6096            ));
 6097            edit_ranges.push(edit_start..edit_end);
 6098        }
 6099
 6100        self.transact(cx, |this, cx| {
 6101            let buffer = this.buffer.update(cx, |buffer, cx| {
 6102                let empty_str: Arc<str> = Arc::default();
 6103                buffer.edit(
 6104                    edit_ranges
 6105                        .into_iter()
 6106                        .map(|range| (range, empty_str.clone())),
 6107                    None,
 6108                    cx,
 6109                );
 6110                buffer.snapshot(cx)
 6111            });
 6112            let new_selections = new_cursors
 6113                .into_iter()
 6114                .map(|(id, cursor)| {
 6115                    let cursor = cursor.to_point(&buffer);
 6116                    Selection {
 6117                        id,
 6118                        start: cursor,
 6119                        end: cursor,
 6120                        reversed: false,
 6121                        goal: SelectionGoal::None,
 6122                    }
 6123                })
 6124                .collect();
 6125
 6126            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6127                s.select(new_selections);
 6128            });
 6129        });
 6130    }
 6131
 6132    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6133        if self.read_only(cx) {
 6134            return;
 6135        }
 6136        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6137        for selection in self.selections.all::<Point>(cx) {
 6138            let start = MultiBufferRow(selection.start.row);
 6139            let end = if selection.start.row == selection.end.row {
 6140                MultiBufferRow(selection.start.row + 1)
 6141            } else {
 6142                MultiBufferRow(selection.end.row)
 6143            };
 6144
 6145            if let Some(last_row_range) = row_ranges.last_mut() {
 6146                if start <= last_row_range.end {
 6147                    last_row_range.end = end;
 6148                    continue;
 6149                }
 6150            }
 6151            row_ranges.push(start..end);
 6152        }
 6153
 6154        let snapshot = self.buffer.read(cx).snapshot(cx);
 6155        let mut cursor_positions = Vec::new();
 6156        for row_range in &row_ranges {
 6157            let anchor = snapshot.anchor_before(Point::new(
 6158                row_range.end.previous_row().0,
 6159                snapshot.line_len(row_range.end.previous_row()),
 6160            ));
 6161            cursor_positions.push(anchor..anchor);
 6162        }
 6163
 6164        self.transact(cx, |this, cx| {
 6165            for row_range in row_ranges.into_iter().rev() {
 6166                for row in row_range.iter_rows().rev() {
 6167                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6168                    let next_line_row = row.next_row();
 6169                    let indent = snapshot.indent_size_for_line(next_line_row);
 6170                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6171
 6172                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6173                        " "
 6174                    } else {
 6175                        ""
 6176                    };
 6177
 6178                    this.buffer.update(cx, |buffer, cx| {
 6179                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6180                    });
 6181                }
 6182            }
 6183
 6184            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6185                s.select_anchor_ranges(cursor_positions)
 6186            });
 6187        });
 6188    }
 6189
 6190    pub fn sort_lines_case_sensitive(
 6191        &mut self,
 6192        _: &SortLinesCaseSensitive,
 6193        cx: &mut ViewContext<Self>,
 6194    ) {
 6195        self.manipulate_lines(cx, |lines| lines.sort())
 6196    }
 6197
 6198    pub fn sort_lines_case_insensitive(
 6199        &mut self,
 6200        _: &SortLinesCaseInsensitive,
 6201        cx: &mut ViewContext<Self>,
 6202    ) {
 6203        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6204    }
 6205
 6206    pub fn unique_lines_case_insensitive(
 6207        &mut self,
 6208        _: &UniqueLinesCaseInsensitive,
 6209        cx: &mut ViewContext<Self>,
 6210    ) {
 6211        self.manipulate_lines(cx, |lines| {
 6212            let mut seen = HashSet::default();
 6213            lines.retain(|line| seen.insert(line.to_lowercase()));
 6214        })
 6215    }
 6216
 6217    pub fn unique_lines_case_sensitive(
 6218        &mut self,
 6219        _: &UniqueLinesCaseSensitive,
 6220        cx: &mut ViewContext<Self>,
 6221    ) {
 6222        self.manipulate_lines(cx, |lines| {
 6223            let mut seen = HashSet::default();
 6224            lines.retain(|line| seen.insert(*line));
 6225        })
 6226    }
 6227
 6228    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6229        let mut revert_changes = HashMap::default();
 6230        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6231        for hunk in hunks_for_rows(
 6232            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6233            &multi_buffer_snapshot,
 6234        ) {
 6235            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6236        }
 6237        if !revert_changes.is_empty() {
 6238            self.transact(cx, |editor, cx| {
 6239                editor.revert(revert_changes, cx);
 6240            });
 6241        }
 6242    }
 6243
 6244    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6245        let Some(project) = self.project.clone() else {
 6246            return;
 6247        };
 6248        self.reload(project, cx).detach_and_notify_err(cx);
 6249    }
 6250
 6251    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6252        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6253        if !revert_changes.is_empty() {
 6254            self.transact(cx, |editor, cx| {
 6255                editor.revert(revert_changes, cx);
 6256            });
 6257        }
 6258    }
 6259
 6260    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6261        let snapshot = self.buffer.read(cx).snapshot(cx);
 6262        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6263        let mut ranges_by_buffer = HashMap::default();
 6264        self.transact(cx, |editor, cx| {
 6265            for hunk in hunks {
 6266                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6267                    ranges_by_buffer
 6268                        .entry(buffer.clone())
 6269                        .or_insert_with(Vec::new)
 6270                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 6271                }
 6272            }
 6273
 6274            for (buffer, ranges) in ranges_by_buffer {
 6275                buffer.update(cx, |buffer, cx| {
 6276                    buffer.merge_into_base(ranges, cx);
 6277                });
 6278            }
 6279        });
 6280    }
 6281
 6282    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6283        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6284            let project_path = buffer.read(cx).project_path(cx)?;
 6285            let project = self.project.as_ref()?.read(cx);
 6286            let entry = project.entry_for_path(&project_path, cx)?;
 6287            let abs_path = project.absolute_path(&project_path, cx)?;
 6288            let parent = if entry.is_symlink {
 6289                abs_path.canonicalize().ok()?
 6290            } else {
 6291                abs_path
 6292            }
 6293            .parent()?
 6294            .to_path_buf();
 6295            Some(parent)
 6296        }) {
 6297            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6298        }
 6299    }
 6300
 6301    fn gather_revert_changes(
 6302        &mut self,
 6303        selections: &[Selection<Anchor>],
 6304        cx: &mut ViewContext<'_, Editor>,
 6305    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6306        let mut revert_changes = HashMap::default();
 6307        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6308        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6309            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6310        }
 6311        revert_changes
 6312    }
 6313
 6314    pub fn prepare_revert_change(
 6315        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6316        multi_buffer: &Model<MultiBuffer>,
 6317        hunk: &MultiBufferDiffHunk,
 6318        cx: &AppContext,
 6319    ) -> Option<()> {
 6320        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6321        let buffer = buffer.read(cx);
 6322        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6323        let buffer_snapshot = buffer.snapshot();
 6324        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6325        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6326            probe
 6327                .0
 6328                .start
 6329                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6330                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6331        }) {
 6332            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6333            Some(())
 6334        } else {
 6335            None
 6336        }
 6337    }
 6338
 6339    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6340        self.manipulate_lines(cx, |lines| lines.reverse())
 6341    }
 6342
 6343    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6344        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6345    }
 6346
 6347    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6348    where
 6349        Fn: FnMut(&mut Vec<&str>),
 6350    {
 6351        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6352        let buffer = self.buffer.read(cx).snapshot(cx);
 6353
 6354        let mut edits = Vec::new();
 6355
 6356        let selections = self.selections.all::<Point>(cx);
 6357        let mut selections = selections.iter().peekable();
 6358        let mut contiguous_row_selections = Vec::new();
 6359        let mut new_selections = Vec::new();
 6360        let mut added_lines = 0;
 6361        let mut removed_lines = 0;
 6362
 6363        while let Some(selection) = selections.next() {
 6364            let (start_row, end_row) = consume_contiguous_rows(
 6365                &mut contiguous_row_selections,
 6366                selection,
 6367                &display_map,
 6368                &mut selections,
 6369            );
 6370
 6371            let start_point = Point::new(start_row.0, 0);
 6372            let end_point = Point::new(
 6373                end_row.previous_row().0,
 6374                buffer.line_len(end_row.previous_row()),
 6375            );
 6376            let text = buffer
 6377                .text_for_range(start_point..end_point)
 6378                .collect::<String>();
 6379
 6380            let mut lines = text.split('\n').collect_vec();
 6381
 6382            let lines_before = lines.len();
 6383            callback(&mut lines);
 6384            let lines_after = lines.len();
 6385
 6386            edits.push((start_point..end_point, lines.join("\n")));
 6387
 6388            // Selections must change based on added and removed line count
 6389            let start_row =
 6390                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6391            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6392            new_selections.push(Selection {
 6393                id: selection.id,
 6394                start: start_row,
 6395                end: end_row,
 6396                goal: SelectionGoal::None,
 6397                reversed: selection.reversed,
 6398            });
 6399
 6400            if lines_after > lines_before {
 6401                added_lines += lines_after - lines_before;
 6402            } else if lines_before > lines_after {
 6403                removed_lines += lines_before - lines_after;
 6404            }
 6405        }
 6406
 6407        self.transact(cx, |this, cx| {
 6408            let buffer = this.buffer.update(cx, |buffer, cx| {
 6409                buffer.edit(edits, None, cx);
 6410                buffer.snapshot(cx)
 6411            });
 6412
 6413            // Recalculate offsets on newly edited buffer
 6414            let new_selections = new_selections
 6415                .iter()
 6416                .map(|s| {
 6417                    let start_point = Point::new(s.start.0, 0);
 6418                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6419                    Selection {
 6420                        id: s.id,
 6421                        start: buffer.point_to_offset(start_point),
 6422                        end: buffer.point_to_offset(end_point),
 6423                        goal: s.goal,
 6424                        reversed: s.reversed,
 6425                    }
 6426                })
 6427                .collect();
 6428
 6429            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6430                s.select(new_selections);
 6431            });
 6432
 6433            this.request_autoscroll(Autoscroll::fit(), cx);
 6434        });
 6435    }
 6436
 6437    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6438        self.manipulate_text(cx, |text| text.to_uppercase())
 6439    }
 6440
 6441    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6442        self.manipulate_text(cx, |text| text.to_lowercase())
 6443    }
 6444
 6445    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6446        self.manipulate_text(cx, |text| {
 6447            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6448            // https://github.com/rutrum/convert-case/issues/16
 6449            text.split('\n')
 6450                .map(|line| line.to_case(Case::Title))
 6451                .join("\n")
 6452        })
 6453    }
 6454
 6455    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6456        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6457    }
 6458
 6459    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6460        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6461    }
 6462
 6463    pub fn convert_to_upper_camel_case(
 6464        &mut self,
 6465        _: &ConvertToUpperCamelCase,
 6466        cx: &mut ViewContext<Self>,
 6467    ) {
 6468        self.manipulate_text(cx, |text| {
 6469            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6470            // https://github.com/rutrum/convert-case/issues/16
 6471            text.split('\n')
 6472                .map(|line| line.to_case(Case::UpperCamel))
 6473                .join("\n")
 6474        })
 6475    }
 6476
 6477    pub fn convert_to_lower_camel_case(
 6478        &mut self,
 6479        _: &ConvertToLowerCamelCase,
 6480        cx: &mut ViewContext<Self>,
 6481    ) {
 6482        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6483    }
 6484
 6485    pub fn convert_to_opposite_case(
 6486        &mut self,
 6487        _: &ConvertToOppositeCase,
 6488        cx: &mut ViewContext<Self>,
 6489    ) {
 6490        self.manipulate_text(cx, |text| {
 6491            text.chars()
 6492                .fold(String::with_capacity(text.len()), |mut t, c| {
 6493                    if c.is_uppercase() {
 6494                        t.extend(c.to_lowercase());
 6495                    } else {
 6496                        t.extend(c.to_uppercase());
 6497                    }
 6498                    t
 6499                })
 6500        })
 6501    }
 6502
 6503    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6504    where
 6505        Fn: FnMut(&str) -> String,
 6506    {
 6507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6508        let buffer = self.buffer.read(cx).snapshot(cx);
 6509
 6510        let mut new_selections = Vec::new();
 6511        let mut edits = Vec::new();
 6512        let mut selection_adjustment = 0i32;
 6513
 6514        for selection in self.selections.all::<usize>(cx) {
 6515            let selection_is_empty = selection.is_empty();
 6516
 6517            let (start, end) = if selection_is_empty {
 6518                let word_range = movement::surrounding_word(
 6519                    &display_map,
 6520                    selection.start.to_display_point(&display_map),
 6521                );
 6522                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6523                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6524                (start, end)
 6525            } else {
 6526                (selection.start, selection.end)
 6527            };
 6528
 6529            let text = buffer.text_for_range(start..end).collect::<String>();
 6530            let old_length = text.len() as i32;
 6531            let text = callback(&text);
 6532
 6533            new_selections.push(Selection {
 6534                start: (start as i32 - selection_adjustment) as usize,
 6535                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6536                goal: SelectionGoal::None,
 6537                ..selection
 6538            });
 6539
 6540            selection_adjustment += old_length - text.len() as i32;
 6541
 6542            edits.push((start..end, text));
 6543        }
 6544
 6545        self.transact(cx, |this, cx| {
 6546            this.buffer.update(cx, |buffer, cx| {
 6547                buffer.edit(edits, None, cx);
 6548            });
 6549
 6550            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6551                s.select(new_selections);
 6552            });
 6553
 6554            this.request_autoscroll(Autoscroll::fit(), cx);
 6555        });
 6556    }
 6557
 6558    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6559        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6560        let buffer = &display_map.buffer_snapshot;
 6561        let selections = self.selections.all::<Point>(cx);
 6562
 6563        let mut edits = Vec::new();
 6564        let mut selections_iter = selections.iter().peekable();
 6565        while let Some(selection) = selections_iter.next() {
 6566            // Avoid duplicating the same lines twice.
 6567            let mut rows = selection.spanned_rows(false, &display_map);
 6568
 6569            while let Some(next_selection) = selections_iter.peek() {
 6570                let next_rows = next_selection.spanned_rows(false, &display_map);
 6571                if next_rows.start < rows.end {
 6572                    rows.end = next_rows.end;
 6573                    selections_iter.next().unwrap();
 6574                } else {
 6575                    break;
 6576                }
 6577            }
 6578
 6579            // Copy the text from the selected row region and splice it either at the start
 6580            // or end of the region.
 6581            let start = Point::new(rows.start.0, 0);
 6582            let end = Point::new(
 6583                rows.end.previous_row().0,
 6584                buffer.line_len(rows.end.previous_row()),
 6585            );
 6586            let text = buffer
 6587                .text_for_range(start..end)
 6588                .chain(Some("\n"))
 6589                .collect::<String>();
 6590            let insert_location = if upwards {
 6591                Point::new(rows.end.0, 0)
 6592            } else {
 6593                start
 6594            };
 6595            edits.push((insert_location..insert_location, text));
 6596        }
 6597
 6598        self.transact(cx, |this, cx| {
 6599            this.buffer.update(cx, |buffer, cx| {
 6600                buffer.edit(edits, None, cx);
 6601            });
 6602
 6603            this.request_autoscroll(Autoscroll::fit(), cx);
 6604        });
 6605    }
 6606
 6607    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6608        self.duplicate_line(true, cx);
 6609    }
 6610
 6611    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6612        self.duplicate_line(false, cx);
 6613    }
 6614
 6615    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6616        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6617        let buffer = self.buffer.read(cx).snapshot(cx);
 6618
 6619        let mut edits = Vec::new();
 6620        let mut unfold_ranges = Vec::new();
 6621        let mut refold_ranges = Vec::new();
 6622
 6623        let selections = self.selections.all::<Point>(cx);
 6624        let mut selections = selections.iter().peekable();
 6625        let mut contiguous_row_selections = Vec::new();
 6626        let mut new_selections = Vec::new();
 6627
 6628        while let Some(selection) = selections.next() {
 6629            // Find all the selections that span a contiguous row range
 6630            let (start_row, end_row) = consume_contiguous_rows(
 6631                &mut contiguous_row_selections,
 6632                selection,
 6633                &display_map,
 6634                &mut selections,
 6635            );
 6636
 6637            // Move the text spanned by the row range to be before the line preceding the row range
 6638            if start_row.0 > 0 {
 6639                let range_to_move = Point::new(
 6640                    start_row.previous_row().0,
 6641                    buffer.line_len(start_row.previous_row()),
 6642                )
 6643                    ..Point::new(
 6644                        end_row.previous_row().0,
 6645                        buffer.line_len(end_row.previous_row()),
 6646                    );
 6647                let insertion_point = display_map
 6648                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6649                    .0;
 6650
 6651                // Don't move lines across excerpts
 6652                if buffer
 6653                    .excerpt_boundaries_in_range((
 6654                        Bound::Excluded(insertion_point),
 6655                        Bound::Included(range_to_move.end),
 6656                    ))
 6657                    .next()
 6658                    .is_none()
 6659                {
 6660                    let text = buffer
 6661                        .text_for_range(range_to_move.clone())
 6662                        .flat_map(|s| s.chars())
 6663                        .skip(1)
 6664                        .chain(['\n'])
 6665                        .collect::<String>();
 6666
 6667                    edits.push((
 6668                        buffer.anchor_after(range_to_move.start)
 6669                            ..buffer.anchor_before(range_to_move.end),
 6670                        String::new(),
 6671                    ));
 6672                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6673                    edits.push((insertion_anchor..insertion_anchor, text));
 6674
 6675                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6676
 6677                    // Move selections up
 6678                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6679                        |mut selection| {
 6680                            selection.start.row -= row_delta;
 6681                            selection.end.row -= row_delta;
 6682                            selection
 6683                        },
 6684                    ));
 6685
 6686                    // Move folds up
 6687                    unfold_ranges.push(range_to_move.clone());
 6688                    for fold in display_map.folds_in_range(
 6689                        buffer.anchor_before(range_to_move.start)
 6690                            ..buffer.anchor_after(range_to_move.end),
 6691                    ) {
 6692                        let mut start = fold.range.start.to_point(&buffer);
 6693                        let mut end = fold.range.end.to_point(&buffer);
 6694                        start.row -= row_delta;
 6695                        end.row -= row_delta;
 6696                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6697                    }
 6698                }
 6699            }
 6700
 6701            // If we didn't move line(s), preserve the existing selections
 6702            new_selections.append(&mut contiguous_row_selections);
 6703        }
 6704
 6705        self.transact(cx, |this, cx| {
 6706            this.unfold_ranges(unfold_ranges, true, true, cx);
 6707            this.buffer.update(cx, |buffer, cx| {
 6708                for (range, text) in edits {
 6709                    buffer.edit([(range, text)], None, cx);
 6710                }
 6711            });
 6712            this.fold_ranges(refold_ranges, true, cx);
 6713            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6714                s.select(new_selections);
 6715            })
 6716        });
 6717    }
 6718
 6719    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6720        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6721        let buffer = self.buffer.read(cx).snapshot(cx);
 6722
 6723        let mut edits = Vec::new();
 6724        let mut unfold_ranges = Vec::new();
 6725        let mut refold_ranges = Vec::new();
 6726
 6727        let selections = self.selections.all::<Point>(cx);
 6728        let mut selections = selections.iter().peekable();
 6729        let mut contiguous_row_selections = Vec::new();
 6730        let mut new_selections = Vec::new();
 6731
 6732        while let Some(selection) = selections.next() {
 6733            // Find all the selections that span a contiguous row range
 6734            let (start_row, end_row) = consume_contiguous_rows(
 6735                &mut contiguous_row_selections,
 6736                selection,
 6737                &display_map,
 6738                &mut selections,
 6739            );
 6740
 6741            // Move the text spanned by the row range to be after the last line of the row range
 6742            if end_row.0 <= buffer.max_point().row {
 6743                let range_to_move =
 6744                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6745                let insertion_point = display_map
 6746                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6747                    .0;
 6748
 6749                // Don't move lines across excerpt boundaries
 6750                if buffer
 6751                    .excerpt_boundaries_in_range((
 6752                        Bound::Excluded(range_to_move.start),
 6753                        Bound::Included(insertion_point),
 6754                    ))
 6755                    .next()
 6756                    .is_none()
 6757                {
 6758                    let mut text = String::from("\n");
 6759                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6760                    text.pop(); // Drop trailing newline
 6761                    edits.push((
 6762                        buffer.anchor_after(range_to_move.start)
 6763                            ..buffer.anchor_before(range_to_move.end),
 6764                        String::new(),
 6765                    ));
 6766                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6767                    edits.push((insertion_anchor..insertion_anchor, text));
 6768
 6769                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6770
 6771                    // Move selections down
 6772                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6773                        |mut selection| {
 6774                            selection.start.row += row_delta;
 6775                            selection.end.row += row_delta;
 6776                            selection
 6777                        },
 6778                    ));
 6779
 6780                    // Move folds down
 6781                    unfold_ranges.push(range_to_move.clone());
 6782                    for fold in display_map.folds_in_range(
 6783                        buffer.anchor_before(range_to_move.start)
 6784                            ..buffer.anchor_after(range_to_move.end),
 6785                    ) {
 6786                        let mut start = fold.range.start.to_point(&buffer);
 6787                        let mut end = fold.range.end.to_point(&buffer);
 6788                        start.row += row_delta;
 6789                        end.row += row_delta;
 6790                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6791                    }
 6792                }
 6793            }
 6794
 6795            // If we didn't move line(s), preserve the existing selections
 6796            new_selections.append(&mut contiguous_row_selections);
 6797        }
 6798
 6799        self.transact(cx, |this, cx| {
 6800            this.unfold_ranges(unfold_ranges, true, true, cx);
 6801            this.buffer.update(cx, |buffer, cx| {
 6802                for (range, text) in edits {
 6803                    buffer.edit([(range, text)], None, cx);
 6804                }
 6805            });
 6806            this.fold_ranges(refold_ranges, true, cx);
 6807            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6808        });
 6809    }
 6810
 6811    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6812        let text_layout_details = &self.text_layout_details(cx);
 6813        self.transact(cx, |this, cx| {
 6814            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6815                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6816                let line_mode = s.line_mode;
 6817                s.move_with(|display_map, selection| {
 6818                    if !selection.is_empty() || line_mode {
 6819                        return;
 6820                    }
 6821
 6822                    let mut head = selection.head();
 6823                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6824                    if head.column() == display_map.line_len(head.row()) {
 6825                        transpose_offset = display_map
 6826                            .buffer_snapshot
 6827                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6828                    }
 6829
 6830                    if transpose_offset == 0 {
 6831                        return;
 6832                    }
 6833
 6834                    *head.column_mut() += 1;
 6835                    head = display_map.clip_point(head, Bias::Right);
 6836                    let goal = SelectionGoal::HorizontalPosition(
 6837                        display_map
 6838                            .x_for_display_point(head, text_layout_details)
 6839                            .into(),
 6840                    );
 6841                    selection.collapse_to(head, goal);
 6842
 6843                    let transpose_start = display_map
 6844                        .buffer_snapshot
 6845                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6846                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6847                        let transpose_end = display_map
 6848                            .buffer_snapshot
 6849                            .clip_offset(transpose_offset + 1, Bias::Right);
 6850                        if let Some(ch) =
 6851                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6852                        {
 6853                            edits.push((transpose_start..transpose_offset, String::new()));
 6854                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6855                        }
 6856                    }
 6857                });
 6858                edits
 6859            });
 6860            this.buffer
 6861                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6862            let selections = this.selections.all::<usize>(cx);
 6863            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6864                s.select(selections);
 6865            });
 6866        });
 6867    }
 6868
 6869    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6870        self.rewrap_impl(true, cx)
 6871    }
 6872
 6873    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6874        let buffer = self.buffer.read(cx).snapshot(cx);
 6875        let selections = self.selections.all::<Point>(cx);
 6876        let mut selections = selections.iter().peekable();
 6877
 6878        let mut edits = Vec::new();
 6879        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6880
 6881        while let Some(selection) = selections.next() {
 6882            let mut start_row = selection.start.row;
 6883            let mut end_row = selection.end.row;
 6884
 6885            // Skip selections that overlap with a range that has already been rewrapped.
 6886            let selection_range = start_row..end_row;
 6887            if rewrapped_row_ranges
 6888                .iter()
 6889                .any(|range| range.overlaps(&selection_range))
 6890            {
 6891                continue;
 6892            }
 6893
 6894            let mut should_rewrap = !only_text;
 6895
 6896            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6897                match language_scope.language_name().0.as_ref() {
 6898                    "Markdown" | "Plain Text" => {
 6899                        should_rewrap = true;
 6900                    }
 6901                    _ => {}
 6902                }
 6903            }
 6904
 6905            // Since not all lines in the selection may be at the same indent
 6906            // level, choose the indent size that is the most common between all
 6907            // of the lines.
 6908            //
 6909            // If there is a tie, we use the deepest indent.
 6910            let (indent_size, indent_end) = {
 6911                let mut indent_size_occurrences = HashMap::default();
 6912                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6913
 6914                for row in start_row..=end_row {
 6915                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6916                    rows_by_indent_size.entry(indent).or_default().push(row);
 6917                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6918                }
 6919
 6920                let indent_size = indent_size_occurrences
 6921                    .into_iter()
 6922                    .max_by_key(|(indent, count)| (*count, indent.len))
 6923                    .map(|(indent, _)| indent)
 6924                    .unwrap_or_default();
 6925                let row = rows_by_indent_size[&indent_size][0];
 6926                let indent_end = Point::new(row, indent_size.len);
 6927
 6928                (indent_size, indent_end)
 6929            };
 6930
 6931            let mut line_prefix = indent_size.chars().collect::<String>();
 6932
 6933            if let Some(comment_prefix) =
 6934                buffer
 6935                    .language_scope_at(selection.head())
 6936                    .and_then(|language| {
 6937                        language
 6938                            .line_comment_prefixes()
 6939                            .iter()
 6940                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6941                            .cloned()
 6942                    })
 6943            {
 6944                line_prefix.push_str(&comment_prefix);
 6945                should_rewrap = true;
 6946            }
 6947
 6948            if selection.is_empty() {
 6949                'expand_upwards: while start_row > 0 {
 6950                    let prev_row = start_row - 1;
 6951                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6952                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6953                    {
 6954                        start_row = prev_row;
 6955                    } else {
 6956                        break 'expand_upwards;
 6957                    }
 6958                }
 6959
 6960                'expand_downwards: while end_row < buffer.max_point().row {
 6961                    let next_row = end_row + 1;
 6962                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6963                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6964                    {
 6965                        end_row = next_row;
 6966                    } else {
 6967                        break 'expand_downwards;
 6968                    }
 6969                }
 6970            }
 6971
 6972            if !should_rewrap {
 6973                continue;
 6974            }
 6975
 6976            let start = Point::new(start_row, 0);
 6977            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6978            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6979            let Some(lines_without_prefixes) = selection_text
 6980                .lines()
 6981                .map(|line| {
 6982                    line.strip_prefix(&line_prefix)
 6983                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6984                        .ok_or_else(|| {
 6985                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6986                        })
 6987                })
 6988                .collect::<Result<Vec<_>, _>>()
 6989                .log_err()
 6990            else {
 6991                continue;
 6992            };
 6993
 6994            let unwrapped_text = lines_without_prefixes.join(" ");
 6995            let wrap_column = buffer
 6996                .settings_at(Point::new(start_row, 0), cx)
 6997                .preferred_line_length as usize;
 6998            let mut wrapped_text = String::new();
 6999            let mut current_line = line_prefix.clone();
 7000            for word in unwrapped_text.split_whitespace() {
 7001                if current_line.len() + word.len() >= wrap_column {
 7002                    wrapped_text.push_str(&current_line);
 7003                    wrapped_text.push('\n');
 7004                    current_line.truncate(line_prefix.len());
 7005                }
 7006
 7007                if current_line.len() > line_prefix.len() {
 7008                    current_line.push(' ');
 7009                }
 7010
 7011                current_line.push_str(word);
 7012            }
 7013
 7014            if !current_line.is_empty() {
 7015                wrapped_text.push_str(&current_line);
 7016            }
 7017
 7018            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7019            let mut offset = start.to_offset(&buffer);
 7020            let mut moved_since_edit = true;
 7021
 7022            for change in diff.iter_all_changes() {
 7023                let value = change.value();
 7024                match change.tag() {
 7025                    ChangeTag::Equal => {
 7026                        offset += value.len();
 7027                        moved_since_edit = true;
 7028                    }
 7029                    ChangeTag::Delete => {
 7030                        let start = buffer.anchor_after(offset);
 7031                        let end = buffer.anchor_before(offset + value.len());
 7032
 7033                        if moved_since_edit {
 7034                            edits.push((start..end, String::new()));
 7035                        } else {
 7036                            edits.last_mut().unwrap().0.end = end;
 7037                        }
 7038
 7039                        offset += value.len();
 7040                        moved_since_edit = false;
 7041                    }
 7042                    ChangeTag::Insert => {
 7043                        if moved_since_edit {
 7044                            let anchor = buffer.anchor_after(offset);
 7045                            edits.push((anchor..anchor, value.to_string()));
 7046                        } else {
 7047                            edits.last_mut().unwrap().1.push_str(value);
 7048                        }
 7049
 7050                        moved_since_edit = false;
 7051                    }
 7052                }
 7053            }
 7054
 7055            rewrapped_row_ranges.push(start_row..=end_row);
 7056        }
 7057
 7058        self.buffer
 7059            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7060    }
 7061
 7062    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7063        let mut text = String::new();
 7064        let buffer = self.buffer.read(cx).snapshot(cx);
 7065        let mut selections = self.selections.all::<Point>(cx);
 7066        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7067        {
 7068            let max_point = buffer.max_point();
 7069            let mut is_first = true;
 7070            for selection in &mut selections {
 7071                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7072                if is_entire_line {
 7073                    selection.start = Point::new(selection.start.row, 0);
 7074                    if !selection.is_empty() && selection.end.column == 0 {
 7075                        selection.end = cmp::min(max_point, selection.end);
 7076                    } else {
 7077                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7078                    }
 7079                    selection.goal = SelectionGoal::None;
 7080                }
 7081                if is_first {
 7082                    is_first = false;
 7083                } else {
 7084                    text += "\n";
 7085                }
 7086                let mut len = 0;
 7087                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7088                    text.push_str(chunk);
 7089                    len += chunk.len();
 7090                }
 7091                clipboard_selections.push(ClipboardSelection {
 7092                    len,
 7093                    is_entire_line,
 7094                    first_line_indent: buffer
 7095                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7096                        .len,
 7097                });
 7098            }
 7099        }
 7100
 7101        self.transact(cx, |this, cx| {
 7102            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7103                s.select(selections);
 7104            });
 7105            this.insert("", cx);
 7106            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7107                text,
 7108                clipboard_selections,
 7109            ));
 7110        });
 7111    }
 7112
 7113    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7114        let selections = self.selections.all::<Point>(cx);
 7115        let buffer = self.buffer.read(cx).read(cx);
 7116        let mut text = String::new();
 7117
 7118        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7119        {
 7120            let max_point = buffer.max_point();
 7121            let mut is_first = true;
 7122            for selection in selections.iter() {
 7123                let mut start = selection.start;
 7124                let mut end = selection.end;
 7125                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7126                if is_entire_line {
 7127                    start = Point::new(start.row, 0);
 7128                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7129                }
 7130                if is_first {
 7131                    is_first = false;
 7132                } else {
 7133                    text += "\n";
 7134                }
 7135                let mut len = 0;
 7136                for chunk in buffer.text_for_range(start..end) {
 7137                    text.push_str(chunk);
 7138                    len += chunk.len();
 7139                }
 7140                clipboard_selections.push(ClipboardSelection {
 7141                    len,
 7142                    is_entire_line,
 7143                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7144                });
 7145            }
 7146        }
 7147
 7148        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7149            text,
 7150            clipboard_selections,
 7151        ));
 7152    }
 7153
 7154    pub fn do_paste(
 7155        &mut self,
 7156        text: &String,
 7157        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7158        handle_entire_lines: bool,
 7159        cx: &mut ViewContext<Self>,
 7160    ) {
 7161        if self.read_only(cx) {
 7162            return;
 7163        }
 7164
 7165        let clipboard_text = Cow::Borrowed(text);
 7166
 7167        self.transact(cx, |this, cx| {
 7168            if let Some(mut clipboard_selections) = clipboard_selections {
 7169                let old_selections = this.selections.all::<usize>(cx);
 7170                let all_selections_were_entire_line =
 7171                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7172                let first_selection_indent_column =
 7173                    clipboard_selections.first().map(|s| s.first_line_indent);
 7174                if clipboard_selections.len() != old_selections.len() {
 7175                    clipboard_selections.drain(..);
 7176                }
 7177
 7178                this.buffer.update(cx, |buffer, cx| {
 7179                    let snapshot = buffer.read(cx);
 7180                    let mut start_offset = 0;
 7181                    let mut edits = Vec::new();
 7182                    let mut original_indent_columns = Vec::new();
 7183                    for (ix, selection) in old_selections.iter().enumerate() {
 7184                        let to_insert;
 7185                        let entire_line;
 7186                        let original_indent_column;
 7187                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7188                            let end_offset = start_offset + clipboard_selection.len;
 7189                            to_insert = &clipboard_text[start_offset..end_offset];
 7190                            entire_line = clipboard_selection.is_entire_line;
 7191                            start_offset = end_offset + 1;
 7192                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7193                        } else {
 7194                            to_insert = clipboard_text.as_str();
 7195                            entire_line = all_selections_were_entire_line;
 7196                            original_indent_column = first_selection_indent_column
 7197                        }
 7198
 7199                        // If the corresponding selection was empty when this slice of the
 7200                        // clipboard text was written, then the entire line containing the
 7201                        // selection was copied. If this selection is also currently empty,
 7202                        // then paste the line before the current line of the buffer.
 7203                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7204                            let column = selection.start.to_point(&snapshot).column as usize;
 7205                            let line_start = selection.start - column;
 7206                            line_start..line_start
 7207                        } else {
 7208                            selection.range()
 7209                        };
 7210
 7211                        edits.push((range, to_insert));
 7212                        original_indent_columns.extend(original_indent_column);
 7213                    }
 7214                    drop(snapshot);
 7215
 7216                    buffer.edit(
 7217                        edits,
 7218                        Some(AutoindentMode::Block {
 7219                            original_indent_columns,
 7220                        }),
 7221                        cx,
 7222                    );
 7223                });
 7224
 7225                let selections = this.selections.all::<usize>(cx);
 7226                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7227            } else {
 7228                this.insert(&clipboard_text, cx);
 7229            }
 7230        });
 7231    }
 7232
 7233    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7234        if let Some(item) = cx.read_from_clipboard() {
 7235            let entries = item.entries();
 7236
 7237            match entries.first() {
 7238                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7239                // of all the pasted entries.
 7240                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7241                    .do_paste(
 7242                        clipboard_string.text(),
 7243                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7244                        true,
 7245                        cx,
 7246                    ),
 7247                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7248            }
 7249        }
 7250    }
 7251
 7252    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7253        if self.read_only(cx) {
 7254            return;
 7255        }
 7256
 7257        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7258            if let Some((selections, _)) =
 7259                self.selection_history.transaction(transaction_id).cloned()
 7260            {
 7261                self.change_selections(None, cx, |s| {
 7262                    s.select_anchors(selections.to_vec());
 7263                });
 7264            }
 7265            self.request_autoscroll(Autoscroll::fit(), cx);
 7266            self.unmark_text(cx);
 7267            self.refresh_inline_completion(true, false, cx);
 7268            cx.emit(EditorEvent::Edited { transaction_id });
 7269            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7270        }
 7271    }
 7272
 7273    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7274        if self.read_only(cx) {
 7275            return;
 7276        }
 7277
 7278        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7279            if let Some((_, Some(selections))) =
 7280                self.selection_history.transaction(transaction_id).cloned()
 7281            {
 7282                self.change_selections(None, cx, |s| {
 7283                    s.select_anchors(selections.to_vec());
 7284                });
 7285            }
 7286            self.request_autoscroll(Autoscroll::fit(), cx);
 7287            self.unmark_text(cx);
 7288            self.refresh_inline_completion(true, false, cx);
 7289            cx.emit(EditorEvent::Edited { transaction_id });
 7290        }
 7291    }
 7292
 7293    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7294        self.buffer
 7295            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7296    }
 7297
 7298    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7299        self.buffer
 7300            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7301    }
 7302
 7303    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7304        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7305            let line_mode = s.line_mode;
 7306            s.move_with(|map, selection| {
 7307                let cursor = if selection.is_empty() && !line_mode {
 7308                    movement::left(map, selection.start)
 7309                } else {
 7310                    selection.start
 7311                };
 7312                selection.collapse_to(cursor, SelectionGoal::None);
 7313            });
 7314        })
 7315    }
 7316
 7317    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7318        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7319            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7320        })
 7321    }
 7322
 7323    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7324        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7325            let line_mode = s.line_mode;
 7326            s.move_with(|map, selection| {
 7327                let cursor = if selection.is_empty() && !line_mode {
 7328                    movement::right(map, selection.end)
 7329                } else {
 7330                    selection.end
 7331                };
 7332                selection.collapse_to(cursor, SelectionGoal::None)
 7333            });
 7334        })
 7335    }
 7336
 7337    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7339            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7340        })
 7341    }
 7342
 7343    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7344        if self.take_rename(true, cx).is_some() {
 7345            return;
 7346        }
 7347
 7348        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7349            cx.propagate();
 7350            return;
 7351        }
 7352
 7353        let text_layout_details = &self.text_layout_details(cx);
 7354        let selection_count = self.selections.count();
 7355        let first_selection = self.selections.first_anchor();
 7356
 7357        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7358            let line_mode = s.line_mode;
 7359            s.move_with(|map, selection| {
 7360                if !selection.is_empty() && !line_mode {
 7361                    selection.goal = SelectionGoal::None;
 7362                }
 7363                let (cursor, goal) = movement::up(
 7364                    map,
 7365                    selection.start,
 7366                    selection.goal,
 7367                    false,
 7368                    text_layout_details,
 7369                );
 7370                selection.collapse_to(cursor, goal);
 7371            });
 7372        });
 7373
 7374        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7375        {
 7376            cx.propagate();
 7377        }
 7378    }
 7379
 7380    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7381        if self.take_rename(true, cx).is_some() {
 7382            return;
 7383        }
 7384
 7385        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7386            cx.propagate();
 7387            return;
 7388        }
 7389
 7390        let text_layout_details = &self.text_layout_details(cx);
 7391
 7392        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7393            let line_mode = s.line_mode;
 7394            s.move_with(|map, selection| {
 7395                if !selection.is_empty() && !line_mode {
 7396                    selection.goal = SelectionGoal::None;
 7397                }
 7398                let (cursor, goal) = movement::up_by_rows(
 7399                    map,
 7400                    selection.start,
 7401                    action.lines,
 7402                    selection.goal,
 7403                    false,
 7404                    text_layout_details,
 7405                );
 7406                selection.collapse_to(cursor, goal);
 7407            });
 7408        })
 7409    }
 7410
 7411    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7412        if self.take_rename(true, cx).is_some() {
 7413            return;
 7414        }
 7415
 7416        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7417            cx.propagate();
 7418            return;
 7419        }
 7420
 7421        let text_layout_details = &self.text_layout_details(cx);
 7422
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            let line_mode = s.line_mode;
 7425            s.move_with(|map, selection| {
 7426                if !selection.is_empty() && !line_mode {
 7427                    selection.goal = SelectionGoal::None;
 7428                }
 7429                let (cursor, goal) = movement::down_by_rows(
 7430                    map,
 7431                    selection.start,
 7432                    action.lines,
 7433                    selection.goal,
 7434                    false,
 7435                    text_layout_details,
 7436                );
 7437                selection.collapse_to(cursor, goal);
 7438            });
 7439        })
 7440    }
 7441
 7442    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7443        let text_layout_details = &self.text_layout_details(cx);
 7444        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7445            s.move_heads_with(|map, head, goal| {
 7446                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7447            })
 7448        })
 7449    }
 7450
 7451    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7452        let text_layout_details = &self.text_layout_details(cx);
 7453        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7454            s.move_heads_with(|map, head, goal| {
 7455                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7456            })
 7457        })
 7458    }
 7459
 7460    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7461        let Some(row_count) = self.visible_row_count() else {
 7462            return;
 7463        };
 7464
 7465        let text_layout_details = &self.text_layout_details(cx);
 7466
 7467        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7468            s.move_heads_with(|map, head, goal| {
 7469                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7470            })
 7471        })
 7472    }
 7473
 7474    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7475        if self.take_rename(true, cx).is_some() {
 7476            return;
 7477        }
 7478
 7479        if self
 7480            .context_menu
 7481            .write()
 7482            .as_mut()
 7483            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7484            .unwrap_or(false)
 7485        {
 7486            return;
 7487        }
 7488
 7489        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7490            cx.propagate();
 7491            return;
 7492        }
 7493
 7494        let Some(row_count) = self.visible_row_count() else {
 7495            return;
 7496        };
 7497
 7498        let autoscroll = if action.center_cursor {
 7499            Autoscroll::center()
 7500        } else {
 7501            Autoscroll::fit()
 7502        };
 7503
 7504        let text_layout_details = &self.text_layout_details(cx);
 7505
 7506        self.change_selections(Some(autoscroll), cx, |s| {
 7507            let line_mode = s.line_mode;
 7508            s.move_with(|map, selection| {
 7509                if !selection.is_empty() && !line_mode {
 7510                    selection.goal = SelectionGoal::None;
 7511                }
 7512                let (cursor, goal) = movement::up_by_rows(
 7513                    map,
 7514                    selection.end,
 7515                    row_count,
 7516                    selection.goal,
 7517                    false,
 7518                    text_layout_details,
 7519                );
 7520                selection.collapse_to(cursor, goal);
 7521            });
 7522        });
 7523    }
 7524
 7525    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7526        let text_layout_details = &self.text_layout_details(cx);
 7527        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7528            s.move_heads_with(|map, head, goal| {
 7529                movement::up(map, head, goal, false, text_layout_details)
 7530            })
 7531        })
 7532    }
 7533
 7534    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7535        self.take_rename(true, cx);
 7536
 7537        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7538            cx.propagate();
 7539            return;
 7540        }
 7541
 7542        let text_layout_details = &self.text_layout_details(cx);
 7543        let selection_count = self.selections.count();
 7544        let first_selection = self.selections.first_anchor();
 7545
 7546        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7547            let line_mode = s.line_mode;
 7548            s.move_with(|map, selection| {
 7549                if !selection.is_empty() && !line_mode {
 7550                    selection.goal = SelectionGoal::None;
 7551                }
 7552                let (cursor, goal) = movement::down(
 7553                    map,
 7554                    selection.end,
 7555                    selection.goal,
 7556                    false,
 7557                    text_layout_details,
 7558                );
 7559                selection.collapse_to(cursor, goal);
 7560            });
 7561        });
 7562
 7563        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7564        {
 7565            cx.propagate();
 7566        }
 7567    }
 7568
 7569    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7570        let Some(row_count) = self.visible_row_count() else {
 7571            return;
 7572        };
 7573
 7574        let text_layout_details = &self.text_layout_details(cx);
 7575
 7576        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7577            s.move_heads_with(|map, head, goal| {
 7578                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7579            })
 7580        })
 7581    }
 7582
 7583    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7584        if self.take_rename(true, cx).is_some() {
 7585            return;
 7586        }
 7587
 7588        if self
 7589            .context_menu
 7590            .write()
 7591            .as_mut()
 7592            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7593            .unwrap_or(false)
 7594        {
 7595            return;
 7596        }
 7597
 7598        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7599            cx.propagate();
 7600            return;
 7601        }
 7602
 7603        let Some(row_count) = self.visible_row_count() else {
 7604            return;
 7605        };
 7606
 7607        let autoscroll = if action.center_cursor {
 7608            Autoscroll::center()
 7609        } else {
 7610            Autoscroll::fit()
 7611        };
 7612
 7613        let text_layout_details = &self.text_layout_details(cx);
 7614        self.change_selections(Some(autoscroll), cx, |s| {
 7615            let line_mode = s.line_mode;
 7616            s.move_with(|map, selection| {
 7617                if !selection.is_empty() && !line_mode {
 7618                    selection.goal = SelectionGoal::None;
 7619                }
 7620                let (cursor, goal) = movement::down_by_rows(
 7621                    map,
 7622                    selection.end,
 7623                    row_count,
 7624                    selection.goal,
 7625                    false,
 7626                    text_layout_details,
 7627                );
 7628                selection.collapse_to(cursor, goal);
 7629            });
 7630        });
 7631    }
 7632
 7633    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7634        let text_layout_details = &self.text_layout_details(cx);
 7635        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7636            s.move_heads_with(|map, head, goal| {
 7637                movement::down(map, head, goal, false, text_layout_details)
 7638            })
 7639        });
 7640    }
 7641
 7642    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7643        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7644            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7645        }
 7646    }
 7647
 7648    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7649        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7650            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7651        }
 7652    }
 7653
 7654    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7655        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7656            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7657        }
 7658    }
 7659
 7660    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7661        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7662            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7663        }
 7664    }
 7665
 7666    pub fn move_to_previous_word_start(
 7667        &mut self,
 7668        _: &MoveToPreviousWordStart,
 7669        cx: &mut ViewContext<Self>,
 7670    ) {
 7671        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7672            s.move_cursors_with(|map, head, _| {
 7673                (
 7674                    movement::previous_word_start(map, head),
 7675                    SelectionGoal::None,
 7676                )
 7677            });
 7678        })
 7679    }
 7680
 7681    pub fn move_to_previous_subword_start(
 7682        &mut self,
 7683        _: &MoveToPreviousSubwordStart,
 7684        cx: &mut ViewContext<Self>,
 7685    ) {
 7686        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7687            s.move_cursors_with(|map, head, _| {
 7688                (
 7689                    movement::previous_subword_start(map, head),
 7690                    SelectionGoal::None,
 7691                )
 7692            });
 7693        })
 7694    }
 7695
 7696    pub fn select_to_previous_word_start(
 7697        &mut self,
 7698        _: &SelectToPreviousWordStart,
 7699        cx: &mut ViewContext<Self>,
 7700    ) {
 7701        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7702            s.move_heads_with(|map, head, _| {
 7703                (
 7704                    movement::previous_word_start(map, head),
 7705                    SelectionGoal::None,
 7706                )
 7707            });
 7708        })
 7709    }
 7710
 7711    pub fn select_to_previous_subword_start(
 7712        &mut self,
 7713        _: &SelectToPreviousSubwordStart,
 7714        cx: &mut ViewContext<Self>,
 7715    ) {
 7716        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7717            s.move_heads_with(|map, head, _| {
 7718                (
 7719                    movement::previous_subword_start(map, head),
 7720                    SelectionGoal::None,
 7721                )
 7722            });
 7723        })
 7724    }
 7725
 7726    pub fn delete_to_previous_word_start(
 7727        &mut self,
 7728        action: &DeleteToPreviousWordStart,
 7729        cx: &mut ViewContext<Self>,
 7730    ) {
 7731        self.transact(cx, |this, cx| {
 7732            this.select_autoclose_pair(cx);
 7733            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7734                let line_mode = s.line_mode;
 7735                s.move_with(|map, selection| {
 7736                    if selection.is_empty() && !line_mode {
 7737                        let cursor = if action.ignore_newlines {
 7738                            movement::previous_word_start(map, selection.head())
 7739                        } else {
 7740                            movement::previous_word_start_or_newline(map, selection.head())
 7741                        };
 7742                        selection.set_head(cursor, SelectionGoal::None);
 7743                    }
 7744                });
 7745            });
 7746            this.insert("", cx);
 7747        });
 7748    }
 7749
 7750    pub fn delete_to_previous_subword_start(
 7751        &mut self,
 7752        _: &DeleteToPreviousSubwordStart,
 7753        cx: &mut ViewContext<Self>,
 7754    ) {
 7755        self.transact(cx, |this, cx| {
 7756            this.select_autoclose_pair(cx);
 7757            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7758                let line_mode = s.line_mode;
 7759                s.move_with(|map, selection| {
 7760                    if selection.is_empty() && !line_mode {
 7761                        let cursor = movement::previous_subword_start(map, selection.head());
 7762                        selection.set_head(cursor, SelectionGoal::None);
 7763                    }
 7764                });
 7765            });
 7766            this.insert("", cx);
 7767        });
 7768    }
 7769
 7770    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7771        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7772            s.move_cursors_with(|map, head, _| {
 7773                (movement::next_word_end(map, head), SelectionGoal::None)
 7774            });
 7775        })
 7776    }
 7777
 7778    pub fn move_to_next_subword_end(
 7779        &mut self,
 7780        _: &MoveToNextSubwordEnd,
 7781        cx: &mut ViewContext<Self>,
 7782    ) {
 7783        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7784            s.move_cursors_with(|map, head, _| {
 7785                (movement::next_subword_end(map, head), SelectionGoal::None)
 7786            });
 7787        })
 7788    }
 7789
 7790    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7792            s.move_heads_with(|map, head, _| {
 7793                (movement::next_word_end(map, head), SelectionGoal::None)
 7794            });
 7795        })
 7796    }
 7797
 7798    pub fn select_to_next_subword_end(
 7799        &mut self,
 7800        _: &SelectToNextSubwordEnd,
 7801        cx: &mut ViewContext<Self>,
 7802    ) {
 7803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7804            s.move_heads_with(|map, head, _| {
 7805                (movement::next_subword_end(map, head), SelectionGoal::None)
 7806            });
 7807        })
 7808    }
 7809
 7810    pub fn delete_to_next_word_end(
 7811        &mut self,
 7812        action: &DeleteToNextWordEnd,
 7813        cx: &mut ViewContext<Self>,
 7814    ) {
 7815        self.transact(cx, |this, cx| {
 7816            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7817                let line_mode = s.line_mode;
 7818                s.move_with(|map, selection| {
 7819                    if selection.is_empty() && !line_mode {
 7820                        let cursor = if action.ignore_newlines {
 7821                            movement::next_word_end(map, selection.head())
 7822                        } else {
 7823                            movement::next_word_end_or_newline(map, selection.head())
 7824                        };
 7825                        selection.set_head(cursor, SelectionGoal::None);
 7826                    }
 7827                });
 7828            });
 7829            this.insert("", cx);
 7830        });
 7831    }
 7832
 7833    pub fn delete_to_next_subword_end(
 7834        &mut self,
 7835        _: &DeleteToNextSubwordEnd,
 7836        cx: &mut ViewContext<Self>,
 7837    ) {
 7838        self.transact(cx, |this, cx| {
 7839            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7840                s.move_with(|map, selection| {
 7841                    if selection.is_empty() {
 7842                        let cursor = movement::next_subword_end(map, selection.head());
 7843                        selection.set_head(cursor, SelectionGoal::None);
 7844                    }
 7845                });
 7846            });
 7847            this.insert("", cx);
 7848        });
 7849    }
 7850
 7851    pub fn move_to_beginning_of_line(
 7852        &mut self,
 7853        action: &MoveToBeginningOfLine,
 7854        cx: &mut ViewContext<Self>,
 7855    ) {
 7856        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7857            s.move_cursors_with(|map, head, _| {
 7858                (
 7859                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7860                    SelectionGoal::None,
 7861                )
 7862            });
 7863        })
 7864    }
 7865
 7866    pub fn select_to_beginning_of_line(
 7867        &mut self,
 7868        action: &SelectToBeginningOfLine,
 7869        cx: &mut ViewContext<Self>,
 7870    ) {
 7871        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7872            s.move_heads_with(|map, head, _| {
 7873                (
 7874                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7875                    SelectionGoal::None,
 7876                )
 7877            });
 7878        });
 7879    }
 7880
 7881    pub fn delete_to_beginning_of_line(
 7882        &mut self,
 7883        _: &DeleteToBeginningOfLine,
 7884        cx: &mut ViewContext<Self>,
 7885    ) {
 7886        self.transact(cx, |this, cx| {
 7887            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7888                s.move_with(|_, selection| {
 7889                    selection.reversed = true;
 7890                });
 7891            });
 7892
 7893            this.select_to_beginning_of_line(
 7894                &SelectToBeginningOfLine {
 7895                    stop_at_soft_wraps: false,
 7896                },
 7897                cx,
 7898            );
 7899            this.backspace(&Backspace, cx);
 7900        });
 7901    }
 7902
 7903    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7904        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7905            s.move_cursors_with(|map, head, _| {
 7906                (
 7907                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7908                    SelectionGoal::None,
 7909                )
 7910            });
 7911        })
 7912    }
 7913
 7914    pub fn select_to_end_of_line(
 7915        &mut self,
 7916        action: &SelectToEndOfLine,
 7917        cx: &mut ViewContext<Self>,
 7918    ) {
 7919        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7920            s.move_heads_with(|map, head, _| {
 7921                (
 7922                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7923                    SelectionGoal::None,
 7924                )
 7925            });
 7926        })
 7927    }
 7928
 7929    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7930        self.transact(cx, |this, cx| {
 7931            this.select_to_end_of_line(
 7932                &SelectToEndOfLine {
 7933                    stop_at_soft_wraps: false,
 7934                },
 7935                cx,
 7936            );
 7937            this.delete(&Delete, cx);
 7938        });
 7939    }
 7940
 7941    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7942        self.transact(cx, |this, cx| {
 7943            this.select_to_end_of_line(
 7944                &SelectToEndOfLine {
 7945                    stop_at_soft_wraps: false,
 7946                },
 7947                cx,
 7948            );
 7949            this.cut(&Cut, cx);
 7950        });
 7951    }
 7952
 7953    pub fn move_to_start_of_paragraph(
 7954        &mut self,
 7955        _: &MoveToStartOfParagraph,
 7956        cx: &mut ViewContext<Self>,
 7957    ) {
 7958        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7959            cx.propagate();
 7960            return;
 7961        }
 7962
 7963        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7964            s.move_with(|map, selection| {
 7965                selection.collapse_to(
 7966                    movement::start_of_paragraph(map, selection.head(), 1),
 7967                    SelectionGoal::None,
 7968                )
 7969            });
 7970        })
 7971    }
 7972
 7973    pub fn move_to_end_of_paragraph(
 7974        &mut self,
 7975        _: &MoveToEndOfParagraph,
 7976        cx: &mut ViewContext<Self>,
 7977    ) {
 7978        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7979            cx.propagate();
 7980            return;
 7981        }
 7982
 7983        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7984            s.move_with(|map, selection| {
 7985                selection.collapse_to(
 7986                    movement::end_of_paragraph(map, selection.head(), 1),
 7987                    SelectionGoal::None,
 7988                )
 7989            });
 7990        })
 7991    }
 7992
 7993    pub fn select_to_start_of_paragraph(
 7994        &mut self,
 7995        _: &SelectToStartOfParagraph,
 7996        cx: &mut ViewContext<Self>,
 7997    ) {
 7998        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7999            cx.propagate();
 8000            return;
 8001        }
 8002
 8003        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8004            s.move_heads_with(|map, head, _| {
 8005                (
 8006                    movement::start_of_paragraph(map, head, 1),
 8007                    SelectionGoal::None,
 8008                )
 8009            });
 8010        })
 8011    }
 8012
 8013    pub fn select_to_end_of_paragraph(
 8014        &mut self,
 8015        _: &SelectToEndOfParagraph,
 8016        cx: &mut ViewContext<Self>,
 8017    ) {
 8018        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8019            cx.propagate();
 8020            return;
 8021        }
 8022
 8023        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8024            s.move_heads_with(|map, head, _| {
 8025                (
 8026                    movement::end_of_paragraph(map, head, 1),
 8027                    SelectionGoal::None,
 8028                )
 8029            });
 8030        })
 8031    }
 8032
 8033    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8034        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8035            cx.propagate();
 8036            return;
 8037        }
 8038
 8039        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8040            s.select_ranges(vec![0..0]);
 8041        });
 8042    }
 8043
 8044    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8045        let mut selection = self.selections.last::<Point>(cx);
 8046        selection.set_head(Point::zero(), SelectionGoal::None);
 8047
 8048        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8049            s.select(vec![selection]);
 8050        });
 8051    }
 8052
 8053    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8054        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8055            cx.propagate();
 8056            return;
 8057        }
 8058
 8059        let cursor = self.buffer.read(cx).read(cx).len();
 8060        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8061            s.select_ranges(vec![cursor..cursor])
 8062        });
 8063    }
 8064
 8065    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8066        self.nav_history = nav_history;
 8067    }
 8068
 8069    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8070        self.nav_history.as_ref()
 8071    }
 8072
 8073    fn push_to_nav_history(
 8074        &mut self,
 8075        cursor_anchor: Anchor,
 8076        new_position: Option<Point>,
 8077        cx: &mut ViewContext<Self>,
 8078    ) {
 8079        if let Some(nav_history) = self.nav_history.as_mut() {
 8080            let buffer = self.buffer.read(cx).read(cx);
 8081            let cursor_position = cursor_anchor.to_point(&buffer);
 8082            let scroll_state = self.scroll_manager.anchor();
 8083            let scroll_top_row = scroll_state.top_row(&buffer);
 8084            drop(buffer);
 8085
 8086            if let Some(new_position) = new_position {
 8087                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8088                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8089                    return;
 8090                }
 8091            }
 8092
 8093            nav_history.push(
 8094                Some(NavigationData {
 8095                    cursor_anchor,
 8096                    cursor_position,
 8097                    scroll_anchor: scroll_state,
 8098                    scroll_top_row,
 8099                }),
 8100                cx,
 8101            );
 8102        }
 8103    }
 8104
 8105    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8106        let buffer = self.buffer.read(cx).snapshot(cx);
 8107        let mut selection = self.selections.first::<usize>(cx);
 8108        selection.set_head(buffer.len(), SelectionGoal::None);
 8109        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8110            s.select(vec![selection]);
 8111        });
 8112    }
 8113
 8114    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8115        let end = self.buffer.read(cx).read(cx).len();
 8116        self.change_selections(None, cx, |s| {
 8117            s.select_ranges(vec![0..end]);
 8118        });
 8119    }
 8120
 8121    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8122        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8123        let mut selections = self.selections.all::<Point>(cx);
 8124        let max_point = display_map.buffer_snapshot.max_point();
 8125        for selection in &mut selections {
 8126            let rows = selection.spanned_rows(true, &display_map);
 8127            selection.start = Point::new(rows.start.0, 0);
 8128            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8129            selection.reversed = false;
 8130        }
 8131        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8132            s.select(selections);
 8133        });
 8134    }
 8135
 8136    pub fn split_selection_into_lines(
 8137        &mut self,
 8138        _: &SplitSelectionIntoLines,
 8139        cx: &mut ViewContext<Self>,
 8140    ) {
 8141        let mut to_unfold = Vec::new();
 8142        let mut new_selection_ranges = Vec::new();
 8143        {
 8144            let selections = self.selections.all::<Point>(cx);
 8145            let buffer = self.buffer.read(cx).read(cx);
 8146            for selection in selections {
 8147                for row in selection.start.row..selection.end.row {
 8148                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8149                    new_selection_ranges.push(cursor..cursor);
 8150                }
 8151                new_selection_ranges.push(selection.end..selection.end);
 8152                to_unfold.push(selection.start..selection.end);
 8153            }
 8154        }
 8155        self.unfold_ranges(to_unfold, true, true, cx);
 8156        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8157            s.select_ranges(new_selection_ranges);
 8158        });
 8159    }
 8160
 8161    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8162        self.add_selection(true, cx);
 8163    }
 8164
 8165    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8166        self.add_selection(false, cx);
 8167    }
 8168
 8169    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8170        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8171        let mut selections = self.selections.all::<Point>(cx);
 8172        let text_layout_details = self.text_layout_details(cx);
 8173        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8174            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8175            let range = oldest_selection.display_range(&display_map).sorted();
 8176
 8177            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8178            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8179            let positions = start_x.min(end_x)..start_x.max(end_x);
 8180
 8181            selections.clear();
 8182            let mut stack = Vec::new();
 8183            for row in range.start.row().0..=range.end.row().0 {
 8184                if let Some(selection) = self.selections.build_columnar_selection(
 8185                    &display_map,
 8186                    DisplayRow(row),
 8187                    &positions,
 8188                    oldest_selection.reversed,
 8189                    &text_layout_details,
 8190                ) {
 8191                    stack.push(selection.id);
 8192                    selections.push(selection);
 8193                }
 8194            }
 8195
 8196            if above {
 8197                stack.reverse();
 8198            }
 8199
 8200            AddSelectionsState { above, stack }
 8201        });
 8202
 8203        let last_added_selection = *state.stack.last().unwrap();
 8204        let mut new_selections = Vec::new();
 8205        if above == state.above {
 8206            let end_row = if above {
 8207                DisplayRow(0)
 8208            } else {
 8209                display_map.max_point().row()
 8210            };
 8211
 8212            'outer: for selection in selections {
 8213                if selection.id == last_added_selection {
 8214                    let range = selection.display_range(&display_map).sorted();
 8215                    debug_assert_eq!(range.start.row(), range.end.row());
 8216                    let mut row = range.start.row();
 8217                    let positions =
 8218                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8219                            px(start)..px(end)
 8220                        } else {
 8221                            let start_x =
 8222                                display_map.x_for_display_point(range.start, &text_layout_details);
 8223                            let end_x =
 8224                                display_map.x_for_display_point(range.end, &text_layout_details);
 8225                            start_x.min(end_x)..start_x.max(end_x)
 8226                        };
 8227
 8228                    while row != end_row {
 8229                        if above {
 8230                            row.0 -= 1;
 8231                        } else {
 8232                            row.0 += 1;
 8233                        }
 8234
 8235                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8236                            &display_map,
 8237                            row,
 8238                            &positions,
 8239                            selection.reversed,
 8240                            &text_layout_details,
 8241                        ) {
 8242                            state.stack.push(new_selection.id);
 8243                            if above {
 8244                                new_selections.push(new_selection);
 8245                                new_selections.push(selection);
 8246                            } else {
 8247                                new_selections.push(selection);
 8248                                new_selections.push(new_selection);
 8249                            }
 8250
 8251                            continue 'outer;
 8252                        }
 8253                    }
 8254                }
 8255
 8256                new_selections.push(selection);
 8257            }
 8258        } else {
 8259            new_selections = selections;
 8260            new_selections.retain(|s| s.id != last_added_selection);
 8261            state.stack.pop();
 8262        }
 8263
 8264        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8265            s.select(new_selections);
 8266        });
 8267        if state.stack.len() > 1 {
 8268            self.add_selections_state = Some(state);
 8269        }
 8270    }
 8271
 8272    pub fn select_next_match_internal(
 8273        &mut self,
 8274        display_map: &DisplaySnapshot,
 8275        replace_newest: bool,
 8276        autoscroll: Option<Autoscroll>,
 8277        cx: &mut ViewContext<Self>,
 8278    ) -> Result<()> {
 8279        fn select_next_match_ranges(
 8280            this: &mut Editor,
 8281            range: Range<usize>,
 8282            replace_newest: bool,
 8283            auto_scroll: Option<Autoscroll>,
 8284            cx: &mut ViewContext<Editor>,
 8285        ) {
 8286            this.unfold_ranges([range.clone()], false, true, cx);
 8287            this.change_selections(auto_scroll, cx, |s| {
 8288                if replace_newest {
 8289                    s.delete(s.newest_anchor().id);
 8290                }
 8291                s.insert_range(range.clone());
 8292            });
 8293        }
 8294
 8295        let buffer = &display_map.buffer_snapshot;
 8296        let mut selections = self.selections.all::<usize>(cx);
 8297        if let Some(mut select_next_state) = self.select_next_state.take() {
 8298            let query = &select_next_state.query;
 8299            if !select_next_state.done {
 8300                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8301                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8302                let mut next_selected_range = None;
 8303
 8304                let bytes_after_last_selection =
 8305                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8306                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8307                let query_matches = query
 8308                    .stream_find_iter(bytes_after_last_selection)
 8309                    .map(|result| (last_selection.end, result))
 8310                    .chain(
 8311                        query
 8312                            .stream_find_iter(bytes_before_first_selection)
 8313                            .map(|result| (0, result)),
 8314                    );
 8315
 8316                for (start_offset, query_match) in query_matches {
 8317                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8318                    let offset_range =
 8319                        start_offset + query_match.start()..start_offset + query_match.end();
 8320                    let display_range = offset_range.start.to_display_point(display_map)
 8321                        ..offset_range.end.to_display_point(display_map);
 8322
 8323                    if !select_next_state.wordwise
 8324                        || (!movement::is_inside_word(display_map, display_range.start)
 8325                            && !movement::is_inside_word(display_map, display_range.end))
 8326                    {
 8327                        // TODO: This is n^2, because we might check all the selections
 8328                        if !selections
 8329                            .iter()
 8330                            .any(|selection| selection.range().overlaps(&offset_range))
 8331                        {
 8332                            next_selected_range = Some(offset_range);
 8333                            break;
 8334                        }
 8335                    }
 8336                }
 8337
 8338                if let Some(next_selected_range) = next_selected_range {
 8339                    select_next_match_ranges(
 8340                        self,
 8341                        next_selected_range,
 8342                        replace_newest,
 8343                        autoscroll,
 8344                        cx,
 8345                    );
 8346                } else {
 8347                    select_next_state.done = true;
 8348                }
 8349            }
 8350
 8351            self.select_next_state = Some(select_next_state);
 8352        } else {
 8353            let mut only_carets = true;
 8354            let mut same_text_selected = true;
 8355            let mut selected_text = None;
 8356
 8357            let mut selections_iter = selections.iter().peekable();
 8358            while let Some(selection) = selections_iter.next() {
 8359                if selection.start != selection.end {
 8360                    only_carets = false;
 8361                }
 8362
 8363                if same_text_selected {
 8364                    if selected_text.is_none() {
 8365                        selected_text =
 8366                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8367                    }
 8368
 8369                    if let Some(next_selection) = selections_iter.peek() {
 8370                        if next_selection.range().len() == selection.range().len() {
 8371                            let next_selected_text = buffer
 8372                                .text_for_range(next_selection.range())
 8373                                .collect::<String>();
 8374                            if Some(next_selected_text) != selected_text {
 8375                                same_text_selected = false;
 8376                                selected_text = None;
 8377                            }
 8378                        } else {
 8379                            same_text_selected = false;
 8380                            selected_text = None;
 8381                        }
 8382                    }
 8383                }
 8384            }
 8385
 8386            if only_carets {
 8387                for selection in &mut selections {
 8388                    let word_range = movement::surrounding_word(
 8389                        display_map,
 8390                        selection.start.to_display_point(display_map),
 8391                    );
 8392                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8393                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8394                    selection.goal = SelectionGoal::None;
 8395                    selection.reversed = false;
 8396                    select_next_match_ranges(
 8397                        self,
 8398                        selection.start..selection.end,
 8399                        replace_newest,
 8400                        autoscroll,
 8401                        cx,
 8402                    );
 8403                }
 8404
 8405                if selections.len() == 1 {
 8406                    let selection = selections
 8407                        .last()
 8408                        .expect("ensured that there's only one selection");
 8409                    let query = buffer
 8410                        .text_for_range(selection.start..selection.end)
 8411                        .collect::<String>();
 8412                    let is_empty = query.is_empty();
 8413                    let select_state = SelectNextState {
 8414                        query: AhoCorasick::new(&[query])?,
 8415                        wordwise: true,
 8416                        done: is_empty,
 8417                    };
 8418                    self.select_next_state = Some(select_state);
 8419                } else {
 8420                    self.select_next_state = None;
 8421                }
 8422            } else if let Some(selected_text) = selected_text {
 8423                self.select_next_state = Some(SelectNextState {
 8424                    query: AhoCorasick::new(&[selected_text])?,
 8425                    wordwise: false,
 8426                    done: false,
 8427                });
 8428                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8429            }
 8430        }
 8431        Ok(())
 8432    }
 8433
 8434    pub fn select_all_matches(
 8435        &mut self,
 8436        _action: &SelectAllMatches,
 8437        cx: &mut ViewContext<Self>,
 8438    ) -> Result<()> {
 8439        self.push_to_selection_history();
 8440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8441
 8442        self.select_next_match_internal(&display_map, false, None, cx)?;
 8443        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8444            return Ok(());
 8445        };
 8446        if select_next_state.done {
 8447            return Ok(());
 8448        }
 8449
 8450        let mut new_selections = self.selections.all::<usize>(cx);
 8451
 8452        let buffer = &display_map.buffer_snapshot;
 8453        let query_matches = select_next_state
 8454            .query
 8455            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8456
 8457        for query_match in query_matches {
 8458            let query_match = query_match.unwrap(); // can only fail due to I/O
 8459            let offset_range = query_match.start()..query_match.end();
 8460            let display_range = offset_range.start.to_display_point(&display_map)
 8461                ..offset_range.end.to_display_point(&display_map);
 8462
 8463            if !select_next_state.wordwise
 8464                || (!movement::is_inside_word(&display_map, display_range.start)
 8465                    && !movement::is_inside_word(&display_map, display_range.end))
 8466            {
 8467                self.selections.change_with(cx, |selections| {
 8468                    new_selections.push(Selection {
 8469                        id: selections.new_selection_id(),
 8470                        start: offset_range.start,
 8471                        end: offset_range.end,
 8472                        reversed: false,
 8473                        goal: SelectionGoal::None,
 8474                    });
 8475                });
 8476            }
 8477        }
 8478
 8479        new_selections.sort_by_key(|selection| selection.start);
 8480        let mut ix = 0;
 8481        while ix + 1 < new_selections.len() {
 8482            let current_selection = &new_selections[ix];
 8483            let next_selection = &new_selections[ix + 1];
 8484            if current_selection.range().overlaps(&next_selection.range()) {
 8485                if current_selection.id < next_selection.id {
 8486                    new_selections.remove(ix + 1);
 8487                } else {
 8488                    new_selections.remove(ix);
 8489                }
 8490            } else {
 8491                ix += 1;
 8492            }
 8493        }
 8494
 8495        select_next_state.done = true;
 8496        self.unfold_ranges(
 8497            new_selections.iter().map(|selection| selection.range()),
 8498            false,
 8499            false,
 8500            cx,
 8501        );
 8502        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8503            selections.select(new_selections)
 8504        });
 8505
 8506        Ok(())
 8507    }
 8508
 8509    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8510        self.push_to_selection_history();
 8511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8512        self.select_next_match_internal(
 8513            &display_map,
 8514            action.replace_newest,
 8515            Some(Autoscroll::newest()),
 8516            cx,
 8517        )?;
 8518        Ok(())
 8519    }
 8520
 8521    pub fn select_previous(
 8522        &mut self,
 8523        action: &SelectPrevious,
 8524        cx: &mut ViewContext<Self>,
 8525    ) -> Result<()> {
 8526        self.push_to_selection_history();
 8527        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8528        let buffer = &display_map.buffer_snapshot;
 8529        let mut selections = self.selections.all::<usize>(cx);
 8530        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8531            let query = &select_prev_state.query;
 8532            if !select_prev_state.done {
 8533                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8534                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8535                let mut next_selected_range = None;
 8536                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8537                let bytes_before_last_selection =
 8538                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8539                let bytes_after_first_selection =
 8540                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8541                let query_matches = query
 8542                    .stream_find_iter(bytes_before_last_selection)
 8543                    .map(|result| (last_selection.start, result))
 8544                    .chain(
 8545                        query
 8546                            .stream_find_iter(bytes_after_first_selection)
 8547                            .map(|result| (buffer.len(), result)),
 8548                    );
 8549                for (end_offset, query_match) in query_matches {
 8550                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8551                    let offset_range =
 8552                        end_offset - query_match.end()..end_offset - query_match.start();
 8553                    let display_range = offset_range.start.to_display_point(&display_map)
 8554                        ..offset_range.end.to_display_point(&display_map);
 8555
 8556                    if !select_prev_state.wordwise
 8557                        || (!movement::is_inside_word(&display_map, display_range.start)
 8558                            && !movement::is_inside_word(&display_map, display_range.end))
 8559                    {
 8560                        next_selected_range = Some(offset_range);
 8561                        break;
 8562                    }
 8563                }
 8564
 8565                if let Some(next_selected_range) = next_selected_range {
 8566                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8567                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8568                        if action.replace_newest {
 8569                            s.delete(s.newest_anchor().id);
 8570                        }
 8571                        s.insert_range(next_selected_range);
 8572                    });
 8573                } else {
 8574                    select_prev_state.done = true;
 8575                }
 8576            }
 8577
 8578            self.select_prev_state = Some(select_prev_state);
 8579        } else {
 8580            let mut only_carets = true;
 8581            let mut same_text_selected = true;
 8582            let mut selected_text = None;
 8583
 8584            let mut selections_iter = selections.iter().peekable();
 8585            while let Some(selection) = selections_iter.next() {
 8586                if selection.start != selection.end {
 8587                    only_carets = false;
 8588                }
 8589
 8590                if same_text_selected {
 8591                    if selected_text.is_none() {
 8592                        selected_text =
 8593                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8594                    }
 8595
 8596                    if let Some(next_selection) = selections_iter.peek() {
 8597                        if next_selection.range().len() == selection.range().len() {
 8598                            let next_selected_text = buffer
 8599                                .text_for_range(next_selection.range())
 8600                                .collect::<String>();
 8601                            if Some(next_selected_text) != selected_text {
 8602                                same_text_selected = false;
 8603                                selected_text = None;
 8604                            }
 8605                        } else {
 8606                            same_text_selected = false;
 8607                            selected_text = None;
 8608                        }
 8609                    }
 8610                }
 8611            }
 8612
 8613            if only_carets {
 8614                for selection in &mut selections {
 8615                    let word_range = movement::surrounding_word(
 8616                        &display_map,
 8617                        selection.start.to_display_point(&display_map),
 8618                    );
 8619                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8620                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8621                    selection.goal = SelectionGoal::None;
 8622                    selection.reversed = false;
 8623                }
 8624                if selections.len() == 1 {
 8625                    let selection = selections
 8626                        .last()
 8627                        .expect("ensured that there's only one selection");
 8628                    let query = buffer
 8629                        .text_for_range(selection.start..selection.end)
 8630                        .collect::<String>();
 8631                    let is_empty = query.is_empty();
 8632                    let select_state = SelectNextState {
 8633                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8634                        wordwise: true,
 8635                        done: is_empty,
 8636                    };
 8637                    self.select_prev_state = Some(select_state);
 8638                } else {
 8639                    self.select_prev_state = None;
 8640                }
 8641
 8642                self.unfold_ranges(
 8643                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8644                    false,
 8645                    true,
 8646                    cx,
 8647                );
 8648                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8649                    s.select(selections);
 8650                });
 8651            } else if let Some(selected_text) = selected_text {
 8652                self.select_prev_state = Some(SelectNextState {
 8653                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8654                    wordwise: false,
 8655                    done: false,
 8656                });
 8657                self.select_previous(action, cx)?;
 8658            }
 8659        }
 8660        Ok(())
 8661    }
 8662
 8663    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8664        let text_layout_details = &self.text_layout_details(cx);
 8665        self.transact(cx, |this, cx| {
 8666            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8667            let mut edits = Vec::new();
 8668            let mut selection_edit_ranges = Vec::new();
 8669            let mut last_toggled_row = None;
 8670            let snapshot = this.buffer.read(cx).read(cx);
 8671            let empty_str: Arc<str> = Arc::default();
 8672            let mut suffixes_inserted = Vec::new();
 8673
 8674            fn comment_prefix_range(
 8675                snapshot: &MultiBufferSnapshot,
 8676                row: MultiBufferRow,
 8677                comment_prefix: &str,
 8678                comment_prefix_whitespace: &str,
 8679            ) -> Range<Point> {
 8680                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8681
 8682                let mut line_bytes = snapshot
 8683                    .bytes_in_range(start..snapshot.max_point())
 8684                    .flatten()
 8685                    .copied();
 8686
 8687                // If this line currently begins with the line comment prefix, then record
 8688                // the range containing the prefix.
 8689                if line_bytes
 8690                    .by_ref()
 8691                    .take(comment_prefix.len())
 8692                    .eq(comment_prefix.bytes())
 8693                {
 8694                    // Include any whitespace that matches the comment prefix.
 8695                    let matching_whitespace_len = line_bytes
 8696                        .zip(comment_prefix_whitespace.bytes())
 8697                        .take_while(|(a, b)| a == b)
 8698                        .count() as u32;
 8699                    let end = Point::new(
 8700                        start.row,
 8701                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8702                    );
 8703                    start..end
 8704                } else {
 8705                    start..start
 8706                }
 8707            }
 8708
 8709            fn comment_suffix_range(
 8710                snapshot: &MultiBufferSnapshot,
 8711                row: MultiBufferRow,
 8712                comment_suffix: &str,
 8713                comment_suffix_has_leading_space: bool,
 8714            ) -> Range<Point> {
 8715                let end = Point::new(row.0, snapshot.line_len(row));
 8716                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8717
 8718                let mut line_end_bytes = snapshot
 8719                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8720                    .flatten()
 8721                    .copied();
 8722
 8723                let leading_space_len = if suffix_start_column > 0
 8724                    && line_end_bytes.next() == Some(b' ')
 8725                    && comment_suffix_has_leading_space
 8726                {
 8727                    1
 8728                } else {
 8729                    0
 8730                };
 8731
 8732                // If this line currently begins with the line comment prefix, then record
 8733                // the range containing the prefix.
 8734                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8735                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8736                    start..end
 8737                } else {
 8738                    end..end
 8739                }
 8740            }
 8741
 8742            // TODO: Handle selections that cross excerpts
 8743            for selection in &mut selections {
 8744                let start_column = snapshot
 8745                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8746                    .len;
 8747                let language = if let Some(language) =
 8748                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8749                {
 8750                    language
 8751                } else {
 8752                    continue;
 8753                };
 8754
 8755                selection_edit_ranges.clear();
 8756
 8757                // If multiple selections contain a given row, avoid processing that
 8758                // row more than once.
 8759                let mut start_row = MultiBufferRow(selection.start.row);
 8760                if last_toggled_row == Some(start_row) {
 8761                    start_row = start_row.next_row();
 8762                }
 8763                let end_row =
 8764                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8765                        MultiBufferRow(selection.end.row - 1)
 8766                    } else {
 8767                        MultiBufferRow(selection.end.row)
 8768                    };
 8769                last_toggled_row = Some(end_row);
 8770
 8771                if start_row > end_row {
 8772                    continue;
 8773                }
 8774
 8775                // If the language has line comments, toggle those.
 8776                let full_comment_prefixes = language.line_comment_prefixes();
 8777                if !full_comment_prefixes.is_empty() {
 8778                    let first_prefix = full_comment_prefixes
 8779                        .first()
 8780                        .expect("prefixes is non-empty");
 8781                    let prefix_trimmed_lengths = full_comment_prefixes
 8782                        .iter()
 8783                        .map(|p| p.trim_end_matches(' ').len())
 8784                        .collect::<SmallVec<[usize; 4]>>();
 8785
 8786                    let mut all_selection_lines_are_comments = true;
 8787
 8788                    for row in start_row.0..=end_row.0 {
 8789                        let row = MultiBufferRow(row);
 8790                        if start_row < end_row && snapshot.is_line_blank(row) {
 8791                            continue;
 8792                        }
 8793
 8794                        let prefix_range = full_comment_prefixes
 8795                            .iter()
 8796                            .zip(prefix_trimmed_lengths.iter().copied())
 8797                            .map(|(prefix, trimmed_prefix_len)| {
 8798                                comment_prefix_range(
 8799                                    snapshot.deref(),
 8800                                    row,
 8801                                    &prefix[..trimmed_prefix_len],
 8802                                    &prefix[trimmed_prefix_len..],
 8803                                )
 8804                            })
 8805                            .max_by_key(|range| range.end.column - range.start.column)
 8806                            .expect("prefixes is non-empty");
 8807
 8808                        if prefix_range.is_empty() {
 8809                            all_selection_lines_are_comments = false;
 8810                        }
 8811
 8812                        selection_edit_ranges.push(prefix_range);
 8813                    }
 8814
 8815                    if all_selection_lines_are_comments {
 8816                        edits.extend(
 8817                            selection_edit_ranges
 8818                                .iter()
 8819                                .cloned()
 8820                                .map(|range| (range, empty_str.clone())),
 8821                        );
 8822                    } else {
 8823                        let min_column = selection_edit_ranges
 8824                            .iter()
 8825                            .map(|range| range.start.column)
 8826                            .min()
 8827                            .unwrap_or(0);
 8828                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8829                            let position = Point::new(range.start.row, min_column);
 8830                            (position..position, first_prefix.clone())
 8831                        }));
 8832                    }
 8833                } else if let Some((full_comment_prefix, comment_suffix)) =
 8834                    language.block_comment_delimiters()
 8835                {
 8836                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8837                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8838                    let prefix_range = comment_prefix_range(
 8839                        snapshot.deref(),
 8840                        start_row,
 8841                        comment_prefix,
 8842                        comment_prefix_whitespace,
 8843                    );
 8844                    let suffix_range = comment_suffix_range(
 8845                        snapshot.deref(),
 8846                        end_row,
 8847                        comment_suffix.trim_start_matches(' '),
 8848                        comment_suffix.starts_with(' '),
 8849                    );
 8850
 8851                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8852                        edits.push((
 8853                            prefix_range.start..prefix_range.start,
 8854                            full_comment_prefix.clone(),
 8855                        ));
 8856                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8857                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8858                    } else {
 8859                        edits.push((prefix_range, empty_str.clone()));
 8860                        edits.push((suffix_range, empty_str.clone()));
 8861                    }
 8862                } else {
 8863                    continue;
 8864                }
 8865            }
 8866
 8867            drop(snapshot);
 8868            this.buffer.update(cx, |buffer, cx| {
 8869                buffer.edit(edits, None, cx);
 8870            });
 8871
 8872            // Adjust selections so that they end before any comment suffixes that
 8873            // were inserted.
 8874            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8875            let mut selections = this.selections.all::<Point>(cx);
 8876            let snapshot = this.buffer.read(cx).read(cx);
 8877            for selection in &mut selections {
 8878                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8879                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8880                        Ordering::Less => {
 8881                            suffixes_inserted.next();
 8882                            continue;
 8883                        }
 8884                        Ordering::Greater => break,
 8885                        Ordering::Equal => {
 8886                            if selection.end.column == snapshot.line_len(row) {
 8887                                if selection.is_empty() {
 8888                                    selection.start.column -= suffix_len as u32;
 8889                                }
 8890                                selection.end.column -= suffix_len as u32;
 8891                            }
 8892                            break;
 8893                        }
 8894                    }
 8895                }
 8896            }
 8897
 8898            drop(snapshot);
 8899            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8900
 8901            let selections = this.selections.all::<Point>(cx);
 8902            let selections_on_single_row = selections.windows(2).all(|selections| {
 8903                selections[0].start.row == selections[1].start.row
 8904                    && selections[0].end.row == selections[1].end.row
 8905                    && selections[0].start.row == selections[0].end.row
 8906            });
 8907            let selections_selecting = selections
 8908                .iter()
 8909                .any(|selection| selection.start != selection.end);
 8910            let advance_downwards = action.advance_downwards
 8911                && selections_on_single_row
 8912                && !selections_selecting
 8913                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8914
 8915            if advance_downwards {
 8916                let snapshot = this.buffer.read(cx).snapshot(cx);
 8917
 8918                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8919                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8920                        let mut point = display_point.to_point(display_snapshot);
 8921                        point.row += 1;
 8922                        point = snapshot.clip_point(point, Bias::Left);
 8923                        let display_point = point.to_display_point(display_snapshot);
 8924                        let goal = SelectionGoal::HorizontalPosition(
 8925                            display_snapshot
 8926                                .x_for_display_point(display_point, text_layout_details)
 8927                                .into(),
 8928                        );
 8929                        (display_point, goal)
 8930                    })
 8931                });
 8932            }
 8933        });
 8934    }
 8935
 8936    pub fn select_enclosing_symbol(
 8937        &mut self,
 8938        _: &SelectEnclosingSymbol,
 8939        cx: &mut ViewContext<Self>,
 8940    ) {
 8941        let buffer = self.buffer.read(cx).snapshot(cx);
 8942        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8943
 8944        fn update_selection(
 8945            selection: &Selection<usize>,
 8946            buffer_snap: &MultiBufferSnapshot,
 8947        ) -> Option<Selection<usize>> {
 8948            let cursor = selection.head();
 8949            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8950            for symbol in symbols.iter().rev() {
 8951                let start = symbol.range.start.to_offset(buffer_snap);
 8952                let end = symbol.range.end.to_offset(buffer_snap);
 8953                let new_range = start..end;
 8954                if start < selection.start || end > selection.end {
 8955                    return Some(Selection {
 8956                        id: selection.id,
 8957                        start: new_range.start,
 8958                        end: new_range.end,
 8959                        goal: SelectionGoal::None,
 8960                        reversed: selection.reversed,
 8961                    });
 8962                }
 8963            }
 8964            None
 8965        }
 8966
 8967        let mut selected_larger_symbol = false;
 8968        let new_selections = old_selections
 8969            .iter()
 8970            .map(|selection| match update_selection(selection, &buffer) {
 8971                Some(new_selection) => {
 8972                    if new_selection.range() != selection.range() {
 8973                        selected_larger_symbol = true;
 8974                    }
 8975                    new_selection
 8976                }
 8977                None => selection.clone(),
 8978            })
 8979            .collect::<Vec<_>>();
 8980
 8981        if selected_larger_symbol {
 8982            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8983                s.select(new_selections);
 8984            });
 8985        }
 8986    }
 8987
 8988    pub fn select_larger_syntax_node(
 8989        &mut self,
 8990        _: &SelectLargerSyntaxNode,
 8991        cx: &mut ViewContext<Self>,
 8992    ) {
 8993        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8994        let buffer = self.buffer.read(cx).snapshot(cx);
 8995        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8996
 8997        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8998        let mut selected_larger_node = false;
 8999        let new_selections = old_selections
 9000            .iter()
 9001            .map(|selection| {
 9002                let old_range = selection.start..selection.end;
 9003                let mut new_range = old_range.clone();
 9004                while let Some(containing_range) =
 9005                    buffer.range_for_syntax_ancestor(new_range.clone())
 9006                {
 9007                    new_range = containing_range;
 9008                    if !display_map.intersects_fold(new_range.start)
 9009                        && !display_map.intersects_fold(new_range.end)
 9010                    {
 9011                        break;
 9012                    }
 9013                }
 9014
 9015                selected_larger_node |= new_range != old_range;
 9016                Selection {
 9017                    id: selection.id,
 9018                    start: new_range.start,
 9019                    end: new_range.end,
 9020                    goal: SelectionGoal::None,
 9021                    reversed: selection.reversed,
 9022                }
 9023            })
 9024            .collect::<Vec<_>>();
 9025
 9026        if selected_larger_node {
 9027            stack.push(old_selections);
 9028            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9029                s.select(new_selections);
 9030            });
 9031        }
 9032        self.select_larger_syntax_node_stack = stack;
 9033    }
 9034
 9035    pub fn select_smaller_syntax_node(
 9036        &mut self,
 9037        _: &SelectSmallerSyntaxNode,
 9038        cx: &mut ViewContext<Self>,
 9039    ) {
 9040        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9041        if let Some(selections) = stack.pop() {
 9042            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9043                s.select(selections.to_vec());
 9044            });
 9045        }
 9046        self.select_larger_syntax_node_stack = stack;
 9047    }
 9048
 9049    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9050        if !EditorSettings::get_global(cx).gutter.runnables {
 9051            self.clear_tasks();
 9052            return Task::ready(());
 9053        }
 9054        let project = self.project.clone();
 9055        cx.spawn(|this, mut cx| async move {
 9056            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9057                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9058            }) else {
 9059                return;
 9060            };
 9061
 9062            let Some(project) = project else {
 9063                return;
 9064            };
 9065
 9066            let hide_runnables = project
 9067                .update(&mut cx, |project, cx| {
 9068                    // Do not display any test indicators in non-dev server remote projects.
 9069                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9070                })
 9071                .unwrap_or(true);
 9072            if hide_runnables {
 9073                return;
 9074            }
 9075            let new_rows =
 9076                cx.background_executor()
 9077                    .spawn({
 9078                        let snapshot = display_snapshot.clone();
 9079                        async move {
 9080                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9081                        }
 9082                    })
 9083                    .await;
 9084            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9085
 9086            this.update(&mut cx, |this, _| {
 9087                this.clear_tasks();
 9088                for (key, value) in rows {
 9089                    this.insert_tasks(key, value);
 9090                }
 9091            })
 9092            .ok();
 9093        })
 9094    }
 9095    fn fetch_runnable_ranges(
 9096        snapshot: &DisplaySnapshot,
 9097        range: Range<Anchor>,
 9098    ) -> Vec<language::RunnableRange> {
 9099        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9100    }
 9101
 9102    fn runnable_rows(
 9103        project: Model<Project>,
 9104        snapshot: DisplaySnapshot,
 9105        runnable_ranges: Vec<RunnableRange>,
 9106        mut cx: AsyncWindowContext,
 9107    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9108        runnable_ranges
 9109            .into_iter()
 9110            .filter_map(|mut runnable| {
 9111                let tasks = cx
 9112                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9113                    .ok()?;
 9114                if tasks.is_empty() {
 9115                    return None;
 9116                }
 9117
 9118                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9119
 9120                let row = snapshot
 9121                    .buffer_snapshot
 9122                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9123                    .1
 9124                    .start
 9125                    .row;
 9126
 9127                let context_range =
 9128                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9129                Some((
 9130                    (runnable.buffer_id, row),
 9131                    RunnableTasks {
 9132                        templates: tasks,
 9133                        offset: MultiBufferOffset(runnable.run_range.start),
 9134                        context_range,
 9135                        column: point.column,
 9136                        extra_variables: runnable.extra_captures,
 9137                    },
 9138                ))
 9139            })
 9140            .collect()
 9141    }
 9142
 9143    fn templates_with_tags(
 9144        project: &Model<Project>,
 9145        runnable: &mut Runnable,
 9146        cx: &WindowContext<'_>,
 9147    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9148        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9149            let (worktree_id, file) = project
 9150                .buffer_for_id(runnable.buffer, cx)
 9151                .and_then(|buffer| buffer.read(cx).file())
 9152                .map(|file| (file.worktree_id(cx), file.clone()))
 9153                .unzip();
 9154
 9155            (
 9156                project.task_store().read(cx).task_inventory().cloned(),
 9157                worktree_id,
 9158                file,
 9159            )
 9160        });
 9161
 9162        let tags = mem::take(&mut runnable.tags);
 9163        let mut tags: Vec<_> = tags
 9164            .into_iter()
 9165            .flat_map(|tag| {
 9166                let tag = tag.0.clone();
 9167                inventory
 9168                    .as_ref()
 9169                    .into_iter()
 9170                    .flat_map(|inventory| {
 9171                        inventory.read(cx).list_tasks(
 9172                            file.clone(),
 9173                            Some(runnable.language.clone()),
 9174                            worktree_id,
 9175                            cx,
 9176                        )
 9177                    })
 9178                    .filter(move |(_, template)| {
 9179                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9180                    })
 9181            })
 9182            .sorted_by_key(|(kind, _)| kind.to_owned())
 9183            .collect();
 9184        if let Some((leading_tag_source, _)) = tags.first() {
 9185            // Strongest source wins; if we have worktree tag binding, prefer that to
 9186            // global and language bindings;
 9187            // if we have a global binding, prefer that to language binding.
 9188            let first_mismatch = tags
 9189                .iter()
 9190                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9191            if let Some(index) = first_mismatch {
 9192                tags.truncate(index);
 9193            }
 9194        }
 9195
 9196        tags
 9197    }
 9198
 9199    pub fn move_to_enclosing_bracket(
 9200        &mut self,
 9201        _: &MoveToEnclosingBracket,
 9202        cx: &mut ViewContext<Self>,
 9203    ) {
 9204        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9205            s.move_offsets_with(|snapshot, selection| {
 9206                let Some(enclosing_bracket_ranges) =
 9207                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9208                else {
 9209                    return;
 9210                };
 9211
 9212                let mut best_length = usize::MAX;
 9213                let mut best_inside = false;
 9214                let mut best_in_bracket_range = false;
 9215                let mut best_destination = None;
 9216                for (open, close) in enclosing_bracket_ranges {
 9217                    let close = close.to_inclusive();
 9218                    let length = close.end() - open.start;
 9219                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9220                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9221                        || close.contains(&selection.head());
 9222
 9223                    // If best is next to a bracket and current isn't, skip
 9224                    if !in_bracket_range && best_in_bracket_range {
 9225                        continue;
 9226                    }
 9227
 9228                    // Prefer smaller lengths unless best is inside and current isn't
 9229                    if length > best_length && (best_inside || !inside) {
 9230                        continue;
 9231                    }
 9232
 9233                    best_length = length;
 9234                    best_inside = inside;
 9235                    best_in_bracket_range = in_bracket_range;
 9236                    best_destination = Some(
 9237                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9238                            if inside {
 9239                                open.end
 9240                            } else {
 9241                                open.start
 9242                            }
 9243                        } else if inside {
 9244                            *close.start()
 9245                        } else {
 9246                            *close.end()
 9247                        },
 9248                    );
 9249                }
 9250
 9251                if let Some(destination) = best_destination {
 9252                    selection.collapse_to(destination, SelectionGoal::None);
 9253                }
 9254            })
 9255        });
 9256    }
 9257
 9258    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9259        self.end_selection(cx);
 9260        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9261        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9262            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9263            self.select_next_state = entry.select_next_state;
 9264            self.select_prev_state = entry.select_prev_state;
 9265            self.add_selections_state = entry.add_selections_state;
 9266            self.request_autoscroll(Autoscroll::newest(), cx);
 9267        }
 9268        self.selection_history.mode = SelectionHistoryMode::Normal;
 9269    }
 9270
 9271    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9272        self.end_selection(cx);
 9273        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9274        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9275            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9276            self.select_next_state = entry.select_next_state;
 9277            self.select_prev_state = entry.select_prev_state;
 9278            self.add_selections_state = entry.add_selections_state;
 9279            self.request_autoscroll(Autoscroll::newest(), cx);
 9280        }
 9281        self.selection_history.mode = SelectionHistoryMode::Normal;
 9282    }
 9283
 9284    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9285        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9286    }
 9287
 9288    pub fn expand_excerpts_down(
 9289        &mut self,
 9290        action: &ExpandExcerptsDown,
 9291        cx: &mut ViewContext<Self>,
 9292    ) {
 9293        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9294    }
 9295
 9296    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9297        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9298    }
 9299
 9300    pub fn expand_excerpts_for_direction(
 9301        &mut self,
 9302        lines: u32,
 9303        direction: ExpandExcerptDirection,
 9304        cx: &mut ViewContext<Self>,
 9305    ) {
 9306        let selections = self.selections.disjoint_anchors();
 9307
 9308        let lines = if lines == 0 {
 9309            EditorSettings::get_global(cx).expand_excerpt_lines
 9310        } else {
 9311            lines
 9312        };
 9313
 9314        self.buffer.update(cx, |buffer, cx| {
 9315            buffer.expand_excerpts(
 9316                selections
 9317                    .iter()
 9318                    .map(|selection| selection.head().excerpt_id)
 9319                    .dedup(),
 9320                lines,
 9321                direction,
 9322                cx,
 9323            )
 9324        })
 9325    }
 9326
 9327    pub fn expand_excerpt(
 9328        &mut self,
 9329        excerpt: ExcerptId,
 9330        direction: ExpandExcerptDirection,
 9331        cx: &mut ViewContext<Self>,
 9332    ) {
 9333        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9334        self.buffer.update(cx, |buffer, cx| {
 9335            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9336        })
 9337    }
 9338
 9339    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9340        self.go_to_diagnostic_impl(Direction::Next, cx)
 9341    }
 9342
 9343    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9344        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9345    }
 9346
 9347    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9348        let buffer = self.buffer.read(cx).snapshot(cx);
 9349        let selection = self.selections.newest::<usize>(cx);
 9350
 9351        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9352        if direction == Direction::Next {
 9353            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9354                let (group_id, jump_to) = popover.activation_info();
 9355                if self.activate_diagnostics(group_id, cx) {
 9356                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9357                        let mut new_selection = s.newest_anchor().clone();
 9358                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9359                        s.select_anchors(vec![new_selection.clone()]);
 9360                    });
 9361                }
 9362                return;
 9363            }
 9364        }
 9365
 9366        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9367            active_diagnostics
 9368                .primary_range
 9369                .to_offset(&buffer)
 9370                .to_inclusive()
 9371        });
 9372        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9373            if active_primary_range.contains(&selection.head()) {
 9374                *active_primary_range.start()
 9375            } else {
 9376                selection.head()
 9377            }
 9378        } else {
 9379            selection.head()
 9380        };
 9381        let snapshot = self.snapshot(cx);
 9382        loop {
 9383            let diagnostics = if direction == Direction::Prev {
 9384                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9385            } else {
 9386                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9387            }
 9388            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9389            let group = diagnostics
 9390                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9391                // be sorted in a stable way
 9392                // skip until we are at current active diagnostic, if it exists
 9393                .skip_while(|entry| {
 9394                    (match direction {
 9395                        Direction::Prev => entry.range.start >= search_start,
 9396                        Direction::Next => entry.range.start <= search_start,
 9397                    }) && self
 9398                        .active_diagnostics
 9399                        .as_ref()
 9400                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9401                })
 9402                .find_map(|entry| {
 9403                    if entry.diagnostic.is_primary
 9404                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9405                        && !entry.range.is_empty()
 9406                        // if we match with the active diagnostic, skip it
 9407                        && Some(entry.diagnostic.group_id)
 9408                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9409                    {
 9410                        Some((entry.range, entry.diagnostic.group_id))
 9411                    } else {
 9412                        None
 9413                    }
 9414                });
 9415
 9416            if let Some((primary_range, group_id)) = group {
 9417                if self.activate_diagnostics(group_id, cx) {
 9418                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9419                        s.select(vec![Selection {
 9420                            id: selection.id,
 9421                            start: primary_range.start,
 9422                            end: primary_range.start,
 9423                            reversed: false,
 9424                            goal: SelectionGoal::None,
 9425                        }]);
 9426                    });
 9427                }
 9428                break;
 9429            } else {
 9430                // Cycle around to the start of the buffer, potentially moving back to the start of
 9431                // the currently active diagnostic.
 9432                active_primary_range.take();
 9433                if direction == Direction::Prev {
 9434                    if search_start == buffer.len() {
 9435                        break;
 9436                    } else {
 9437                        search_start = buffer.len();
 9438                    }
 9439                } else if search_start == 0 {
 9440                    break;
 9441                } else {
 9442                    search_start = 0;
 9443                }
 9444            }
 9445        }
 9446    }
 9447
 9448    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9449        let snapshot = self
 9450            .display_map
 9451            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9452        let selection = self.selections.newest::<Point>(cx);
 9453        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9454    }
 9455
 9456    fn go_to_hunk_after_position(
 9457        &mut self,
 9458        snapshot: &DisplaySnapshot,
 9459        position: Point,
 9460        cx: &mut ViewContext<'_, Editor>,
 9461    ) -> Option<MultiBufferDiffHunk> {
 9462        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9463            snapshot,
 9464            position,
 9465            false,
 9466            snapshot
 9467                .buffer_snapshot
 9468                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9469            cx,
 9470        ) {
 9471            return Some(hunk);
 9472        }
 9473
 9474        let wrapped_point = Point::zero();
 9475        self.go_to_next_hunk_in_direction(
 9476            snapshot,
 9477            wrapped_point,
 9478            true,
 9479            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9480                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9481            ),
 9482            cx,
 9483        )
 9484    }
 9485
 9486    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9487        let snapshot = self
 9488            .display_map
 9489            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9490        let selection = self.selections.newest::<Point>(cx);
 9491
 9492        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9493    }
 9494
 9495    fn go_to_hunk_before_position(
 9496        &mut self,
 9497        snapshot: &DisplaySnapshot,
 9498        position: Point,
 9499        cx: &mut ViewContext<'_, Editor>,
 9500    ) -> Option<MultiBufferDiffHunk> {
 9501        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9502            snapshot,
 9503            position,
 9504            false,
 9505            snapshot
 9506                .buffer_snapshot
 9507                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9508            cx,
 9509        ) {
 9510            return Some(hunk);
 9511        }
 9512
 9513        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9514        self.go_to_next_hunk_in_direction(
 9515            snapshot,
 9516            wrapped_point,
 9517            true,
 9518            snapshot
 9519                .buffer_snapshot
 9520                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9521            cx,
 9522        )
 9523    }
 9524
 9525    fn go_to_next_hunk_in_direction(
 9526        &mut self,
 9527        snapshot: &DisplaySnapshot,
 9528        initial_point: Point,
 9529        is_wrapped: bool,
 9530        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9531        cx: &mut ViewContext<Editor>,
 9532    ) -> Option<MultiBufferDiffHunk> {
 9533        let display_point = initial_point.to_display_point(snapshot);
 9534        let mut hunks = hunks
 9535            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9536            .filter(|(display_hunk, _)| {
 9537                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9538            })
 9539            .dedup();
 9540
 9541        if let Some((display_hunk, hunk)) = hunks.next() {
 9542            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9543                let row = display_hunk.start_display_row();
 9544                let point = DisplayPoint::new(row, 0);
 9545                s.select_display_ranges([point..point]);
 9546            });
 9547
 9548            Some(hunk)
 9549        } else {
 9550            None
 9551        }
 9552    }
 9553
 9554    pub fn go_to_definition(
 9555        &mut self,
 9556        _: &GoToDefinition,
 9557        cx: &mut ViewContext<Self>,
 9558    ) -> Task<Result<Navigated>> {
 9559        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9560        cx.spawn(|editor, mut cx| async move {
 9561            if definition.await? == Navigated::Yes {
 9562                return Ok(Navigated::Yes);
 9563            }
 9564            match editor.update(&mut cx, |editor, cx| {
 9565                editor.find_all_references(&FindAllReferences, cx)
 9566            })? {
 9567                Some(references) => references.await,
 9568                None => Ok(Navigated::No),
 9569            }
 9570        })
 9571    }
 9572
 9573    pub fn go_to_declaration(
 9574        &mut self,
 9575        _: &GoToDeclaration,
 9576        cx: &mut ViewContext<Self>,
 9577    ) -> Task<Result<Navigated>> {
 9578        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9579    }
 9580
 9581    pub fn go_to_declaration_split(
 9582        &mut self,
 9583        _: &GoToDeclaration,
 9584        cx: &mut ViewContext<Self>,
 9585    ) -> Task<Result<Navigated>> {
 9586        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9587    }
 9588
 9589    pub fn go_to_implementation(
 9590        &mut self,
 9591        _: &GoToImplementation,
 9592        cx: &mut ViewContext<Self>,
 9593    ) -> Task<Result<Navigated>> {
 9594        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9595    }
 9596
 9597    pub fn go_to_implementation_split(
 9598        &mut self,
 9599        _: &GoToImplementationSplit,
 9600        cx: &mut ViewContext<Self>,
 9601    ) -> Task<Result<Navigated>> {
 9602        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9603    }
 9604
 9605    pub fn go_to_type_definition(
 9606        &mut self,
 9607        _: &GoToTypeDefinition,
 9608        cx: &mut ViewContext<Self>,
 9609    ) -> Task<Result<Navigated>> {
 9610        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9611    }
 9612
 9613    pub fn go_to_definition_split(
 9614        &mut self,
 9615        _: &GoToDefinitionSplit,
 9616        cx: &mut ViewContext<Self>,
 9617    ) -> Task<Result<Navigated>> {
 9618        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9619    }
 9620
 9621    pub fn go_to_type_definition_split(
 9622        &mut self,
 9623        _: &GoToTypeDefinitionSplit,
 9624        cx: &mut ViewContext<Self>,
 9625    ) -> Task<Result<Navigated>> {
 9626        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9627    }
 9628
 9629    fn go_to_definition_of_kind(
 9630        &mut self,
 9631        kind: GotoDefinitionKind,
 9632        split: bool,
 9633        cx: &mut ViewContext<Self>,
 9634    ) -> Task<Result<Navigated>> {
 9635        let Some(provider) = self.semantics_provider.clone() else {
 9636            return Task::ready(Ok(Navigated::No));
 9637        };
 9638        let buffer = self.buffer.read(cx);
 9639        let head = self.selections.newest::<usize>(cx).head();
 9640        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9641            text_anchor
 9642        } else {
 9643            return Task::ready(Ok(Navigated::No));
 9644        };
 9645
 9646        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9647            return Task::ready(Ok(Navigated::No));
 9648        };
 9649
 9650        cx.spawn(|editor, mut cx| async move {
 9651            let definitions = definitions.await?;
 9652            let navigated = editor
 9653                .update(&mut cx, |editor, cx| {
 9654                    editor.navigate_to_hover_links(
 9655                        Some(kind),
 9656                        definitions
 9657                            .into_iter()
 9658                            .filter(|location| {
 9659                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9660                            })
 9661                            .map(HoverLink::Text)
 9662                            .collect::<Vec<_>>(),
 9663                        split,
 9664                        cx,
 9665                    )
 9666                })?
 9667                .await?;
 9668            anyhow::Ok(navigated)
 9669        })
 9670    }
 9671
 9672    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9673        let position = self.selections.newest_anchor().head();
 9674        let Some((buffer, buffer_position)) =
 9675            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9676        else {
 9677            return;
 9678        };
 9679
 9680        cx.spawn(|editor, mut cx| async move {
 9681            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9682                editor.update(&mut cx, |_, cx| {
 9683                    cx.open_url(&url);
 9684                })
 9685            } else {
 9686                Ok(())
 9687            }
 9688        })
 9689        .detach();
 9690    }
 9691
 9692    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9693        let Some(workspace) = self.workspace() else {
 9694            return;
 9695        };
 9696
 9697        let position = self.selections.newest_anchor().head();
 9698
 9699        let Some((buffer, buffer_position)) =
 9700            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9701        else {
 9702            return;
 9703        };
 9704
 9705        let project = self.project.clone();
 9706
 9707        cx.spawn(|_, mut cx| async move {
 9708            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9709
 9710            if let Some((_, path)) = result {
 9711                workspace
 9712                    .update(&mut cx, |workspace, cx| {
 9713                        workspace.open_resolved_path(path, cx)
 9714                    })?
 9715                    .await?;
 9716            }
 9717            anyhow::Ok(())
 9718        })
 9719        .detach();
 9720    }
 9721
 9722    pub(crate) fn navigate_to_hover_links(
 9723        &mut self,
 9724        kind: Option<GotoDefinitionKind>,
 9725        mut definitions: Vec<HoverLink>,
 9726        split: bool,
 9727        cx: &mut ViewContext<Editor>,
 9728    ) -> Task<Result<Navigated>> {
 9729        // If there is one definition, just open it directly
 9730        if definitions.len() == 1 {
 9731            let definition = definitions.pop().unwrap();
 9732
 9733            enum TargetTaskResult {
 9734                Location(Option<Location>),
 9735                AlreadyNavigated,
 9736            }
 9737
 9738            let target_task = match definition {
 9739                HoverLink::Text(link) => {
 9740                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9741                }
 9742                HoverLink::InlayHint(lsp_location, server_id) => {
 9743                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9744                    cx.background_executor().spawn(async move {
 9745                        let location = computation.await?;
 9746                        Ok(TargetTaskResult::Location(location))
 9747                    })
 9748                }
 9749                HoverLink::Url(url) => {
 9750                    cx.open_url(&url);
 9751                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9752                }
 9753                HoverLink::File(path) => {
 9754                    if let Some(workspace) = self.workspace() {
 9755                        cx.spawn(|_, mut cx| async move {
 9756                            workspace
 9757                                .update(&mut cx, |workspace, cx| {
 9758                                    workspace.open_resolved_path(path, cx)
 9759                                })?
 9760                                .await
 9761                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9762                        })
 9763                    } else {
 9764                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9765                    }
 9766                }
 9767            };
 9768            cx.spawn(|editor, mut cx| async move {
 9769                let target = match target_task.await.context("target resolution task")? {
 9770                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9771                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9772                    TargetTaskResult::Location(Some(target)) => target,
 9773                };
 9774
 9775                editor.update(&mut cx, |editor, cx| {
 9776                    let Some(workspace) = editor.workspace() else {
 9777                        return Navigated::No;
 9778                    };
 9779                    let pane = workspace.read(cx).active_pane().clone();
 9780
 9781                    let range = target.range.to_offset(target.buffer.read(cx));
 9782                    let range = editor.range_for_match(&range);
 9783
 9784                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9785                        let buffer = target.buffer.read(cx);
 9786                        let range = check_multiline_range(buffer, range);
 9787                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9788                            s.select_ranges([range]);
 9789                        });
 9790                    } else {
 9791                        cx.window_context().defer(move |cx| {
 9792                            let target_editor: View<Self> =
 9793                                workspace.update(cx, |workspace, cx| {
 9794                                    let pane = if split {
 9795                                        workspace.adjacent_pane(cx)
 9796                                    } else {
 9797                                        workspace.active_pane().clone()
 9798                                    };
 9799
 9800                                    workspace.open_project_item(
 9801                                        pane,
 9802                                        target.buffer.clone(),
 9803                                        true,
 9804                                        true,
 9805                                        cx,
 9806                                    )
 9807                                });
 9808                            target_editor.update(cx, |target_editor, cx| {
 9809                                // When selecting a definition in a different buffer, disable the nav history
 9810                                // to avoid creating a history entry at the previous cursor location.
 9811                                pane.update(cx, |pane, _| pane.disable_history());
 9812                                let buffer = target.buffer.read(cx);
 9813                                let range = check_multiline_range(buffer, range);
 9814                                target_editor.change_selections(
 9815                                    Some(Autoscroll::focused()),
 9816                                    cx,
 9817                                    |s| {
 9818                                        s.select_ranges([range]);
 9819                                    },
 9820                                );
 9821                                pane.update(cx, |pane, _| pane.enable_history());
 9822                            });
 9823                        });
 9824                    }
 9825                    Navigated::Yes
 9826                })
 9827            })
 9828        } else if !definitions.is_empty() {
 9829            cx.spawn(|editor, mut cx| async move {
 9830                let (title, location_tasks, workspace) = editor
 9831                    .update(&mut cx, |editor, cx| {
 9832                        let tab_kind = match kind {
 9833                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9834                            _ => "Definitions",
 9835                        };
 9836                        let title = definitions
 9837                            .iter()
 9838                            .find_map(|definition| match definition {
 9839                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9840                                    let buffer = origin.buffer.read(cx);
 9841                                    format!(
 9842                                        "{} for {}",
 9843                                        tab_kind,
 9844                                        buffer
 9845                                            .text_for_range(origin.range.clone())
 9846                                            .collect::<String>()
 9847                                    )
 9848                                }),
 9849                                HoverLink::InlayHint(_, _) => None,
 9850                                HoverLink::Url(_) => None,
 9851                                HoverLink::File(_) => None,
 9852                            })
 9853                            .unwrap_or(tab_kind.to_string());
 9854                        let location_tasks = definitions
 9855                            .into_iter()
 9856                            .map(|definition| match definition {
 9857                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9858                                HoverLink::InlayHint(lsp_location, server_id) => {
 9859                                    editor.compute_target_location(lsp_location, server_id, cx)
 9860                                }
 9861                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9862                                HoverLink::File(_) => Task::ready(Ok(None)),
 9863                            })
 9864                            .collect::<Vec<_>>();
 9865                        (title, location_tasks, editor.workspace().clone())
 9866                    })
 9867                    .context("location tasks preparation")?;
 9868
 9869                let locations = future::join_all(location_tasks)
 9870                    .await
 9871                    .into_iter()
 9872                    .filter_map(|location| location.transpose())
 9873                    .collect::<Result<_>>()
 9874                    .context("location tasks")?;
 9875
 9876                let Some(workspace) = workspace else {
 9877                    return Ok(Navigated::No);
 9878                };
 9879                let opened = workspace
 9880                    .update(&mut cx, |workspace, cx| {
 9881                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9882                    })
 9883                    .ok();
 9884
 9885                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9886            })
 9887        } else {
 9888            Task::ready(Ok(Navigated::No))
 9889        }
 9890    }
 9891
 9892    fn compute_target_location(
 9893        &self,
 9894        lsp_location: lsp::Location,
 9895        server_id: LanguageServerId,
 9896        cx: &mut ViewContext<Editor>,
 9897    ) -> Task<anyhow::Result<Option<Location>>> {
 9898        let Some(project) = self.project.clone() else {
 9899            return Task::Ready(Some(Ok(None)));
 9900        };
 9901
 9902        cx.spawn(move |editor, mut cx| async move {
 9903            let location_task = editor.update(&mut cx, |editor, cx| {
 9904                project.update(cx, |project, cx| {
 9905                    let language_server_name =
 9906                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9907                            project
 9908                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9909                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9910                        });
 9911                    language_server_name.map(|language_server_name| {
 9912                        project.open_local_buffer_via_lsp(
 9913                            lsp_location.uri.clone(),
 9914                            server_id,
 9915                            language_server_name,
 9916                            cx,
 9917                        )
 9918                    })
 9919                })
 9920            })?;
 9921            let location = match location_task {
 9922                Some(task) => Some({
 9923                    let target_buffer_handle = task.await.context("open local buffer")?;
 9924                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9925                        let target_start = target_buffer
 9926                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9927                        let target_end = target_buffer
 9928                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9929                        target_buffer.anchor_after(target_start)
 9930                            ..target_buffer.anchor_before(target_end)
 9931                    })?;
 9932                    Location {
 9933                        buffer: target_buffer_handle,
 9934                        range,
 9935                    }
 9936                }),
 9937                None => None,
 9938            };
 9939            Ok(location)
 9940        })
 9941    }
 9942
 9943    pub fn find_all_references(
 9944        &mut self,
 9945        _: &FindAllReferences,
 9946        cx: &mut ViewContext<Self>,
 9947    ) -> Option<Task<Result<Navigated>>> {
 9948        let multi_buffer = self.buffer.read(cx);
 9949        let selection = self.selections.newest::<usize>(cx);
 9950        let head = selection.head();
 9951
 9952        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9953        let head_anchor = multi_buffer_snapshot.anchor_at(
 9954            head,
 9955            if head < selection.tail() {
 9956                Bias::Right
 9957            } else {
 9958                Bias::Left
 9959            },
 9960        );
 9961
 9962        match self
 9963            .find_all_references_task_sources
 9964            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9965        {
 9966            Ok(_) => {
 9967                log::info!(
 9968                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9969                );
 9970                return None;
 9971            }
 9972            Err(i) => {
 9973                self.find_all_references_task_sources.insert(i, head_anchor);
 9974            }
 9975        }
 9976
 9977        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9978        let workspace = self.workspace()?;
 9979        let project = workspace.read(cx).project().clone();
 9980        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9981        Some(cx.spawn(|editor, mut cx| async move {
 9982            let _cleanup = defer({
 9983                let mut cx = cx.clone();
 9984                move || {
 9985                    let _ = editor.update(&mut cx, |editor, _| {
 9986                        if let Ok(i) =
 9987                            editor
 9988                                .find_all_references_task_sources
 9989                                .binary_search_by(|anchor| {
 9990                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9991                                })
 9992                        {
 9993                            editor.find_all_references_task_sources.remove(i);
 9994                        }
 9995                    });
 9996                }
 9997            });
 9998
 9999            let locations = references.await?;
10000            if locations.is_empty() {
10001                return anyhow::Ok(Navigated::No);
10002            }
10003
10004            workspace.update(&mut cx, |workspace, cx| {
10005                let title = locations
10006                    .first()
10007                    .as_ref()
10008                    .map(|location| {
10009                        let buffer = location.buffer.read(cx);
10010                        format!(
10011                            "References to `{}`",
10012                            buffer
10013                                .text_for_range(location.range.clone())
10014                                .collect::<String>()
10015                        )
10016                    })
10017                    .unwrap();
10018                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10019                Navigated::Yes
10020            })
10021        }))
10022    }
10023
10024    /// Opens a multibuffer with the given project locations in it
10025    pub fn open_locations_in_multibuffer(
10026        workspace: &mut Workspace,
10027        mut locations: Vec<Location>,
10028        title: String,
10029        split: bool,
10030        cx: &mut ViewContext<Workspace>,
10031    ) {
10032        // If there are multiple definitions, open them in a multibuffer
10033        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10034        let mut locations = locations.into_iter().peekable();
10035        let mut ranges_to_highlight = Vec::new();
10036        let capability = workspace.project().read(cx).capability();
10037
10038        let excerpt_buffer = cx.new_model(|cx| {
10039            let mut multibuffer = MultiBuffer::new(capability);
10040            while let Some(location) = locations.next() {
10041                let buffer = location.buffer.read(cx);
10042                let mut ranges_for_buffer = Vec::new();
10043                let range = location.range.to_offset(buffer);
10044                ranges_for_buffer.push(range.clone());
10045
10046                while let Some(next_location) = locations.peek() {
10047                    if next_location.buffer == location.buffer {
10048                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10049                        locations.next();
10050                    } else {
10051                        break;
10052                    }
10053                }
10054
10055                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10056                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10057                    location.buffer.clone(),
10058                    ranges_for_buffer,
10059                    DEFAULT_MULTIBUFFER_CONTEXT,
10060                    cx,
10061                ))
10062            }
10063
10064            multibuffer.with_title(title)
10065        });
10066
10067        let editor = cx.new_view(|cx| {
10068            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10069        });
10070        editor.update(cx, |editor, cx| {
10071            if let Some(first_range) = ranges_to_highlight.first() {
10072                editor.change_selections(None, cx, |selections| {
10073                    selections.clear_disjoint();
10074                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10075                });
10076            }
10077            editor.highlight_background::<Self>(
10078                &ranges_to_highlight,
10079                |theme| theme.editor_highlighted_line_background,
10080                cx,
10081            );
10082        });
10083
10084        let item = Box::new(editor);
10085        let item_id = item.item_id();
10086
10087        if split {
10088            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10089        } else {
10090            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10091                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10092                    pane.close_current_preview_item(cx)
10093                } else {
10094                    None
10095                }
10096            });
10097            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10098        }
10099        workspace.active_pane().update(cx, |pane, cx| {
10100            pane.set_preview_item_id(Some(item_id), cx);
10101        });
10102    }
10103
10104    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10105        use language::ToOffset as _;
10106
10107        let provider = self.semantics_provider.clone()?;
10108        let selection = self.selections.newest_anchor().clone();
10109        let (cursor_buffer, cursor_buffer_position) = self
10110            .buffer
10111            .read(cx)
10112            .text_anchor_for_position(selection.head(), cx)?;
10113        let (tail_buffer, cursor_buffer_position_end) = self
10114            .buffer
10115            .read(cx)
10116            .text_anchor_for_position(selection.tail(), cx)?;
10117        if tail_buffer != cursor_buffer {
10118            return None;
10119        }
10120
10121        let snapshot = cursor_buffer.read(cx).snapshot();
10122        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10123        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10124        let prepare_rename = provider
10125            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10126            .unwrap_or_else(|| Task::ready(Ok(None)));
10127        drop(snapshot);
10128
10129        Some(cx.spawn(|this, mut cx| async move {
10130            let rename_range = if let Some(range) = prepare_rename.await? {
10131                Some(range)
10132            } else {
10133                this.update(&mut cx, |this, cx| {
10134                    let buffer = this.buffer.read(cx).snapshot(cx);
10135                    let mut buffer_highlights = this
10136                        .document_highlights_for_position(selection.head(), &buffer)
10137                        .filter(|highlight| {
10138                            highlight.start.excerpt_id == selection.head().excerpt_id
10139                                && highlight.end.excerpt_id == selection.head().excerpt_id
10140                        });
10141                    buffer_highlights
10142                        .next()
10143                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10144                })?
10145            };
10146            if let Some(rename_range) = rename_range {
10147                this.update(&mut cx, |this, cx| {
10148                    let snapshot = cursor_buffer.read(cx).snapshot();
10149                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10150                    let cursor_offset_in_rename_range =
10151                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10152                    let cursor_offset_in_rename_range_end =
10153                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10154
10155                    this.take_rename(false, cx);
10156                    let buffer = this.buffer.read(cx).read(cx);
10157                    let cursor_offset = selection.head().to_offset(&buffer);
10158                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10159                    let rename_end = rename_start + rename_buffer_range.len();
10160                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10161                    let mut old_highlight_id = None;
10162                    let old_name: Arc<str> = buffer
10163                        .chunks(rename_start..rename_end, true)
10164                        .map(|chunk| {
10165                            if old_highlight_id.is_none() {
10166                                old_highlight_id = chunk.syntax_highlight_id;
10167                            }
10168                            chunk.text
10169                        })
10170                        .collect::<String>()
10171                        .into();
10172
10173                    drop(buffer);
10174
10175                    // Position the selection in the rename editor so that it matches the current selection.
10176                    this.show_local_selections = false;
10177                    let rename_editor = cx.new_view(|cx| {
10178                        let mut editor = Editor::single_line(cx);
10179                        editor.buffer.update(cx, |buffer, cx| {
10180                            buffer.edit([(0..0, old_name.clone())], None, cx)
10181                        });
10182                        let rename_selection_range = match cursor_offset_in_rename_range
10183                            .cmp(&cursor_offset_in_rename_range_end)
10184                        {
10185                            Ordering::Equal => {
10186                                editor.select_all(&SelectAll, cx);
10187                                return editor;
10188                            }
10189                            Ordering::Less => {
10190                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10191                            }
10192                            Ordering::Greater => {
10193                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10194                            }
10195                        };
10196                        if rename_selection_range.end > old_name.len() {
10197                            editor.select_all(&SelectAll, cx);
10198                        } else {
10199                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10200                                s.select_ranges([rename_selection_range]);
10201                            });
10202                        }
10203                        editor
10204                    });
10205                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10206                        if e == &EditorEvent::Focused {
10207                            cx.emit(EditorEvent::FocusedIn)
10208                        }
10209                    })
10210                    .detach();
10211
10212                    let write_highlights =
10213                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10214                    let read_highlights =
10215                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10216                    let ranges = write_highlights
10217                        .iter()
10218                        .flat_map(|(_, ranges)| ranges.iter())
10219                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10220                        .cloned()
10221                        .collect();
10222
10223                    this.highlight_text::<Rename>(
10224                        ranges,
10225                        HighlightStyle {
10226                            fade_out: Some(0.6),
10227                            ..Default::default()
10228                        },
10229                        cx,
10230                    );
10231                    let rename_focus_handle = rename_editor.focus_handle(cx);
10232                    cx.focus(&rename_focus_handle);
10233                    let block_id = this.insert_blocks(
10234                        [BlockProperties {
10235                            style: BlockStyle::Flex,
10236                            position: range.start,
10237                            height: 1,
10238                            render: Box::new({
10239                                let rename_editor = rename_editor.clone();
10240                                move |cx: &mut BlockContext| {
10241                                    let mut text_style = cx.editor_style.text.clone();
10242                                    if let Some(highlight_style) = old_highlight_id
10243                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10244                                    {
10245                                        text_style = text_style.highlight(highlight_style);
10246                                    }
10247                                    div()
10248                                        .pl(cx.anchor_x)
10249                                        .child(EditorElement::new(
10250                                            &rename_editor,
10251                                            EditorStyle {
10252                                                background: cx.theme().system().transparent,
10253                                                local_player: cx.editor_style.local_player,
10254                                                text: text_style,
10255                                                scrollbar_width: cx.editor_style.scrollbar_width,
10256                                                syntax: cx.editor_style.syntax.clone(),
10257                                                status: cx.editor_style.status.clone(),
10258                                                inlay_hints_style: HighlightStyle {
10259                                                    font_weight: Some(FontWeight::BOLD),
10260                                                    ..make_inlay_hints_style(cx)
10261                                                },
10262                                                suggestions_style: HighlightStyle {
10263                                                    color: Some(cx.theme().status().predictive),
10264                                                    ..HighlightStyle::default()
10265                                                },
10266                                                ..EditorStyle::default()
10267                                            },
10268                                        ))
10269                                        .into_any_element()
10270                                }
10271                            }),
10272                            disposition: BlockDisposition::Below,
10273                            priority: 0,
10274                        }],
10275                        Some(Autoscroll::fit()),
10276                        cx,
10277                    )[0];
10278                    this.pending_rename = Some(RenameState {
10279                        range,
10280                        old_name,
10281                        editor: rename_editor,
10282                        block_id,
10283                    });
10284                })?;
10285            }
10286
10287            Ok(())
10288        }))
10289    }
10290
10291    pub fn confirm_rename(
10292        &mut self,
10293        _: &ConfirmRename,
10294        cx: &mut ViewContext<Self>,
10295    ) -> Option<Task<Result<()>>> {
10296        let rename = self.take_rename(false, cx)?;
10297        let workspace = self.workspace()?.downgrade();
10298        let (buffer, start) = self
10299            .buffer
10300            .read(cx)
10301            .text_anchor_for_position(rename.range.start, cx)?;
10302        let (end_buffer, _) = self
10303            .buffer
10304            .read(cx)
10305            .text_anchor_for_position(rename.range.end, cx)?;
10306        if buffer != end_buffer {
10307            return None;
10308        }
10309
10310        let old_name = rename.old_name;
10311        let new_name = rename.editor.read(cx).text(cx);
10312
10313        let rename = self.semantics_provider.as_ref()?.perform_rename(
10314            &buffer,
10315            start,
10316            new_name.clone(),
10317            cx,
10318        )?;
10319
10320        Some(cx.spawn(|editor, mut cx| async move {
10321            let project_transaction = rename.await?;
10322            Self::open_project_transaction(
10323                &editor,
10324                workspace,
10325                project_transaction,
10326                format!("Rename: {}{}", old_name, new_name),
10327                cx.clone(),
10328            )
10329            .await?;
10330
10331            editor.update(&mut cx, |editor, cx| {
10332                editor.refresh_document_highlights(cx);
10333            })?;
10334            Ok(())
10335        }))
10336    }
10337
10338    fn take_rename(
10339        &mut self,
10340        moving_cursor: bool,
10341        cx: &mut ViewContext<Self>,
10342    ) -> Option<RenameState> {
10343        let rename = self.pending_rename.take()?;
10344        if rename.editor.focus_handle(cx).is_focused(cx) {
10345            cx.focus(&self.focus_handle);
10346        }
10347
10348        self.remove_blocks(
10349            [rename.block_id].into_iter().collect(),
10350            Some(Autoscroll::fit()),
10351            cx,
10352        );
10353        self.clear_highlights::<Rename>(cx);
10354        self.show_local_selections = true;
10355
10356        if moving_cursor {
10357            let rename_editor = rename.editor.read(cx);
10358            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10359
10360            // Update the selection to match the position of the selection inside
10361            // the rename editor.
10362            let snapshot = self.buffer.read(cx).read(cx);
10363            let rename_range = rename.range.to_offset(&snapshot);
10364            let cursor_in_editor = snapshot
10365                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10366                .min(rename_range.end);
10367            drop(snapshot);
10368
10369            self.change_selections(None, cx, |s| {
10370                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10371            });
10372        } else {
10373            self.refresh_document_highlights(cx);
10374        }
10375
10376        Some(rename)
10377    }
10378
10379    pub fn pending_rename(&self) -> Option<&RenameState> {
10380        self.pending_rename.as_ref()
10381    }
10382
10383    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10384        let project = match &self.project {
10385            Some(project) => project.clone(),
10386            None => return None,
10387        };
10388
10389        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10390    }
10391
10392    fn format_selections(
10393        &mut self,
10394        _: &FormatSelections,
10395        cx: &mut ViewContext<Self>,
10396    ) -> Option<Task<Result<()>>> {
10397        let project = match &self.project {
10398            Some(project) => project.clone(),
10399            None => return None,
10400        };
10401
10402        let selections = self
10403            .selections
10404            .all_adjusted(cx)
10405            .into_iter()
10406            .filter(|s| !s.is_empty())
10407            .collect_vec();
10408
10409        Some(self.perform_format(
10410            project,
10411            FormatTrigger::Manual,
10412            FormatTarget::Ranges(selections),
10413            cx,
10414        ))
10415    }
10416
10417    fn perform_format(
10418        &mut self,
10419        project: Model<Project>,
10420        trigger: FormatTrigger,
10421        target: FormatTarget,
10422        cx: &mut ViewContext<Self>,
10423    ) -> Task<Result<()>> {
10424        let buffer = self.buffer().clone();
10425        let mut buffers = buffer.read(cx).all_buffers();
10426        if trigger == FormatTrigger::Save {
10427            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10428        }
10429
10430        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10431        let format = project.update(cx, |project, cx| {
10432            project.format(buffers, true, trigger, target, cx)
10433        });
10434
10435        cx.spawn(|_, mut cx| async move {
10436            let transaction = futures::select_biased! {
10437                () = timeout => {
10438                    log::warn!("timed out waiting for formatting");
10439                    None
10440                }
10441                transaction = format.log_err().fuse() => transaction,
10442            };
10443
10444            buffer
10445                .update(&mut cx, |buffer, cx| {
10446                    if let Some(transaction) = transaction {
10447                        if !buffer.is_singleton() {
10448                            buffer.push_transaction(&transaction.0, cx);
10449                        }
10450                    }
10451
10452                    cx.notify();
10453                })
10454                .ok();
10455
10456            Ok(())
10457        })
10458    }
10459
10460    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10461        if let Some(project) = self.project.clone() {
10462            self.buffer.update(cx, |multi_buffer, cx| {
10463                project.update(cx, |project, cx| {
10464                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10465                });
10466            })
10467        }
10468    }
10469
10470    fn cancel_language_server_work(
10471        &mut self,
10472        _: &CancelLanguageServerWork,
10473        cx: &mut ViewContext<Self>,
10474    ) {
10475        if let Some(project) = self.project.clone() {
10476            self.buffer.update(cx, |multi_buffer, cx| {
10477                project.update(cx, |project, cx| {
10478                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10479                });
10480            })
10481        }
10482    }
10483
10484    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10485        cx.show_character_palette();
10486    }
10487
10488    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10489        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10490            let buffer = self.buffer.read(cx).snapshot(cx);
10491            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10492            let is_valid = buffer
10493                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10494                .any(|entry| {
10495                    entry.diagnostic.is_primary
10496                        && !entry.range.is_empty()
10497                        && entry.range.start == primary_range_start
10498                        && entry.diagnostic.message == active_diagnostics.primary_message
10499                });
10500
10501            if is_valid != active_diagnostics.is_valid {
10502                active_diagnostics.is_valid = is_valid;
10503                let mut new_styles = HashMap::default();
10504                for (block_id, diagnostic) in &active_diagnostics.blocks {
10505                    new_styles.insert(
10506                        *block_id,
10507                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10508                    );
10509                }
10510                self.display_map.update(cx, |display_map, _cx| {
10511                    display_map.replace_blocks(new_styles)
10512                });
10513            }
10514        }
10515    }
10516
10517    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10518        self.dismiss_diagnostics(cx);
10519        let snapshot = self.snapshot(cx);
10520        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10521            let buffer = self.buffer.read(cx).snapshot(cx);
10522
10523            let mut primary_range = None;
10524            let mut primary_message = None;
10525            let mut group_end = Point::zero();
10526            let diagnostic_group = buffer
10527                .diagnostic_group::<MultiBufferPoint>(group_id)
10528                .filter_map(|entry| {
10529                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10530                        && (entry.range.start.row == entry.range.end.row
10531                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10532                    {
10533                        return None;
10534                    }
10535                    if entry.range.end > group_end {
10536                        group_end = entry.range.end;
10537                    }
10538                    if entry.diagnostic.is_primary {
10539                        primary_range = Some(entry.range.clone());
10540                        primary_message = Some(entry.diagnostic.message.clone());
10541                    }
10542                    Some(entry)
10543                })
10544                .collect::<Vec<_>>();
10545            let primary_range = primary_range?;
10546            let primary_message = primary_message?;
10547            let primary_range =
10548                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10549
10550            let blocks = display_map
10551                .insert_blocks(
10552                    diagnostic_group.iter().map(|entry| {
10553                        let diagnostic = entry.diagnostic.clone();
10554                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10555                        BlockProperties {
10556                            style: BlockStyle::Fixed,
10557                            position: buffer.anchor_after(entry.range.start),
10558                            height: message_height,
10559                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10560                            disposition: BlockDisposition::Below,
10561                            priority: 0,
10562                        }
10563                    }),
10564                    cx,
10565                )
10566                .into_iter()
10567                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10568                .collect();
10569
10570            Some(ActiveDiagnosticGroup {
10571                primary_range,
10572                primary_message,
10573                group_id,
10574                blocks,
10575                is_valid: true,
10576            })
10577        });
10578        self.active_diagnostics.is_some()
10579    }
10580
10581    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10582        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10583            self.display_map.update(cx, |display_map, cx| {
10584                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10585            });
10586            cx.notify();
10587        }
10588    }
10589
10590    pub fn set_selections_from_remote(
10591        &mut self,
10592        selections: Vec<Selection<Anchor>>,
10593        pending_selection: Option<Selection<Anchor>>,
10594        cx: &mut ViewContext<Self>,
10595    ) {
10596        let old_cursor_position = self.selections.newest_anchor().head();
10597        self.selections.change_with(cx, |s| {
10598            s.select_anchors(selections);
10599            if let Some(pending_selection) = pending_selection {
10600                s.set_pending(pending_selection, SelectMode::Character);
10601            } else {
10602                s.clear_pending();
10603            }
10604        });
10605        self.selections_did_change(false, &old_cursor_position, true, cx);
10606    }
10607
10608    fn push_to_selection_history(&mut self) {
10609        self.selection_history.push(SelectionHistoryEntry {
10610            selections: self.selections.disjoint_anchors(),
10611            select_next_state: self.select_next_state.clone(),
10612            select_prev_state: self.select_prev_state.clone(),
10613            add_selections_state: self.add_selections_state.clone(),
10614        });
10615    }
10616
10617    pub fn transact(
10618        &mut self,
10619        cx: &mut ViewContext<Self>,
10620        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10621    ) -> Option<TransactionId> {
10622        self.start_transaction_at(Instant::now(), cx);
10623        update(self, cx);
10624        self.end_transaction_at(Instant::now(), cx)
10625    }
10626
10627    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10628        self.end_selection(cx);
10629        if let Some(tx_id) = self
10630            .buffer
10631            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10632        {
10633            self.selection_history
10634                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10635            cx.emit(EditorEvent::TransactionBegun {
10636                transaction_id: tx_id,
10637            })
10638        }
10639    }
10640
10641    fn end_transaction_at(
10642        &mut self,
10643        now: Instant,
10644        cx: &mut ViewContext<Self>,
10645    ) -> Option<TransactionId> {
10646        if let Some(transaction_id) = self
10647            .buffer
10648            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10649        {
10650            if let Some((_, end_selections)) =
10651                self.selection_history.transaction_mut(transaction_id)
10652            {
10653                *end_selections = Some(self.selections.disjoint_anchors());
10654            } else {
10655                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10656            }
10657
10658            cx.emit(EditorEvent::Edited { transaction_id });
10659            Some(transaction_id)
10660        } else {
10661            None
10662        }
10663    }
10664
10665    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10666        let selection = self.selections.newest::<Point>(cx);
10667
10668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10669        let range = if selection.is_empty() {
10670            let point = selection.head().to_display_point(&display_map);
10671            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10672            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10673                .to_point(&display_map);
10674            start..end
10675        } else {
10676            selection.range()
10677        };
10678        if display_map.folds_in_range(range).next().is_some() {
10679            self.unfold_lines(&Default::default(), cx)
10680        } else {
10681            self.fold(&Default::default(), cx)
10682        }
10683    }
10684
10685    pub fn toggle_fold_recursive(
10686        &mut self,
10687        _: &actions::ToggleFoldRecursive,
10688        cx: &mut ViewContext<Self>,
10689    ) {
10690        let selection = self.selections.newest::<Point>(cx);
10691
10692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10693        let range = if selection.is_empty() {
10694            let point = selection.head().to_display_point(&display_map);
10695            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10696            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10697                .to_point(&display_map);
10698            start..end
10699        } else {
10700            selection.range()
10701        };
10702        if display_map.folds_in_range(range).next().is_some() {
10703            self.unfold_recursive(&Default::default(), cx)
10704        } else {
10705            self.fold_recursive(&Default::default(), cx)
10706        }
10707    }
10708
10709    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10710        let mut fold_ranges = Vec::new();
10711        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10712        let selections = self.selections.all_adjusted(cx);
10713
10714        for selection in selections {
10715            let range = selection.range().sorted();
10716            let buffer_start_row = range.start.row;
10717
10718            if range.start.row != range.end.row {
10719                let mut found = false;
10720                let mut row = range.start.row;
10721                while row <= range.end.row {
10722                    if let Some((foldable_range, fold_text)) =
10723                        { display_map.foldable_range(MultiBufferRow(row)) }
10724                    {
10725                        found = true;
10726                        row = foldable_range.end.row + 1;
10727                        fold_ranges.push((foldable_range, fold_text));
10728                    } else {
10729                        row += 1
10730                    }
10731                }
10732                if found {
10733                    continue;
10734                }
10735            }
10736
10737            for row in (0..=range.start.row).rev() {
10738                if let Some((foldable_range, fold_text)) =
10739                    display_map.foldable_range(MultiBufferRow(row))
10740                {
10741                    if foldable_range.end.row >= buffer_start_row {
10742                        fold_ranges.push((foldable_range, fold_text));
10743                        if row <= range.start.row {
10744                            break;
10745                        }
10746                    }
10747                }
10748            }
10749        }
10750
10751        self.fold_ranges(fold_ranges, true, cx);
10752    }
10753
10754    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10755        let mut fold_ranges = Vec::new();
10756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10757
10758        for row in 0..display_map.max_buffer_row().0 {
10759            if let Some((foldable_range, fold_text)) =
10760                display_map.foldable_range(MultiBufferRow(row))
10761            {
10762                fold_ranges.push((foldable_range, fold_text));
10763            }
10764        }
10765
10766        self.fold_ranges(fold_ranges, true, cx);
10767    }
10768
10769    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10770        let mut fold_ranges = Vec::new();
10771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10772        let selections = self.selections.all_adjusted(cx);
10773
10774        for selection in selections {
10775            let range = selection.range().sorted();
10776            let buffer_start_row = range.start.row;
10777
10778            if range.start.row != range.end.row {
10779                let mut found = false;
10780                for row in range.start.row..=range.end.row {
10781                    if let Some((foldable_range, fold_text)) =
10782                        { display_map.foldable_range(MultiBufferRow(row)) }
10783                    {
10784                        found = true;
10785                        fold_ranges.push((foldable_range, fold_text));
10786                    }
10787                }
10788                if found {
10789                    continue;
10790                }
10791            }
10792
10793            for row in (0..=range.start.row).rev() {
10794                if let Some((foldable_range, fold_text)) =
10795                    display_map.foldable_range(MultiBufferRow(row))
10796                {
10797                    if foldable_range.end.row >= buffer_start_row {
10798                        fold_ranges.push((foldable_range, fold_text));
10799                    } else {
10800                        break;
10801                    }
10802                }
10803            }
10804        }
10805
10806        self.fold_ranges(fold_ranges, true, cx);
10807    }
10808
10809    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10810        let buffer_row = fold_at.buffer_row;
10811        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10812
10813        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10814            let autoscroll = self
10815                .selections
10816                .all::<Point>(cx)
10817                .iter()
10818                .any(|selection| fold_range.overlaps(&selection.range()));
10819
10820            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10821        }
10822    }
10823
10824    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10825        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10826        let buffer = &display_map.buffer_snapshot;
10827        let selections = self.selections.all::<Point>(cx);
10828        let ranges = selections
10829            .iter()
10830            .map(|s| {
10831                let range = s.display_range(&display_map).sorted();
10832                let mut start = range.start.to_point(&display_map);
10833                let mut end = range.end.to_point(&display_map);
10834                start.column = 0;
10835                end.column = buffer.line_len(MultiBufferRow(end.row));
10836                start..end
10837            })
10838            .collect::<Vec<_>>();
10839
10840        self.unfold_ranges(ranges, true, true, cx);
10841    }
10842
10843    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10844        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10845        let selections = self.selections.all::<Point>(cx);
10846        let ranges = selections
10847            .iter()
10848            .map(|s| {
10849                let mut range = s.display_range(&display_map).sorted();
10850                *range.start.column_mut() = 0;
10851                *range.end.column_mut() = display_map.line_len(range.end.row());
10852                let start = range.start.to_point(&display_map);
10853                let end = range.end.to_point(&display_map);
10854                start..end
10855            })
10856            .collect::<Vec<_>>();
10857
10858        self.unfold_ranges(ranges, true, true, cx);
10859    }
10860
10861    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10862        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10863
10864        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10865            ..Point::new(
10866                unfold_at.buffer_row.0,
10867                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10868            );
10869
10870        let autoscroll = self
10871            .selections
10872            .all::<Point>(cx)
10873            .iter()
10874            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10875
10876        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10877    }
10878
10879    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10880        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10881        self.unfold_ranges(
10882            [Point::zero()..display_map.max_point().to_point(&display_map)],
10883            true,
10884            true,
10885            cx,
10886        );
10887    }
10888
10889    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10890        let selections = self.selections.all::<Point>(cx);
10891        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10892        let line_mode = self.selections.line_mode;
10893        let ranges = selections.into_iter().map(|s| {
10894            if line_mode {
10895                let start = Point::new(s.start.row, 0);
10896                let end = Point::new(
10897                    s.end.row,
10898                    display_map
10899                        .buffer_snapshot
10900                        .line_len(MultiBufferRow(s.end.row)),
10901                );
10902                (start..end, display_map.fold_placeholder.clone())
10903            } else {
10904                (s.start..s.end, display_map.fold_placeholder.clone())
10905            }
10906        });
10907        self.fold_ranges(ranges, true, cx);
10908    }
10909
10910    pub fn fold_ranges<T: ToOffset + Clone>(
10911        &mut self,
10912        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10913        auto_scroll: bool,
10914        cx: &mut ViewContext<Self>,
10915    ) {
10916        let mut fold_ranges = Vec::new();
10917        let mut buffers_affected = HashMap::default();
10918        let multi_buffer = self.buffer().read(cx);
10919        for (fold_range, fold_text) in ranges {
10920            if let Some((_, buffer, _)) =
10921                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10922            {
10923                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10924            };
10925            fold_ranges.push((fold_range, fold_text));
10926        }
10927
10928        let mut ranges = fold_ranges.into_iter().peekable();
10929        if ranges.peek().is_some() {
10930            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10931
10932            if auto_scroll {
10933                self.request_autoscroll(Autoscroll::fit(), cx);
10934            }
10935
10936            for buffer in buffers_affected.into_values() {
10937                self.sync_expanded_diff_hunks(buffer, cx);
10938            }
10939
10940            cx.notify();
10941
10942            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10943                // Clear diagnostics block when folding a range that contains it.
10944                let snapshot = self.snapshot(cx);
10945                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10946                    drop(snapshot);
10947                    self.active_diagnostics = Some(active_diagnostics);
10948                    self.dismiss_diagnostics(cx);
10949                } else {
10950                    self.active_diagnostics = Some(active_diagnostics);
10951                }
10952            }
10953
10954            self.scrollbar_marker_state.dirty = true;
10955        }
10956    }
10957
10958    pub fn unfold_ranges<T: ToOffset + Clone>(
10959        &mut self,
10960        ranges: impl IntoIterator<Item = Range<T>>,
10961        inclusive: bool,
10962        auto_scroll: bool,
10963        cx: &mut ViewContext<Self>,
10964    ) {
10965        let mut unfold_ranges = Vec::new();
10966        let mut buffers_affected = HashMap::default();
10967        let multi_buffer = self.buffer().read(cx);
10968        for range in ranges {
10969            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10970                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10971            };
10972            unfold_ranges.push(range);
10973        }
10974
10975        let mut ranges = unfold_ranges.into_iter().peekable();
10976        if ranges.peek().is_some() {
10977            self.display_map
10978                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10979            if auto_scroll {
10980                self.request_autoscroll(Autoscroll::fit(), cx);
10981            }
10982
10983            for buffer in buffers_affected.into_values() {
10984                self.sync_expanded_diff_hunks(buffer, cx);
10985            }
10986
10987            cx.notify();
10988            self.scrollbar_marker_state.dirty = true;
10989            self.active_indent_guides_state.dirty = true;
10990        }
10991    }
10992
10993    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10994        self.display_map.read(cx).fold_placeholder.clone()
10995    }
10996
10997    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10998        if hovered != self.gutter_hovered {
10999            self.gutter_hovered = hovered;
11000            cx.notify();
11001        }
11002    }
11003
11004    pub fn insert_blocks(
11005        &mut self,
11006        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11007        autoscroll: Option<Autoscroll>,
11008        cx: &mut ViewContext<Self>,
11009    ) -> Vec<CustomBlockId> {
11010        let blocks = self
11011            .display_map
11012            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11013        if let Some(autoscroll) = autoscroll {
11014            self.request_autoscroll(autoscroll, cx);
11015        }
11016        cx.notify();
11017        blocks
11018    }
11019
11020    pub fn resize_blocks(
11021        &mut self,
11022        heights: HashMap<CustomBlockId, u32>,
11023        autoscroll: Option<Autoscroll>,
11024        cx: &mut ViewContext<Self>,
11025    ) {
11026        self.display_map
11027            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11028        if let Some(autoscroll) = autoscroll {
11029            self.request_autoscroll(autoscroll, cx);
11030        }
11031        cx.notify();
11032    }
11033
11034    pub fn replace_blocks(
11035        &mut self,
11036        renderers: HashMap<CustomBlockId, RenderBlock>,
11037        autoscroll: Option<Autoscroll>,
11038        cx: &mut ViewContext<Self>,
11039    ) {
11040        self.display_map
11041            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11042        if let Some(autoscroll) = autoscroll {
11043            self.request_autoscroll(autoscroll, cx);
11044        }
11045        cx.notify();
11046    }
11047
11048    pub fn remove_blocks(
11049        &mut self,
11050        block_ids: HashSet<CustomBlockId>,
11051        autoscroll: Option<Autoscroll>,
11052        cx: &mut ViewContext<Self>,
11053    ) {
11054        self.display_map.update(cx, |display_map, cx| {
11055            display_map.remove_blocks(block_ids, cx)
11056        });
11057        if let Some(autoscroll) = autoscroll {
11058            self.request_autoscroll(autoscroll, cx);
11059        }
11060        cx.notify();
11061    }
11062
11063    pub fn row_for_block(
11064        &self,
11065        block_id: CustomBlockId,
11066        cx: &mut ViewContext<Self>,
11067    ) -> Option<DisplayRow> {
11068        self.display_map
11069            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11070    }
11071
11072    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11073        self.focused_block = Some(focused_block);
11074    }
11075
11076    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11077        self.focused_block.take()
11078    }
11079
11080    pub fn insert_creases(
11081        &mut self,
11082        creases: impl IntoIterator<Item = Crease>,
11083        cx: &mut ViewContext<Self>,
11084    ) -> Vec<CreaseId> {
11085        self.display_map
11086            .update(cx, |map, cx| map.insert_creases(creases, cx))
11087    }
11088
11089    pub fn remove_creases(
11090        &mut self,
11091        ids: impl IntoIterator<Item = CreaseId>,
11092        cx: &mut ViewContext<Self>,
11093    ) {
11094        self.display_map
11095            .update(cx, |map, cx| map.remove_creases(ids, cx));
11096    }
11097
11098    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11099        self.display_map
11100            .update(cx, |map, cx| map.snapshot(cx))
11101            .longest_row()
11102    }
11103
11104    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11105        self.display_map
11106            .update(cx, |map, cx| map.snapshot(cx))
11107            .max_point()
11108    }
11109
11110    pub fn text(&self, cx: &AppContext) -> String {
11111        self.buffer.read(cx).read(cx).text()
11112    }
11113
11114    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11115        let text = self.text(cx);
11116        let text = text.trim();
11117
11118        if text.is_empty() {
11119            return None;
11120        }
11121
11122        Some(text.to_string())
11123    }
11124
11125    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11126        self.transact(cx, |this, cx| {
11127            this.buffer
11128                .read(cx)
11129                .as_singleton()
11130                .expect("you can only call set_text on editors for singleton buffers")
11131                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11132        });
11133    }
11134
11135    pub fn display_text(&self, cx: &mut AppContext) -> String {
11136        self.display_map
11137            .update(cx, |map, cx| map.snapshot(cx))
11138            .text()
11139    }
11140
11141    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11142        let mut wrap_guides = smallvec::smallvec![];
11143
11144        if self.show_wrap_guides == Some(false) {
11145            return wrap_guides;
11146        }
11147
11148        let settings = self.buffer.read(cx).settings_at(0, cx);
11149        if settings.show_wrap_guides {
11150            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11151                wrap_guides.push((soft_wrap as usize, true));
11152            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11153                wrap_guides.push((soft_wrap as usize, true));
11154            }
11155            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11156        }
11157
11158        wrap_guides
11159    }
11160
11161    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11162        let settings = self.buffer.read(cx).settings_at(0, cx);
11163        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11164        match mode {
11165            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11166                SoftWrap::None
11167            }
11168            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11169            language_settings::SoftWrap::PreferredLineLength => {
11170                SoftWrap::Column(settings.preferred_line_length)
11171            }
11172            language_settings::SoftWrap::Bounded => {
11173                SoftWrap::Bounded(settings.preferred_line_length)
11174            }
11175        }
11176    }
11177
11178    pub fn set_soft_wrap_mode(
11179        &mut self,
11180        mode: language_settings::SoftWrap,
11181        cx: &mut ViewContext<Self>,
11182    ) {
11183        self.soft_wrap_mode_override = Some(mode);
11184        cx.notify();
11185    }
11186
11187    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11188        let rem_size = cx.rem_size();
11189        self.display_map.update(cx, |map, cx| {
11190            map.set_font(
11191                style.text.font(),
11192                style.text.font_size.to_pixels(rem_size),
11193                cx,
11194            )
11195        });
11196        self.style = Some(style);
11197    }
11198
11199    pub fn style(&self) -> Option<&EditorStyle> {
11200        self.style.as_ref()
11201    }
11202
11203    // Called by the element. This method is not designed to be called outside of the editor
11204    // element's layout code because it does not notify when rewrapping is computed synchronously.
11205    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11206        self.display_map
11207            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11208    }
11209
11210    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11211        if self.soft_wrap_mode_override.is_some() {
11212            self.soft_wrap_mode_override.take();
11213        } else {
11214            let soft_wrap = match self.soft_wrap_mode(cx) {
11215                SoftWrap::GitDiff => return,
11216                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11217                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11218                    language_settings::SoftWrap::None
11219                }
11220            };
11221            self.soft_wrap_mode_override = Some(soft_wrap);
11222        }
11223        cx.notify();
11224    }
11225
11226    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11227        let Some(workspace) = self.workspace() else {
11228            return;
11229        };
11230        let fs = workspace.read(cx).app_state().fs.clone();
11231        let current_show = TabBarSettings::get_global(cx).show;
11232        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11233            setting.show = Some(!current_show);
11234        });
11235    }
11236
11237    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11238        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11239            self.buffer
11240                .read(cx)
11241                .settings_at(0, cx)
11242                .indent_guides
11243                .enabled
11244        });
11245        self.show_indent_guides = Some(!currently_enabled);
11246        cx.notify();
11247    }
11248
11249    fn should_show_indent_guides(&self) -> Option<bool> {
11250        self.show_indent_guides
11251    }
11252
11253    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11254        let mut editor_settings = EditorSettings::get_global(cx).clone();
11255        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11256        EditorSettings::override_global(editor_settings, cx);
11257    }
11258
11259    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11260        self.use_relative_line_numbers
11261            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11262    }
11263
11264    pub fn toggle_relative_line_numbers(
11265        &mut self,
11266        _: &ToggleRelativeLineNumbers,
11267        cx: &mut ViewContext<Self>,
11268    ) {
11269        let is_relative = self.should_use_relative_line_numbers(cx);
11270        self.set_relative_line_number(Some(!is_relative), cx)
11271    }
11272
11273    pub fn set_relative_line_number(
11274        &mut self,
11275        is_relative: Option<bool>,
11276        cx: &mut ViewContext<Self>,
11277    ) {
11278        self.use_relative_line_numbers = is_relative;
11279        cx.notify();
11280    }
11281
11282    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11283        self.show_gutter = show_gutter;
11284        cx.notify();
11285    }
11286
11287    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11288        self.show_line_numbers = Some(show_line_numbers);
11289        cx.notify();
11290    }
11291
11292    pub fn set_show_git_diff_gutter(
11293        &mut self,
11294        show_git_diff_gutter: bool,
11295        cx: &mut ViewContext<Self>,
11296    ) {
11297        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11298        cx.notify();
11299    }
11300
11301    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11302        self.show_code_actions = Some(show_code_actions);
11303        cx.notify();
11304    }
11305
11306    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11307        self.show_runnables = Some(show_runnables);
11308        cx.notify();
11309    }
11310
11311    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11312        if self.display_map.read(cx).masked != masked {
11313            self.display_map.update(cx, |map, _| map.masked = masked);
11314        }
11315        cx.notify()
11316    }
11317
11318    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11319        self.show_wrap_guides = Some(show_wrap_guides);
11320        cx.notify();
11321    }
11322
11323    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11324        self.show_indent_guides = Some(show_indent_guides);
11325        cx.notify();
11326    }
11327
11328    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11329        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11330            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11331                if let Some(dir) = file.abs_path(cx).parent() {
11332                    return Some(dir.to_owned());
11333                }
11334            }
11335
11336            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11337                return Some(project_path.path.to_path_buf());
11338            }
11339        }
11340
11341        None
11342    }
11343
11344    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11345        self.active_excerpt(cx)?
11346            .1
11347            .read(cx)
11348            .file()
11349            .and_then(|f| f.as_local())
11350    }
11351
11352    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11353        if let Some(target) = self.target_file(cx) {
11354            cx.reveal_path(&target.abs_path(cx));
11355        }
11356    }
11357
11358    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11359        if let Some(file) = self.target_file(cx) {
11360            if let Some(path) = file.abs_path(cx).to_str() {
11361                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11362            }
11363        }
11364    }
11365
11366    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11367        if let Some(file) = self.target_file(cx) {
11368            if let Some(path) = file.path().to_str() {
11369                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11370            }
11371        }
11372    }
11373
11374    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11375        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11376
11377        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11378            self.start_git_blame(true, cx);
11379        }
11380
11381        cx.notify();
11382    }
11383
11384    pub fn toggle_git_blame_inline(
11385        &mut self,
11386        _: &ToggleGitBlameInline,
11387        cx: &mut ViewContext<Self>,
11388    ) {
11389        self.toggle_git_blame_inline_internal(true, cx);
11390        cx.notify();
11391    }
11392
11393    pub fn git_blame_inline_enabled(&self) -> bool {
11394        self.git_blame_inline_enabled
11395    }
11396
11397    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11398        self.show_selection_menu = self
11399            .show_selection_menu
11400            .map(|show_selections_menu| !show_selections_menu)
11401            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11402
11403        cx.notify();
11404    }
11405
11406    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11407        self.show_selection_menu
11408            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11409    }
11410
11411    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11412        if let Some(project) = self.project.as_ref() {
11413            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11414                return;
11415            };
11416
11417            if buffer.read(cx).file().is_none() {
11418                return;
11419            }
11420
11421            let focused = self.focus_handle(cx).contains_focused(cx);
11422
11423            let project = project.clone();
11424            let blame =
11425                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11426            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11427            self.blame = Some(blame);
11428        }
11429    }
11430
11431    fn toggle_git_blame_inline_internal(
11432        &mut self,
11433        user_triggered: bool,
11434        cx: &mut ViewContext<Self>,
11435    ) {
11436        if self.git_blame_inline_enabled {
11437            self.git_blame_inline_enabled = false;
11438            self.show_git_blame_inline = false;
11439            self.show_git_blame_inline_delay_task.take();
11440        } else {
11441            self.git_blame_inline_enabled = true;
11442            self.start_git_blame_inline(user_triggered, cx);
11443        }
11444
11445        cx.notify();
11446    }
11447
11448    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11449        self.start_git_blame(user_triggered, cx);
11450
11451        if ProjectSettings::get_global(cx)
11452            .git
11453            .inline_blame_delay()
11454            .is_some()
11455        {
11456            self.start_inline_blame_timer(cx);
11457        } else {
11458            self.show_git_blame_inline = true
11459        }
11460    }
11461
11462    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11463        self.blame.as_ref()
11464    }
11465
11466    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11467        self.show_git_blame_gutter && self.has_blame_entries(cx)
11468    }
11469
11470    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11471        self.show_git_blame_inline
11472            && self.focus_handle.is_focused(cx)
11473            && !self.newest_selection_head_on_empty_line(cx)
11474            && self.has_blame_entries(cx)
11475    }
11476
11477    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11478        self.blame()
11479            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11480    }
11481
11482    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11483        let cursor_anchor = self.selections.newest_anchor().head();
11484
11485        let snapshot = self.buffer.read(cx).snapshot(cx);
11486        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11487
11488        snapshot.line_len(buffer_row) == 0
11489    }
11490
11491    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11492        let (path, selection, repo) = maybe!({
11493            let project_handle = self.project.as_ref()?.clone();
11494            let project = project_handle.read(cx);
11495
11496            let selection = self.selections.newest::<Point>(cx);
11497            let selection_range = selection.range();
11498
11499            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11500                (buffer, selection_range.start.row..selection_range.end.row)
11501            } else {
11502                let buffer_ranges = self
11503                    .buffer()
11504                    .read(cx)
11505                    .range_to_buffer_ranges(selection_range, cx);
11506
11507                let (buffer, range, _) = if selection.reversed {
11508                    buffer_ranges.first()
11509                } else {
11510                    buffer_ranges.last()
11511                }?;
11512
11513                let snapshot = buffer.read(cx).snapshot();
11514                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11515                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11516                (buffer.clone(), selection)
11517            };
11518
11519            let path = buffer
11520                .read(cx)
11521                .file()?
11522                .as_local()?
11523                .path()
11524                .to_str()?
11525                .to_string();
11526            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11527            Some((path, selection, repo))
11528        })
11529        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11530
11531        const REMOTE_NAME: &str = "origin";
11532        let origin_url = repo
11533            .remote_url(REMOTE_NAME)
11534            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11535        let sha = repo
11536            .head_sha()
11537            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11538
11539        let (provider, remote) =
11540            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11541                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11542
11543        Ok(provider.build_permalink(
11544            remote,
11545            BuildPermalinkParams {
11546                sha: &sha,
11547                path: &path,
11548                selection: Some(selection),
11549            },
11550        ))
11551    }
11552
11553    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11554        let permalink = self.get_permalink_to_line(cx);
11555
11556        match permalink {
11557            Ok(permalink) => {
11558                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11559            }
11560            Err(err) => {
11561                let message = format!("Failed to copy permalink: {err}");
11562
11563                Err::<(), anyhow::Error>(err).log_err();
11564
11565                if let Some(workspace) = self.workspace() {
11566                    workspace.update(cx, |workspace, cx| {
11567                        struct CopyPermalinkToLine;
11568
11569                        workspace.show_toast(
11570                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11571                            cx,
11572                        )
11573                    })
11574                }
11575            }
11576        }
11577    }
11578
11579    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11580        if let Some(file) = self.target_file(cx) {
11581            if let Some(path) = file.path().to_str() {
11582                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11583                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11584            }
11585        }
11586    }
11587
11588    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11589        let permalink = self.get_permalink_to_line(cx);
11590
11591        match permalink {
11592            Ok(permalink) => {
11593                cx.open_url(permalink.as_ref());
11594            }
11595            Err(err) => {
11596                let message = format!("Failed to open permalink: {err}");
11597
11598                Err::<(), anyhow::Error>(err).log_err();
11599
11600                if let Some(workspace) = self.workspace() {
11601                    workspace.update(cx, |workspace, cx| {
11602                        struct OpenPermalinkToLine;
11603
11604                        workspace.show_toast(
11605                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11606                            cx,
11607                        )
11608                    })
11609                }
11610            }
11611        }
11612    }
11613
11614    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11615    /// last highlight added will be used.
11616    ///
11617    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11618    pub fn highlight_rows<T: 'static>(
11619        &mut self,
11620        range: Range<Anchor>,
11621        color: Hsla,
11622        should_autoscroll: bool,
11623        cx: &mut ViewContext<Self>,
11624    ) {
11625        let snapshot = self.buffer().read(cx).snapshot(cx);
11626        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11627        let ix = row_highlights.binary_search_by(|highlight| {
11628            Ordering::Equal
11629                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11630                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11631        });
11632
11633        if let Err(mut ix) = ix {
11634            let index = post_inc(&mut self.highlight_order);
11635
11636            // If this range intersects with the preceding highlight, then merge it with
11637            // the preceding highlight. Otherwise insert a new highlight.
11638            let mut merged = false;
11639            if ix > 0 {
11640                let prev_highlight = &mut row_highlights[ix - 1];
11641                if prev_highlight
11642                    .range
11643                    .end
11644                    .cmp(&range.start, &snapshot)
11645                    .is_ge()
11646                {
11647                    ix -= 1;
11648                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11649                        prev_highlight.range.end = range.end;
11650                    }
11651                    merged = true;
11652                    prev_highlight.index = index;
11653                    prev_highlight.color = color;
11654                    prev_highlight.should_autoscroll = should_autoscroll;
11655                }
11656            }
11657
11658            if !merged {
11659                row_highlights.insert(
11660                    ix,
11661                    RowHighlight {
11662                        range: range.clone(),
11663                        index,
11664                        color,
11665                        should_autoscroll,
11666                    },
11667                );
11668            }
11669
11670            // If any of the following highlights intersect with this one, merge them.
11671            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11672                let highlight = &row_highlights[ix];
11673                if next_highlight
11674                    .range
11675                    .start
11676                    .cmp(&highlight.range.end, &snapshot)
11677                    .is_le()
11678                {
11679                    if next_highlight
11680                        .range
11681                        .end
11682                        .cmp(&highlight.range.end, &snapshot)
11683                        .is_gt()
11684                    {
11685                        row_highlights[ix].range.end = next_highlight.range.end;
11686                    }
11687                    row_highlights.remove(ix + 1);
11688                } else {
11689                    break;
11690                }
11691            }
11692        }
11693    }
11694
11695    /// Remove any highlighted row ranges of the given type that intersect the
11696    /// given ranges.
11697    pub fn remove_highlighted_rows<T: 'static>(
11698        &mut self,
11699        ranges_to_remove: Vec<Range<Anchor>>,
11700        cx: &mut ViewContext<Self>,
11701    ) {
11702        let snapshot = self.buffer().read(cx).snapshot(cx);
11703        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11704        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11705        row_highlights.retain(|highlight| {
11706            while let Some(range_to_remove) = ranges_to_remove.peek() {
11707                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11708                    Ordering::Less | Ordering::Equal => {
11709                        ranges_to_remove.next();
11710                    }
11711                    Ordering::Greater => {
11712                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11713                            Ordering::Less | Ordering::Equal => {
11714                                return false;
11715                            }
11716                            Ordering::Greater => break,
11717                        }
11718                    }
11719                }
11720            }
11721
11722            true
11723        })
11724    }
11725
11726    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11727    pub fn clear_row_highlights<T: 'static>(&mut self) {
11728        self.highlighted_rows.remove(&TypeId::of::<T>());
11729    }
11730
11731    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11732    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11733        self.highlighted_rows
11734            .get(&TypeId::of::<T>())
11735            .map_or(&[] as &[_], |vec| vec.as_slice())
11736            .iter()
11737            .map(|highlight| (highlight.range.clone(), highlight.color))
11738    }
11739
11740    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11741    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11742    /// Allows to ignore certain kinds of highlights.
11743    pub fn highlighted_display_rows(
11744        &mut self,
11745        cx: &mut WindowContext,
11746    ) -> BTreeMap<DisplayRow, Hsla> {
11747        let snapshot = self.snapshot(cx);
11748        let mut used_highlight_orders = HashMap::default();
11749        self.highlighted_rows
11750            .iter()
11751            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11752            .fold(
11753                BTreeMap::<DisplayRow, Hsla>::new(),
11754                |mut unique_rows, highlight| {
11755                    let start = highlight.range.start.to_display_point(&snapshot);
11756                    let end = highlight.range.end.to_display_point(&snapshot);
11757                    let start_row = start.row().0;
11758                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11759                        && end.column() == 0
11760                    {
11761                        end.row().0.saturating_sub(1)
11762                    } else {
11763                        end.row().0
11764                    };
11765                    for row in start_row..=end_row {
11766                        let used_index =
11767                            used_highlight_orders.entry(row).or_insert(highlight.index);
11768                        if highlight.index >= *used_index {
11769                            *used_index = highlight.index;
11770                            unique_rows.insert(DisplayRow(row), highlight.color);
11771                        }
11772                    }
11773                    unique_rows
11774                },
11775            )
11776    }
11777
11778    pub fn highlighted_display_row_for_autoscroll(
11779        &self,
11780        snapshot: &DisplaySnapshot,
11781    ) -> Option<DisplayRow> {
11782        self.highlighted_rows
11783            .values()
11784            .flat_map(|highlighted_rows| highlighted_rows.iter())
11785            .filter_map(|highlight| {
11786                if highlight.should_autoscroll {
11787                    Some(highlight.range.start.to_display_point(snapshot).row())
11788                } else {
11789                    None
11790                }
11791            })
11792            .min()
11793    }
11794
11795    pub fn set_search_within_ranges(
11796        &mut self,
11797        ranges: &[Range<Anchor>],
11798        cx: &mut ViewContext<Self>,
11799    ) {
11800        self.highlight_background::<SearchWithinRange>(
11801            ranges,
11802            |colors| colors.editor_document_highlight_read_background,
11803            cx,
11804        )
11805    }
11806
11807    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11808        self.breadcrumb_header = Some(new_header);
11809    }
11810
11811    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11812        self.clear_background_highlights::<SearchWithinRange>(cx);
11813    }
11814
11815    pub fn highlight_background<T: 'static>(
11816        &mut self,
11817        ranges: &[Range<Anchor>],
11818        color_fetcher: fn(&ThemeColors) -> Hsla,
11819        cx: &mut ViewContext<Self>,
11820    ) {
11821        self.background_highlights
11822            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11823        self.scrollbar_marker_state.dirty = true;
11824        cx.notify();
11825    }
11826
11827    pub fn clear_background_highlights<T: 'static>(
11828        &mut self,
11829        cx: &mut ViewContext<Self>,
11830    ) -> Option<BackgroundHighlight> {
11831        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11832        if !text_highlights.1.is_empty() {
11833            self.scrollbar_marker_state.dirty = true;
11834            cx.notify();
11835        }
11836        Some(text_highlights)
11837    }
11838
11839    pub fn highlight_gutter<T: 'static>(
11840        &mut self,
11841        ranges: &[Range<Anchor>],
11842        color_fetcher: fn(&AppContext) -> Hsla,
11843        cx: &mut ViewContext<Self>,
11844    ) {
11845        self.gutter_highlights
11846            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11847        cx.notify();
11848    }
11849
11850    pub fn clear_gutter_highlights<T: 'static>(
11851        &mut self,
11852        cx: &mut ViewContext<Self>,
11853    ) -> Option<GutterHighlight> {
11854        cx.notify();
11855        self.gutter_highlights.remove(&TypeId::of::<T>())
11856    }
11857
11858    #[cfg(feature = "test-support")]
11859    pub fn all_text_background_highlights(
11860        &mut self,
11861        cx: &mut ViewContext<Self>,
11862    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11863        let snapshot = self.snapshot(cx);
11864        let buffer = &snapshot.buffer_snapshot;
11865        let start = buffer.anchor_before(0);
11866        let end = buffer.anchor_after(buffer.len());
11867        let theme = cx.theme().colors();
11868        self.background_highlights_in_range(start..end, &snapshot, theme)
11869    }
11870
11871    #[cfg(feature = "test-support")]
11872    pub fn search_background_highlights(
11873        &mut self,
11874        cx: &mut ViewContext<Self>,
11875    ) -> Vec<Range<Point>> {
11876        let snapshot = self.buffer().read(cx).snapshot(cx);
11877
11878        let highlights = self
11879            .background_highlights
11880            .get(&TypeId::of::<items::BufferSearchHighlights>());
11881
11882        if let Some((_color, ranges)) = highlights {
11883            ranges
11884                .iter()
11885                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11886                .collect_vec()
11887        } else {
11888            vec![]
11889        }
11890    }
11891
11892    fn document_highlights_for_position<'a>(
11893        &'a self,
11894        position: Anchor,
11895        buffer: &'a MultiBufferSnapshot,
11896    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11897        let read_highlights = self
11898            .background_highlights
11899            .get(&TypeId::of::<DocumentHighlightRead>())
11900            .map(|h| &h.1);
11901        let write_highlights = self
11902            .background_highlights
11903            .get(&TypeId::of::<DocumentHighlightWrite>())
11904            .map(|h| &h.1);
11905        let left_position = position.bias_left(buffer);
11906        let right_position = position.bias_right(buffer);
11907        read_highlights
11908            .into_iter()
11909            .chain(write_highlights)
11910            .flat_map(move |ranges| {
11911                let start_ix = match ranges.binary_search_by(|probe| {
11912                    let cmp = probe.end.cmp(&left_position, buffer);
11913                    if cmp.is_ge() {
11914                        Ordering::Greater
11915                    } else {
11916                        Ordering::Less
11917                    }
11918                }) {
11919                    Ok(i) | Err(i) => i,
11920                };
11921
11922                ranges[start_ix..]
11923                    .iter()
11924                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11925            })
11926    }
11927
11928    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11929        self.background_highlights
11930            .get(&TypeId::of::<T>())
11931            .map_or(false, |(_, highlights)| !highlights.is_empty())
11932    }
11933
11934    pub fn background_highlights_in_range(
11935        &self,
11936        search_range: Range<Anchor>,
11937        display_snapshot: &DisplaySnapshot,
11938        theme: &ThemeColors,
11939    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11940        let mut results = Vec::new();
11941        for (color_fetcher, ranges) in self.background_highlights.values() {
11942            let color = color_fetcher(theme);
11943            let start_ix = match ranges.binary_search_by(|probe| {
11944                let cmp = probe
11945                    .end
11946                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11947                if cmp.is_gt() {
11948                    Ordering::Greater
11949                } else {
11950                    Ordering::Less
11951                }
11952            }) {
11953                Ok(i) | Err(i) => i,
11954            };
11955            for range in &ranges[start_ix..] {
11956                if range
11957                    .start
11958                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11959                    .is_ge()
11960                {
11961                    break;
11962                }
11963
11964                let start = range.start.to_display_point(display_snapshot);
11965                let end = range.end.to_display_point(display_snapshot);
11966                results.push((start..end, color))
11967            }
11968        }
11969        results
11970    }
11971
11972    pub fn background_highlight_row_ranges<T: 'static>(
11973        &self,
11974        search_range: Range<Anchor>,
11975        display_snapshot: &DisplaySnapshot,
11976        count: usize,
11977    ) -> Vec<RangeInclusive<DisplayPoint>> {
11978        let mut results = Vec::new();
11979        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11980            return vec![];
11981        };
11982
11983        let start_ix = match ranges.binary_search_by(|probe| {
11984            let cmp = probe
11985                .end
11986                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11987            if cmp.is_gt() {
11988                Ordering::Greater
11989            } else {
11990                Ordering::Less
11991            }
11992        }) {
11993            Ok(i) | Err(i) => i,
11994        };
11995        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11996            if let (Some(start_display), Some(end_display)) = (start, end) {
11997                results.push(
11998                    start_display.to_display_point(display_snapshot)
11999                        ..=end_display.to_display_point(display_snapshot),
12000                );
12001            }
12002        };
12003        let mut start_row: Option<Point> = None;
12004        let mut end_row: Option<Point> = None;
12005        if ranges.len() > count {
12006            return Vec::new();
12007        }
12008        for range in &ranges[start_ix..] {
12009            if range
12010                .start
12011                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12012                .is_ge()
12013            {
12014                break;
12015            }
12016            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12017            if let Some(current_row) = &end_row {
12018                if end.row == current_row.row {
12019                    continue;
12020                }
12021            }
12022            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12023            if start_row.is_none() {
12024                assert_eq!(end_row, None);
12025                start_row = Some(start);
12026                end_row = Some(end);
12027                continue;
12028            }
12029            if let Some(current_end) = end_row.as_mut() {
12030                if start.row > current_end.row + 1 {
12031                    push_region(start_row, end_row);
12032                    start_row = Some(start);
12033                    end_row = Some(end);
12034                } else {
12035                    // Merge two hunks.
12036                    *current_end = end;
12037                }
12038            } else {
12039                unreachable!();
12040            }
12041        }
12042        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12043        push_region(start_row, end_row);
12044        results
12045    }
12046
12047    pub fn gutter_highlights_in_range(
12048        &self,
12049        search_range: Range<Anchor>,
12050        display_snapshot: &DisplaySnapshot,
12051        cx: &AppContext,
12052    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12053        let mut results = Vec::new();
12054        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12055            let color = color_fetcher(cx);
12056            let start_ix = match ranges.binary_search_by(|probe| {
12057                let cmp = probe
12058                    .end
12059                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12060                if cmp.is_gt() {
12061                    Ordering::Greater
12062                } else {
12063                    Ordering::Less
12064                }
12065            }) {
12066                Ok(i) | Err(i) => i,
12067            };
12068            for range in &ranges[start_ix..] {
12069                if range
12070                    .start
12071                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12072                    .is_ge()
12073                {
12074                    break;
12075                }
12076
12077                let start = range.start.to_display_point(display_snapshot);
12078                let end = range.end.to_display_point(display_snapshot);
12079                results.push((start..end, color))
12080            }
12081        }
12082        results
12083    }
12084
12085    /// Get the text ranges corresponding to the redaction query
12086    pub fn redacted_ranges(
12087        &self,
12088        search_range: Range<Anchor>,
12089        display_snapshot: &DisplaySnapshot,
12090        cx: &WindowContext,
12091    ) -> Vec<Range<DisplayPoint>> {
12092        display_snapshot
12093            .buffer_snapshot
12094            .redacted_ranges(search_range, |file| {
12095                if let Some(file) = file {
12096                    file.is_private()
12097                        && EditorSettings::get(
12098                            Some(SettingsLocation {
12099                                worktree_id: file.worktree_id(cx),
12100                                path: file.path().as_ref(),
12101                            }),
12102                            cx,
12103                        )
12104                        .redact_private_values
12105                } else {
12106                    false
12107                }
12108            })
12109            .map(|range| {
12110                range.start.to_display_point(display_snapshot)
12111                    ..range.end.to_display_point(display_snapshot)
12112            })
12113            .collect()
12114    }
12115
12116    pub fn highlight_text<T: 'static>(
12117        &mut self,
12118        ranges: Vec<Range<Anchor>>,
12119        style: HighlightStyle,
12120        cx: &mut ViewContext<Self>,
12121    ) {
12122        self.display_map.update(cx, |map, _| {
12123            map.highlight_text(TypeId::of::<T>(), ranges, style)
12124        });
12125        cx.notify();
12126    }
12127
12128    pub(crate) fn highlight_inlays<T: 'static>(
12129        &mut self,
12130        highlights: Vec<InlayHighlight>,
12131        style: HighlightStyle,
12132        cx: &mut ViewContext<Self>,
12133    ) {
12134        self.display_map.update(cx, |map, _| {
12135            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12136        });
12137        cx.notify();
12138    }
12139
12140    pub fn text_highlights<'a, T: 'static>(
12141        &'a self,
12142        cx: &'a AppContext,
12143    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12144        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12145    }
12146
12147    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12148        let cleared = self
12149            .display_map
12150            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12151        if cleared {
12152            cx.notify();
12153        }
12154    }
12155
12156    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12157        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12158            && self.focus_handle.is_focused(cx)
12159    }
12160
12161    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12162        self.show_cursor_when_unfocused = is_enabled;
12163        cx.notify();
12164    }
12165
12166    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12167        cx.notify();
12168    }
12169
12170    fn on_buffer_event(
12171        &mut self,
12172        multibuffer: Model<MultiBuffer>,
12173        event: &multi_buffer::Event,
12174        cx: &mut ViewContext<Self>,
12175    ) {
12176        match event {
12177            multi_buffer::Event::Edited {
12178                singleton_buffer_edited,
12179            } => {
12180                self.scrollbar_marker_state.dirty = true;
12181                self.active_indent_guides_state.dirty = true;
12182                self.refresh_active_diagnostics(cx);
12183                self.refresh_code_actions(cx);
12184                if self.has_active_inline_completion(cx) {
12185                    self.update_visible_inline_completion(cx);
12186                }
12187                cx.emit(EditorEvent::BufferEdited);
12188                cx.emit(SearchEvent::MatchesInvalidated);
12189                if *singleton_buffer_edited {
12190                    if let Some(project) = &self.project {
12191                        let project = project.read(cx);
12192                        #[allow(clippy::mutable_key_type)]
12193                        let languages_affected = multibuffer
12194                            .read(cx)
12195                            .all_buffers()
12196                            .into_iter()
12197                            .filter_map(|buffer| {
12198                                let buffer = buffer.read(cx);
12199                                let language = buffer.language()?;
12200                                if project.is_local()
12201                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12202                                {
12203                                    None
12204                                } else {
12205                                    Some(language)
12206                                }
12207                            })
12208                            .cloned()
12209                            .collect::<HashSet<_>>();
12210                        if !languages_affected.is_empty() {
12211                            self.refresh_inlay_hints(
12212                                InlayHintRefreshReason::BufferEdited(languages_affected),
12213                                cx,
12214                            );
12215                        }
12216                    }
12217                }
12218
12219                let Some(project) = &self.project else { return };
12220                let (telemetry, is_via_ssh) = {
12221                    let project = project.read(cx);
12222                    let telemetry = project.client().telemetry().clone();
12223                    let is_via_ssh = project.is_via_ssh();
12224                    (telemetry, is_via_ssh)
12225                };
12226                refresh_linked_ranges(self, cx);
12227                telemetry.log_edit_event("editor", is_via_ssh);
12228            }
12229            multi_buffer::Event::ExcerptsAdded {
12230                buffer,
12231                predecessor,
12232                excerpts,
12233            } => {
12234                self.tasks_update_task = Some(self.refresh_runnables(cx));
12235                cx.emit(EditorEvent::ExcerptsAdded {
12236                    buffer: buffer.clone(),
12237                    predecessor: *predecessor,
12238                    excerpts: excerpts.clone(),
12239                });
12240                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12241            }
12242            multi_buffer::Event::ExcerptsRemoved { ids } => {
12243                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12244                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12245            }
12246            multi_buffer::Event::ExcerptsEdited { ids } => {
12247                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12248            }
12249            multi_buffer::Event::ExcerptsExpanded { ids } => {
12250                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12251            }
12252            multi_buffer::Event::Reparsed(buffer_id) => {
12253                self.tasks_update_task = Some(self.refresh_runnables(cx));
12254
12255                cx.emit(EditorEvent::Reparsed(*buffer_id));
12256            }
12257            multi_buffer::Event::LanguageChanged(buffer_id) => {
12258                linked_editing_ranges::refresh_linked_ranges(self, cx);
12259                cx.emit(EditorEvent::Reparsed(*buffer_id));
12260                cx.notify();
12261            }
12262            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12263            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12264            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12265                cx.emit(EditorEvent::TitleChanged)
12266            }
12267            multi_buffer::Event::DiffBaseChanged => {
12268                self.scrollbar_marker_state.dirty = true;
12269                cx.emit(EditorEvent::DiffBaseChanged);
12270                cx.notify();
12271            }
12272            multi_buffer::Event::DiffUpdated { buffer } => {
12273                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12274                cx.notify();
12275            }
12276            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12277            multi_buffer::Event::DiagnosticsUpdated => {
12278                self.refresh_active_diagnostics(cx);
12279                self.scrollbar_marker_state.dirty = true;
12280                cx.notify();
12281            }
12282            _ => {}
12283        };
12284    }
12285
12286    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12287        cx.notify();
12288    }
12289
12290    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12291        self.tasks_update_task = Some(self.refresh_runnables(cx));
12292        self.refresh_inline_completion(true, false, cx);
12293        self.refresh_inlay_hints(
12294            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12295                self.selections.newest_anchor().head(),
12296                &self.buffer.read(cx).snapshot(cx),
12297                cx,
12298            )),
12299            cx,
12300        );
12301
12302        let old_cursor_shape = self.cursor_shape;
12303
12304        {
12305            let editor_settings = EditorSettings::get_global(cx);
12306            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12307            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12308            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12309        }
12310
12311        if old_cursor_shape != self.cursor_shape {
12312            cx.emit(EditorEvent::CursorShapeChanged);
12313        }
12314
12315        let project_settings = ProjectSettings::get_global(cx);
12316        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12317
12318        if self.mode == EditorMode::Full {
12319            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12320            if self.git_blame_inline_enabled != inline_blame_enabled {
12321                self.toggle_git_blame_inline_internal(false, cx);
12322            }
12323        }
12324
12325        cx.notify();
12326    }
12327
12328    pub fn set_searchable(&mut self, searchable: bool) {
12329        self.searchable = searchable;
12330    }
12331
12332    pub fn searchable(&self) -> bool {
12333        self.searchable
12334    }
12335
12336    fn open_proposed_changes_editor(
12337        &mut self,
12338        _: &OpenProposedChangesEditor,
12339        cx: &mut ViewContext<Self>,
12340    ) {
12341        let Some(workspace) = self.workspace() else {
12342            cx.propagate();
12343            return;
12344        };
12345
12346        let buffer = self.buffer.read(cx);
12347        let mut new_selections_by_buffer = HashMap::default();
12348        for selection in self.selections.all::<usize>(cx) {
12349            for (buffer, range, _) in
12350                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12351            {
12352                let mut range = range.to_point(buffer.read(cx));
12353                range.start.column = 0;
12354                range.end.column = buffer.read(cx).line_len(range.end.row);
12355                new_selections_by_buffer
12356                    .entry(buffer)
12357                    .or_insert(Vec::new())
12358                    .push(range)
12359            }
12360        }
12361
12362        let proposed_changes_buffers = new_selections_by_buffer
12363            .into_iter()
12364            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12365            .collect::<Vec<_>>();
12366        let proposed_changes_editor = cx.new_view(|cx| {
12367            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12368        });
12369
12370        cx.window_context().defer(move |cx| {
12371            workspace.update(cx, |workspace, cx| {
12372                workspace.active_pane().update(cx, |pane, cx| {
12373                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12374                });
12375            });
12376        });
12377    }
12378
12379    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12380        self.open_excerpts_common(true, cx)
12381    }
12382
12383    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12384        self.open_excerpts_common(false, cx)
12385    }
12386
12387    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12388        let buffer = self.buffer.read(cx);
12389        if buffer.is_singleton() {
12390            cx.propagate();
12391            return;
12392        }
12393
12394        let Some(workspace) = self.workspace() else {
12395            cx.propagate();
12396            return;
12397        };
12398
12399        let mut new_selections_by_buffer = HashMap::default();
12400        for selection in self.selections.all::<usize>(cx) {
12401            for (mut buffer_handle, mut range, _) in
12402                buffer.range_to_buffer_ranges(selection.range(), cx)
12403            {
12404                // When editing branch buffers, jump to the corresponding location
12405                // in their base buffer.
12406                let buffer = buffer_handle.read(cx);
12407                if let Some(base_buffer) = buffer.diff_base_buffer() {
12408                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12409                    buffer_handle = base_buffer;
12410                }
12411
12412                if selection.reversed {
12413                    mem::swap(&mut range.start, &mut range.end);
12414                }
12415                new_selections_by_buffer
12416                    .entry(buffer_handle)
12417                    .or_insert(Vec::new())
12418                    .push(range)
12419            }
12420        }
12421
12422        // We defer the pane interaction because we ourselves are a workspace item
12423        // and activating a new item causes the pane to call a method on us reentrantly,
12424        // which panics if we're on the stack.
12425        cx.window_context().defer(move |cx| {
12426            workspace.update(cx, |workspace, cx| {
12427                let pane = if split {
12428                    workspace.adjacent_pane(cx)
12429                } else {
12430                    workspace.active_pane().clone()
12431                };
12432
12433                for (buffer, ranges) in new_selections_by_buffer {
12434                    let editor =
12435                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12436                    editor.update(cx, |editor, cx| {
12437                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12438                            s.select_ranges(ranges);
12439                        });
12440                    });
12441                }
12442            })
12443        });
12444    }
12445
12446    fn jump(
12447        &mut self,
12448        path: ProjectPath,
12449        position: Point,
12450        anchor: language::Anchor,
12451        offset_from_top: u32,
12452        cx: &mut ViewContext<Self>,
12453    ) {
12454        let workspace = self.workspace();
12455        cx.spawn(|_, mut cx| async move {
12456            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12457            let editor = workspace.update(&mut cx, |workspace, cx| {
12458                // Reset the preview item id before opening the new item
12459                workspace.active_pane().update(cx, |pane, cx| {
12460                    pane.set_preview_item_id(None, cx);
12461                });
12462                workspace.open_path_preview(path, None, true, true, cx)
12463            })?;
12464            let editor = editor
12465                .await?
12466                .downcast::<Editor>()
12467                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12468                .downgrade();
12469            editor.update(&mut cx, |editor, cx| {
12470                let buffer = editor
12471                    .buffer()
12472                    .read(cx)
12473                    .as_singleton()
12474                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12475                let buffer = buffer.read(cx);
12476                let cursor = if buffer.can_resolve(&anchor) {
12477                    language::ToPoint::to_point(&anchor, buffer)
12478                } else {
12479                    buffer.clip_point(position, Bias::Left)
12480                };
12481
12482                let nav_history = editor.nav_history.take();
12483                editor.change_selections(
12484                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12485                    cx,
12486                    |s| {
12487                        s.select_ranges([cursor..cursor]);
12488                    },
12489                );
12490                editor.nav_history = nav_history;
12491
12492                anyhow::Ok(())
12493            })??;
12494
12495            anyhow::Ok(())
12496        })
12497        .detach_and_log_err(cx);
12498    }
12499
12500    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12501        let snapshot = self.buffer.read(cx).read(cx);
12502        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12503        Some(
12504            ranges
12505                .iter()
12506                .map(move |range| {
12507                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12508                })
12509                .collect(),
12510        )
12511    }
12512
12513    fn selection_replacement_ranges(
12514        &self,
12515        range: Range<OffsetUtf16>,
12516        cx: &AppContext,
12517    ) -> Vec<Range<OffsetUtf16>> {
12518        let selections = self.selections.all::<OffsetUtf16>(cx);
12519        let newest_selection = selections
12520            .iter()
12521            .max_by_key(|selection| selection.id)
12522            .unwrap();
12523        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12524        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12525        let snapshot = self.buffer.read(cx).read(cx);
12526        selections
12527            .into_iter()
12528            .map(|mut selection| {
12529                selection.start.0 =
12530                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12531                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12532                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12533                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12534            })
12535            .collect()
12536    }
12537
12538    fn report_editor_event(
12539        &self,
12540        operation: &'static str,
12541        file_extension: Option<String>,
12542        cx: &AppContext,
12543    ) {
12544        if cfg!(any(test, feature = "test-support")) {
12545            return;
12546        }
12547
12548        let Some(project) = &self.project else { return };
12549
12550        // If None, we are in a file without an extension
12551        let file = self
12552            .buffer
12553            .read(cx)
12554            .as_singleton()
12555            .and_then(|b| b.read(cx).file());
12556        let file_extension = file_extension.or(file
12557            .as_ref()
12558            .and_then(|file| Path::new(file.file_name(cx)).extension())
12559            .and_then(|e| e.to_str())
12560            .map(|a| a.to_string()));
12561
12562        let vim_mode = cx
12563            .global::<SettingsStore>()
12564            .raw_user_settings()
12565            .get("vim_mode")
12566            == Some(&serde_json::Value::Bool(true));
12567
12568        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12569            == language::language_settings::InlineCompletionProvider::Copilot;
12570        let copilot_enabled_for_language = self
12571            .buffer
12572            .read(cx)
12573            .settings_at(0, cx)
12574            .show_inline_completions;
12575
12576        let project = project.read(cx);
12577        let telemetry = project.client().telemetry().clone();
12578        telemetry.report_editor_event(
12579            file_extension,
12580            vim_mode,
12581            operation,
12582            copilot_enabled,
12583            copilot_enabled_for_language,
12584            project.is_via_ssh(),
12585        )
12586    }
12587
12588    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12589    /// with each line being an array of {text, highlight} objects.
12590    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12591        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12592            return;
12593        };
12594
12595        #[derive(Serialize)]
12596        struct Chunk<'a> {
12597            text: String,
12598            highlight: Option<&'a str>,
12599        }
12600
12601        let snapshot = buffer.read(cx).snapshot();
12602        let range = self
12603            .selected_text_range(false, cx)
12604            .and_then(|selection| {
12605                if selection.range.is_empty() {
12606                    None
12607                } else {
12608                    Some(selection.range)
12609                }
12610            })
12611            .unwrap_or_else(|| 0..snapshot.len());
12612
12613        let chunks = snapshot.chunks(range, true);
12614        let mut lines = Vec::new();
12615        let mut line: VecDeque<Chunk> = VecDeque::new();
12616
12617        let Some(style) = self.style.as_ref() else {
12618            return;
12619        };
12620
12621        for chunk in chunks {
12622            let highlight = chunk
12623                .syntax_highlight_id
12624                .and_then(|id| id.name(&style.syntax));
12625            let mut chunk_lines = chunk.text.split('\n').peekable();
12626            while let Some(text) = chunk_lines.next() {
12627                let mut merged_with_last_token = false;
12628                if let Some(last_token) = line.back_mut() {
12629                    if last_token.highlight == highlight {
12630                        last_token.text.push_str(text);
12631                        merged_with_last_token = true;
12632                    }
12633                }
12634
12635                if !merged_with_last_token {
12636                    line.push_back(Chunk {
12637                        text: text.into(),
12638                        highlight,
12639                    });
12640                }
12641
12642                if chunk_lines.peek().is_some() {
12643                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12644                        line.pop_front();
12645                    }
12646                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12647                        line.pop_back();
12648                    }
12649
12650                    lines.push(mem::take(&mut line));
12651                }
12652            }
12653        }
12654
12655        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12656            return;
12657        };
12658        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12659    }
12660
12661    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12662        &self.inlay_hint_cache
12663    }
12664
12665    pub fn replay_insert_event(
12666        &mut self,
12667        text: &str,
12668        relative_utf16_range: Option<Range<isize>>,
12669        cx: &mut ViewContext<Self>,
12670    ) {
12671        if !self.input_enabled {
12672            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12673            return;
12674        }
12675        if let Some(relative_utf16_range) = relative_utf16_range {
12676            let selections = self.selections.all::<OffsetUtf16>(cx);
12677            self.change_selections(None, cx, |s| {
12678                let new_ranges = selections.into_iter().map(|range| {
12679                    let start = OffsetUtf16(
12680                        range
12681                            .head()
12682                            .0
12683                            .saturating_add_signed(relative_utf16_range.start),
12684                    );
12685                    let end = OffsetUtf16(
12686                        range
12687                            .head()
12688                            .0
12689                            .saturating_add_signed(relative_utf16_range.end),
12690                    );
12691                    start..end
12692                });
12693                s.select_ranges(new_ranges);
12694            });
12695        }
12696
12697        self.handle_input(text, cx);
12698    }
12699
12700    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12701        let Some(provider) = self.semantics_provider.as_ref() else {
12702            return false;
12703        };
12704
12705        let mut supports = false;
12706        self.buffer().read(cx).for_each_buffer(|buffer| {
12707            supports |= provider.supports_inlay_hints(buffer, cx);
12708        });
12709        supports
12710    }
12711
12712    pub fn focus(&self, cx: &mut WindowContext) {
12713        cx.focus(&self.focus_handle)
12714    }
12715
12716    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12717        self.focus_handle.is_focused(cx)
12718    }
12719
12720    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12721        cx.emit(EditorEvent::Focused);
12722
12723        if let Some(descendant) = self
12724            .last_focused_descendant
12725            .take()
12726            .and_then(|descendant| descendant.upgrade())
12727        {
12728            cx.focus(&descendant);
12729        } else {
12730            if let Some(blame) = self.blame.as_ref() {
12731                blame.update(cx, GitBlame::focus)
12732            }
12733
12734            self.blink_manager.update(cx, BlinkManager::enable);
12735            self.show_cursor_names(cx);
12736            self.buffer.update(cx, |buffer, cx| {
12737                buffer.finalize_last_transaction(cx);
12738                if self.leader_peer_id.is_none() {
12739                    buffer.set_active_selections(
12740                        &self.selections.disjoint_anchors(),
12741                        self.selections.line_mode,
12742                        self.cursor_shape,
12743                        cx,
12744                    );
12745                }
12746            });
12747        }
12748    }
12749
12750    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12751        cx.emit(EditorEvent::FocusedIn)
12752    }
12753
12754    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12755        if event.blurred != self.focus_handle {
12756            self.last_focused_descendant = Some(event.blurred);
12757        }
12758    }
12759
12760    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12761        self.blink_manager.update(cx, BlinkManager::disable);
12762        self.buffer
12763            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12764
12765        if let Some(blame) = self.blame.as_ref() {
12766            blame.update(cx, GitBlame::blur)
12767        }
12768        if !self.hover_state.focused(cx) {
12769            hide_hover(self, cx);
12770        }
12771
12772        self.hide_context_menu(cx);
12773        cx.emit(EditorEvent::Blurred);
12774        cx.notify();
12775    }
12776
12777    pub fn register_action<A: Action>(
12778        &mut self,
12779        listener: impl Fn(&A, &mut WindowContext) + 'static,
12780    ) -> Subscription {
12781        let id = self.next_editor_action_id.post_inc();
12782        let listener = Arc::new(listener);
12783        self.editor_actions.borrow_mut().insert(
12784            id,
12785            Box::new(move |cx| {
12786                let cx = cx.window_context();
12787                let listener = listener.clone();
12788                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12789                    let action = action.downcast_ref().unwrap();
12790                    if phase == DispatchPhase::Bubble {
12791                        listener(action, cx)
12792                    }
12793                })
12794            }),
12795        );
12796
12797        let editor_actions = self.editor_actions.clone();
12798        Subscription::new(move || {
12799            editor_actions.borrow_mut().remove(&id);
12800        })
12801    }
12802
12803    pub fn file_header_size(&self) -> u32 {
12804        self.file_header_size
12805    }
12806
12807    pub fn revert(
12808        &mut self,
12809        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12810        cx: &mut ViewContext<Self>,
12811    ) {
12812        self.buffer().update(cx, |multi_buffer, cx| {
12813            for (buffer_id, changes) in revert_changes {
12814                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12815                    buffer.update(cx, |buffer, cx| {
12816                        buffer.edit(
12817                            changes.into_iter().map(|(range, text)| {
12818                                (range, text.to_string().map(Arc::<str>::from))
12819                            }),
12820                            None,
12821                            cx,
12822                        );
12823                    });
12824                }
12825            }
12826        });
12827        self.change_selections(None, cx, |selections| selections.refresh());
12828    }
12829
12830    pub fn to_pixel_point(
12831        &mut self,
12832        source: multi_buffer::Anchor,
12833        editor_snapshot: &EditorSnapshot,
12834        cx: &mut ViewContext<Self>,
12835    ) -> Option<gpui::Point<Pixels>> {
12836        let source_point = source.to_display_point(editor_snapshot);
12837        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12838    }
12839
12840    pub fn display_to_pixel_point(
12841        &mut self,
12842        source: DisplayPoint,
12843        editor_snapshot: &EditorSnapshot,
12844        cx: &mut ViewContext<Self>,
12845    ) -> Option<gpui::Point<Pixels>> {
12846        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12847        let text_layout_details = self.text_layout_details(cx);
12848        let scroll_top = text_layout_details
12849            .scroll_anchor
12850            .scroll_position(editor_snapshot)
12851            .y;
12852
12853        if source.row().as_f32() < scroll_top.floor() {
12854            return None;
12855        }
12856        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12857        let source_y = line_height * (source.row().as_f32() - scroll_top);
12858        Some(gpui::Point::new(source_x, source_y))
12859    }
12860
12861    pub fn has_active_completions_menu(&self) -> bool {
12862        self.context_menu.read().as_ref().map_or(false, |menu| {
12863            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12864        })
12865    }
12866
12867    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12868        self.addons
12869            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12870    }
12871
12872    pub fn unregister_addon<T: Addon>(&mut self) {
12873        self.addons.remove(&std::any::TypeId::of::<T>());
12874    }
12875
12876    pub fn addon<T: Addon>(&self) -> Option<&T> {
12877        let type_id = std::any::TypeId::of::<T>();
12878        self.addons
12879            .get(&type_id)
12880            .and_then(|item| item.to_any().downcast_ref::<T>())
12881    }
12882}
12883
12884fn hunks_for_selections(
12885    multi_buffer_snapshot: &MultiBufferSnapshot,
12886    selections: &[Selection<Anchor>],
12887) -> Vec<MultiBufferDiffHunk> {
12888    let buffer_rows_for_selections = selections.iter().map(|selection| {
12889        let head = selection.head();
12890        let tail = selection.tail();
12891        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12892        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12893        if start > end {
12894            end..start
12895        } else {
12896            start..end
12897        }
12898    });
12899
12900    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12901}
12902
12903pub fn hunks_for_rows(
12904    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12905    multi_buffer_snapshot: &MultiBufferSnapshot,
12906) -> Vec<MultiBufferDiffHunk> {
12907    let mut hunks = Vec::new();
12908    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12909        HashMap::default();
12910    for selected_multi_buffer_rows in rows {
12911        let query_rows =
12912            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12913        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12914            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12915            // when the caret is just above or just below the deleted hunk.
12916            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12917            let related_to_selection = if allow_adjacent {
12918                hunk.row_range.overlaps(&query_rows)
12919                    || hunk.row_range.start == query_rows.end
12920                    || hunk.row_range.end == query_rows.start
12921            } else {
12922                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12923                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12924                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12925                    || selected_multi_buffer_rows.end == hunk.row_range.start
12926            };
12927            if related_to_selection {
12928                if !processed_buffer_rows
12929                    .entry(hunk.buffer_id)
12930                    .or_default()
12931                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12932                {
12933                    continue;
12934                }
12935                hunks.push(hunk);
12936            }
12937        }
12938    }
12939
12940    hunks
12941}
12942
12943pub trait CollaborationHub {
12944    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12945    fn user_participant_indices<'a>(
12946        &self,
12947        cx: &'a AppContext,
12948    ) -> &'a HashMap<u64, ParticipantIndex>;
12949    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12950}
12951
12952impl CollaborationHub for Model<Project> {
12953    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12954        self.read(cx).collaborators()
12955    }
12956
12957    fn user_participant_indices<'a>(
12958        &self,
12959        cx: &'a AppContext,
12960    ) -> &'a HashMap<u64, ParticipantIndex> {
12961        self.read(cx).user_store().read(cx).participant_indices()
12962    }
12963
12964    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12965        let this = self.read(cx);
12966        let user_ids = this.collaborators().values().map(|c| c.user_id);
12967        this.user_store().read_with(cx, |user_store, cx| {
12968            user_store.participant_names(user_ids, cx)
12969        })
12970    }
12971}
12972
12973pub trait SemanticsProvider {
12974    fn hover(
12975        &self,
12976        buffer: &Model<Buffer>,
12977        position: text::Anchor,
12978        cx: &mut AppContext,
12979    ) -> Option<Task<Vec<project::Hover>>>;
12980
12981    fn inlay_hints(
12982        &self,
12983        buffer_handle: Model<Buffer>,
12984        range: Range<text::Anchor>,
12985        cx: &mut AppContext,
12986    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12987
12988    fn resolve_inlay_hint(
12989        &self,
12990        hint: InlayHint,
12991        buffer_handle: Model<Buffer>,
12992        server_id: LanguageServerId,
12993        cx: &mut AppContext,
12994    ) -> Option<Task<anyhow::Result<InlayHint>>>;
12995
12996    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
12997
12998    fn document_highlights(
12999        &self,
13000        buffer: &Model<Buffer>,
13001        position: text::Anchor,
13002        cx: &mut AppContext,
13003    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13004
13005    fn definitions(
13006        &self,
13007        buffer: &Model<Buffer>,
13008        position: text::Anchor,
13009        kind: GotoDefinitionKind,
13010        cx: &mut AppContext,
13011    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13012
13013    fn range_for_rename(
13014        &self,
13015        buffer: &Model<Buffer>,
13016        position: text::Anchor,
13017        cx: &mut AppContext,
13018    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13019
13020    fn perform_rename(
13021        &self,
13022        buffer: &Model<Buffer>,
13023        position: text::Anchor,
13024        new_name: String,
13025        cx: &mut AppContext,
13026    ) -> Option<Task<Result<ProjectTransaction>>>;
13027}
13028
13029pub trait CompletionProvider {
13030    fn completions(
13031        &self,
13032        buffer: &Model<Buffer>,
13033        buffer_position: text::Anchor,
13034        trigger: CompletionContext,
13035        cx: &mut ViewContext<Editor>,
13036    ) -> Task<Result<Vec<Completion>>>;
13037
13038    fn resolve_completions(
13039        &self,
13040        buffer: Model<Buffer>,
13041        completion_indices: Vec<usize>,
13042        completions: Arc<RwLock<Box<[Completion]>>>,
13043        cx: &mut ViewContext<Editor>,
13044    ) -> Task<Result<bool>>;
13045
13046    fn apply_additional_edits_for_completion(
13047        &self,
13048        buffer: Model<Buffer>,
13049        completion: Completion,
13050        push_to_history: bool,
13051        cx: &mut ViewContext<Editor>,
13052    ) -> Task<Result<Option<language::Transaction>>>;
13053
13054    fn is_completion_trigger(
13055        &self,
13056        buffer: &Model<Buffer>,
13057        position: language::Anchor,
13058        text: &str,
13059        trigger_in_words: bool,
13060        cx: &mut ViewContext<Editor>,
13061    ) -> bool;
13062
13063    fn sort_completions(&self) -> bool {
13064        true
13065    }
13066}
13067
13068pub trait CodeActionProvider {
13069    fn code_actions(
13070        &self,
13071        buffer: &Model<Buffer>,
13072        range: Range<text::Anchor>,
13073        cx: &mut WindowContext,
13074    ) -> Task<Result<Vec<CodeAction>>>;
13075
13076    fn apply_code_action(
13077        &self,
13078        buffer_handle: Model<Buffer>,
13079        action: CodeAction,
13080        excerpt_id: ExcerptId,
13081        push_to_history: bool,
13082        cx: &mut WindowContext,
13083    ) -> Task<Result<ProjectTransaction>>;
13084}
13085
13086impl CodeActionProvider for Model<Project> {
13087    fn code_actions(
13088        &self,
13089        buffer: &Model<Buffer>,
13090        range: Range<text::Anchor>,
13091        cx: &mut WindowContext,
13092    ) -> Task<Result<Vec<CodeAction>>> {
13093        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13094    }
13095
13096    fn apply_code_action(
13097        &self,
13098        buffer_handle: Model<Buffer>,
13099        action: CodeAction,
13100        _excerpt_id: ExcerptId,
13101        push_to_history: bool,
13102        cx: &mut WindowContext,
13103    ) -> Task<Result<ProjectTransaction>> {
13104        self.update(cx, |project, cx| {
13105            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13106        })
13107    }
13108}
13109
13110fn snippet_completions(
13111    project: &Project,
13112    buffer: &Model<Buffer>,
13113    buffer_position: text::Anchor,
13114    cx: &mut AppContext,
13115) -> Vec<Completion> {
13116    let language = buffer.read(cx).language_at(buffer_position);
13117    let language_name = language.as_ref().map(|language| language.lsp_id());
13118    let snippet_store = project.snippets().read(cx);
13119    let snippets = snippet_store.snippets_for(language_name, cx);
13120
13121    if snippets.is_empty() {
13122        return vec![];
13123    }
13124    let snapshot = buffer.read(cx).text_snapshot();
13125    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13126
13127    let scope = language.map(|language| language.default_scope());
13128    let classifier = CharClassifier::new(scope).for_completion(true);
13129    let mut last_word = chars
13130        .take_while(|c| classifier.is_word(*c))
13131        .collect::<String>();
13132    last_word = last_word.chars().rev().collect();
13133    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13134    let to_lsp = |point: &text::Anchor| {
13135        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13136        point_to_lsp(end)
13137    };
13138    let lsp_end = to_lsp(&buffer_position);
13139    snippets
13140        .into_iter()
13141        .filter_map(|snippet| {
13142            let matching_prefix = snippet
13143                .prefix
13144                .iter()
13145                .find(|prefix| prefix.starts_with(&last_word))?;
13146            let start = as_offset - last_word.len();
13147            let start = snapshot.anchor_before(start);
13148            let range = start..buffer_position;
13149            let lsp_start = to_lsp(&start);
13150            let lsp_range = lsp::Range {
13151                start: lsp_start,
13152                end: lsp_end,
13153            };
13154            Some(Completion {
13155                old_range: range,
13156                new_text: snippet.body.clone(),
13157                label: CodeLabel {
13158                    text: matching_prefix.clone(),
13159                    runs: vec![],
13160                    filter_range: 0..matching_prefix.len(),
13161                },
13162                server_id: LanguageServerId(usize::MAX),
13163                documentation: snippet.description.clone().map(Documentation::SingleLine),
13164                lsp_completion: lsp::CompletionItem {
13165                    label: snippet.prefix.first().unwrap().clone(),
13166                    kind: Some(CompletionItemKind::SNIPPET),
13167                    label_details: snippet.description.as_ref().map(|description| {
13168                        lsp::CompletionItemLabelDetails {
13169                            detail: Some(description.clone()),
13170                            description: None,
13171                        }
13172                    }),
13173                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13174                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13175                        lsp::InsertReplaceEdit {
13176                            new_text: snippet.body.clone(),
13177                            insert: lsp_range,
13178                            replace: lsp_range,
13179                        },
13180                    )),
13181                    filter_text: Some(snippet.body.clone()),
13182                    sort_text: Some(char::MAX.to_string()),
13183                    ..Default::default()
13184                },
13185                confirm: None,
13186            })
13187        })
13188        .collect()
13189}
13190
13191impl CompletionProvider for Model<Project> {
13192    fn completions(
13193        &self,
13194        buffer: &Model<Buffer>,
13195        buffer_position: text::Anchor,
13196        options: CompletionContext,
13197        cx: &mut ViewContext<Editor>,
13198    ) -> Task<Result<Vec<Completion>>> {
13199        self.update(cx, |project, cx| {
13200            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13201            let project_completions = project.completions(buffer, buffer_position, options, cx);
13202            cx.background_executor().spawn(async move {
13203                let mut completions = project_completions.await?;
13204                //let snippets = snippets.into_iter().;
13205                completions.extend(snippets);
13206                Ok(completions)
13207            })
13208        })
13209    }
13210
13211    fn resolve_completions(
13212        &self,
13213        buffer: Model<Buffer>,
13214        completion_indices: Vec<usize>,
13215        completions: Arc<RwLock<Box<[Completion]>>>,
13216        cx: &mut ViewContext<Editor>,
13217    ) -> Task<Result<bool>> {
13218        self.update(cx, |project, cx| {
13219            project.resolve_completions(buffer, completion_indices, completions, cx)
13220        })
13221    }
13222
13223    fn apply_additional_edits_for_completion(
13224        &self,
13225        buffer: Model<Buffer>,
13226        completion: Completion,
13227        push_to_history: bool,
13228        cx: &mut ViewContext<Editor>,
13229    ) -> Task<Result<Option<language::Transaction>>> {
13230        self.update(cx, |project, cx| {
13231            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13232        })
13233    }
13234
13235    fn is_completion_trigger(
13236        &self,
13237        buffer: &Model<Buffer>,
13238        position: language::Anchor,
13239        text: &str,
13240        trigger_in_words: bool,
13241        cx: &mut ViewContext<Editor>,
13242    ) -> bool {
13243        if !EditorSettings::get_global(cx).show_completions_on_input {
13244            return false;
13245        }
13246
13247        let mut chars = text.chars();
13248        let char = if let Some(char) = chars.next() {
13249            char
13250        } else {
13251            return false;
13252        };
13253        if chars.next().is_some() {
13254            return false;
13255        }
13256
13257        let buffer = buffer.read(cx);
13258        let classifier = buffer
13259            .snapshot()
13260            .char_classifier_at(position)
13261            .for_completion(true);
13262        if trigger_in_words && classifier.is_word(char) {
13263            return true;
13264        }
13265
13266        buffer
13267            .completion_triggers()
13268            .iter()
13269            .any(|string| string == text)
13270    }
13271}
13272
13273impl SemanticsProvider for Model<Project> {
13274    fn hover(
13275        &self,
13276        buffer: &Model<Buffer>,
13277        position: text::Anchor,
13278        cx: &mut AppContext,
13279    ) -> Option<Task<Vec<project::Hover>>> {
13280        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13281    }
13282
13283    fn document_highlights(
13284        &self,
13285        buffer: &Model<Buffer>,
13286        position: text::Anchor,
13287        cx: &mut AppContext,
13288    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13289        Some(self.update(cx, |project, cx| {
13290            project.document_highlights(buffer, position, cx)
13291        }))
13292    }
13293
13294    fn definitions(
13295        &self,
13296        buffer: &Model<Buffer>,
13297        position: text::Anchor,
13298        kind: GotoDefinitionKind,
13299        cx: &mut AppContext,
13300    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13301        Some(self.update(cx, |project, cx| match kind {
13302            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13303            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13304            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13305            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13306        }))
13307    }
13308
13309    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13310        // TODO: make this work for remote projects
13311        self.read(cx)
13312            .language_servers_for_buffer(buffer.read(cx), cx)
13313            .any(
13314                |(_, server)| match server.capabilities().inlay_hint_provider {
13315                    Some(lsp::OneOf::Left(enabled)) => enabled,
13316                    Some(lsp::OneOf::Right(_)) => true,
13317                    None => false,
13318                },
13319            )
13320    }
13321
13322    fn inlay_hints(
13323        &self,
13324        buffer_handle: Model<Buffer>,
13325        range: Range<text::Anchor>,
13326        cx: &mut AppContext,
13327    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13328        Some(self.update(cx, |project, cx| {
13329            project.inlay_hints(buffer_handle, range, cx)
13330        }))
13331    }
13332
13333    fn resolve_inlay_hint(
13334        &self,
13335        hint: InlayHint,
13336        buffer_handle: Model<Buffer>,
13337        server_id: LanguageServerId,
13338        cx: &mut AppContext,
13339    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13340        Some(self.update(cx, |project, cx| {
13341            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13342        }))
13343    }
13344
13345    fn range_for_rename(
13346        &self,
13347        buffer: &Model<Buffer>,
13348        position: text::Anchor,
13349        cx: &mut AppContext,
13350    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13351        Some(self.update(cx, |project, cx| {
13352            project.prepare_rename(buffer.clone(), position, cx)
13353        }))
13354    }
13355
13356    fn perform_rename(
13357        &self,
13358        buffer: &Model<Buffer>,
13359        position: text::Anchor,
13360        new_name: String,
13361        cx: &mut AppContext,
13362    ) -> Option<Task<Result<ProjectTransaction>>> {
13363        Some(self.update(cx, |project, cx| {
13364            project.perform_rename(buffer.clone(), position, new_name, cx)
13365        }))
13366    }
13367}
13368
13369fn inlay_hint_settings(
13370    location: Anchor,
13371    snapshot: &MultiBufferSnapshot,
13372    cx: &mut ViewContext<'_, Editor>,
13373) -> InlayHintSettings {
13374    let file = snapshot.file_at(location);
13375    let language = snapshot.language_at(location);
13376    let settings = all_language_settings(file, cx);
13377    settings
13378        .language(language.map(|l| l.name()).as_ref())
13379        .inlay_hints
13380}
13381
13382fn consume_contiguous_rows(
13383    contiguous_row_selections: &mut Vec<Selection<Point>>,
13384    selection: &Selection<Point>,
13385    display_map: &DisplaySnapshot,
13386    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13387) -> (MultiBufferRow, MultiBufferRow) {
13388    contiguous_row_selections.push(selection.clone());
13389    let start_row = MultiBufferRow(selection.start.row);
13390    let mut end_row = ending_row(selection, display_map);
13391
13392    while let Some(next_selection) = selections.peek() {
13393        if next_selection.start.row <= end_row.0 {
13394            end_row = ending_row(next_selection, display_map);
13395            contiguous_row_selections.push(selections.next().unwrap().clone());
13396        } else {
13397            break;
13398        }
13399    }
13400    (start_row, end_row)
13401}
13402
13403fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13404    if next_selection.end.column > 0 || next_selection.is_empty() {
13405        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13406    } else {
13407        MultiBufferRow(next_selection.end.row)
13408    }
13409}
13410
13411impl EditorSnapshot {
13412    pub fn remote_selections_in_range<'a>(
13413        &'a self,
13414        range: &'a Range<Anchor>,
13415        collaboration_hub: &dyn CollaborationHub,
13416        cx: &'a AppContext,
13417    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13418        let participant_names = collaboration_hub.user_names(cx);
13419        let participant_indices = collaboration_hub.user_participant_indices(cx);
13420        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13421        let collaborators_by_replica_id = collaborators_by_peer_id
13422            .iter()
13423            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13424            .collect::<HashMap<_, _>>();
13425        self.buffer_snapshot
13426            .selections_in_range(range, false)
13427            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13428                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13429                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13430                let user_name = participant_names.get(&collaborator.user_id).cloned();
13431                Some(RemoteSelection {
13432                    replica_id,
13433                    selection,
13434                    cursor_shape,
13435                    line_mode,
13436                    participant_index,
13437                    peer_id: collaborator.peer_id,
13438                    user_name,
13439                })
13440            })
13441    }
13442
13443    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13444        self.display_snapshot.buffer_snapshot.language_at(position)
13445    }
13446
13447    pub fn is_focused(&self) -> bool {
13448        self.is_focused
13449    }
13450
13451    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13452        self.placeholder_text.as_ref()
13453    }
13454
13455    pub fn scroll_position(&self) -> gpui::Point<f32> {
13456        self.scroll_anchor.scroll_position(&self.display_snapshot)
13457    }
13458
13459    fn gutter_dimensions(
13460        &self,
13461        font_id: FontId,
13462        font_size: Pixels,
13463        em_width: Pixels,
13464        em_advance: Pixels,
13465        max_line_number_width: Pixels,
13466        cx: &AppContext,
13467    ) -> GutterDimensions {
13468        if !self.show_gutter {
13469            return GutterDimensions::default();
13470        }
13471        let descent = cx.text_system().descent(font_id, font_size);
13472
13473        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13474            matches!(
13475                ProjectSettings::get_global(cx).git.git_gutter,
13476                Some(GitGutterSetting::TrackedFiles)
13477            )
13478        });
13479        let gutter_settings = EditorSettings::get_global(cx).gutter;
13480        let show_line_numbers = self
13481            .show_line_numbers
13482            .unwrap_or(gutter_settings.line_numbers);
13483        let line_gutter_width = if show_line_numbers {
13484            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13485            let min_width_for_number_on_gutter = em_advance * 4.0;
13486            max_line_number_width.max(min_width_for_number_on_gutter)
13487        } else {
13488            0.0.into()
13489        };
13490
13491        let show_code_actions = self
13492            .show_code_actions
13493            .unwrap_or(gutter_settings.code_actions);
13494
13495        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13496
13497        let git_blame_entries_width =
13498            self.git_blame_gutter_max_author_length
13499                .map(|max_author_length| {
13500                    // Length of the author name, but also space for the commit hash,
13501                    // the spacing and the timestamp.
13502                    let max_char_count = max_author_length
13503                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13504                        + 7 // length of commit sha
13505                        + 14 // length of max relative timestamp ("60 minutes ago")
13506                        + 4; // gaps and margins
13507
13508                    em_advance * max_char_count
13509                });
13510
13511        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13512        left_padding += if show_code_actions || show_runnables {
13513            em_width * 3.0
13514        } else if show_git_gutter && show_line_numbers {
13515            em_width * 2.0
13516        } else if show_git_gutter || show_line_numbers {
13517            em_width
13518        } else {
13519            px(0.)
13520        };
13521
13522        let right_padding = if gutter_settings.folds && show_line_numbers {
13523            em_width * 4.0
13524        } else if gutter_settings.folds {
13525            em_width * 3.0
13526        } else if show_line_numbers {
13527            em_width
13528        } else {
13529            px(0.)
13530        };
13531
13532        GutterDimensions {
13533            left_padding,
13534            right_padding,
13535            width: line_gutter_width + left_padding + right_padding,
13536            margin: -descent,
13537            git_blame_entries_width,
13538        }
13539    }
13540
13541    pub fn render_fold_toggle(
13542        &self,
13543        buffer_row: MultiBufferRow,
13544        row_contains_cursor: bool,
13545        editor: View<Editor>,
13546        cx: &mut WindowContext,
13547    ) -> Option<AnyElement> {
13548        let folded = self.is_line_folded(buffer_row);
13549
13550        if let Some(crease) = self
13551            .crease_snapshot
13552            .query_row(buffer_row, &self.buffer_snapshot)
13553        {
13554            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13555                if folded {
13556                    editor.update(cx, |editor, cx| {
13557                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13558                    });
13559                } else {
13560                    editor.update(cx, |editor, cx| {
13561                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13562                    });
13563                }
13564            });
13565
13566            Some((crease.render_toggle)(
13567                buffer_row,
13568                folded,
13569                toggle_callback,
13570                cx,
13571            ))
13572        } else if folded
13573            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13574        {
13575            Some(
13576                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13577                    .selected(folded)
13578                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13579                        if folded {
13580                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13581                        } else {
13582                            this.fold_at(&FoldAt { buffer_row }, cx);
13583                        }
13584                    }))
13585                    .into_any_element(),
13586            )
13587        } else {
13588            None
13589        }
13590    }
13591
13592    pub fn render_crease_trailer(
13593        &self,
13594        buffer_row: MultiBufferRow,
13595        cx: &mut WindowContext,
13596    ) -> Option<AnyElement> {
13597        let folded = self.is_line_folded(buffer_row);
13598        let crease = self
13599            .crease_snapshot
13600            .query_row(buffer_row, &self.buffer_snapshot)?;
13601        Some((crease.render_trailer)(buffer_row, folded, cx))
13602    }
13603}
13604
13605impl Deref for EditorSnapshot {
13606    type Target = DisplaySnapshot;
13607
13608    fn deref(&self) -> &Self::Target {
13609        &self.display_snapshot
13610    }
13611}
13612
13613#[derive(Clone, Debug, PartialEq, Eq)]
13614pub enum EditorEvent {
13615    InputIgnored {
13616        text: Arc<str>,
13617    },
13618    InputHandled {
13619        utf16_range_to_replace: Option<Range<isize>>,
13620        text: Arc<str>,
13621    },
13622    ExcerptsAdded {
13623        buffer: Model<Buffer>,
13624        predecessor: ExcerptId,
13625        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13626    },
13627    ExcerptsRemoved {
13628        ids: Vec<ExcerptId>,
13629    },
13630    ExcerptsEdited {
13631        ids: Vec<ExcerptId>,
13632    },
13633    ExcerptsExpanded {
13634        ids: Vec<ExcerptId>,
13635    },
13636    BufferEdited,
13637    Edited {
13638        transaction_id: clock::Lamport,
13639    },
13640    Reparsed(BufferId),
13641    Focused,
13642    FocusedIn,
13643    Blurred,
13644    DirtyChanged,
13645    Saved,
13646    TitleChanged,
13647    DiffBaseChanged,
13648    SelectionsChanged {
13649        local: bool,
13650    },
13651    ScrollPositionChanged {
13652        local: bool,
13653        autoscroll: bool,
13654    },
13655    Closed,
13656    TransactionUndone {
13657        transaction_id: clock::Lamport,
13658    },
13659    TransactionBegun {
13660        transaction_id: clock::Lamport,
13661    },
13662    Reloaded,
13663    CursorShapeChanged,
13664}
13665
13666impl EventEmitter<EditorEvent> for Editor {}
13667
13668impl FocusableView for Editor {
13669    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13670        self.focus_handle.clone()
13671    }
13672}
13673
13674impl Render for Editor {
13675    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13676        let settings = ThemeSettings::get_global(cx);
13677
13678        let text_style = match self.mode {
13679            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13680                color: cx.theme().colors().editor_foreground,
13681                font_family: settings.ui_font.family.clone(),
13682                font_features: settings.ui_font.features.clone(),
13683                font_fallbacks: settings.ui_font.fallbacks.clone(),
13684                font_size: rems(0.875).into(),
13685                font_weight: settings.ui_font.weight,
13686                line_height: relative(settings.buffer_line_height.value()),
13687                ..Default::default()
13688            },
13689            EditorMode::Full => TextStyle {
13690                color: cx.theme().colors().editor_foreground,
13691                font_family: settings.buffer_font.family.clone(),
13692                font_features: settings.buffer_font.features.clone(),
13693                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13694                font_size: settings.buffer_font_size(cx).into(),
13695                font_weight: settings.buffer_font.weight,
13696                line_height: relative(settings.buffer_line_height.value()),
13697                ..Default::default()
13698            },
13699        };
13700
13701        let background = match self.mode {
13702            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13703            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13704            EditorMode::Full => cx.theme().colors().editor_background,
13705        };
13706
13707        EditorElement::new(
13708            cx.view(),
13709            EditorStyle {
13710                background,
13711                local_player: cx.theme().players().local(),
13712                text: text_style,
13713                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13714                syntax: cx.theme().syntax().clone(),
13715                status: cx.theme().status().clone(),
13716                inlay_hints_style: make_inlay_hints_style(cx),
13717                suggestions_style: HighlightStyle {
13718                    color: Some(cx.theme().status().predictive),
13719                    ..HighlightStyle::default()
13720                },
13721                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13722            },
13723        )
13724    }
13725}
13726
13727impl ViewInputHandler for Editor {
13728    fn text_for_range(
13729        &mut self,
13730        range_utf16: Range<usize>,
13731        cx: &mut ViewContext<Self>,
13732    ) -> Option<String> {
13733        Some(
13734            self.buffer
13735                .read(cx)
13736                .read(cx)
13737                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13738                .collect(),
13739        )
13740    }
13741
13742    fn selected_text_range(
13743        &mut self,
13744        ignore_disabled_input: bool,
13745        cx: &mut ViewContext<Self>,
13746    ) -> Option<UTF16Selection> {
13747        // Prevent the IME menu from appearing when holding down an alphabetic key
13748        // while input is disabled.
13749        if !ignore_disabled_input && !self.input_enabled {
13750            return None;
13751        }
13752
13753        let selection = self.selections.newest::<OffsetUtf16>(cx);
13754        let range = selection.range();
13755
13756        Some(UTF16Selection {
13757            range: range.start.0..range.end.0,
13758            reversed: selection.reversed,
13759        })
13760    }
13761
13762    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13763        let snapshot = self.buffer.read(cx).read(cx);
13764        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13765        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13766    }
13767
13768    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13769        self.clear_highlights::<InputComposition>(cx);
13770        self.ime_transaction.take();
13771    }
13772
13773    fn replace_text_in_range(
13774        &mut self,
13775        range_utf16: Option<Range<usize>>,
13776        text: &str,
13777        cx: &mut ViewContext<Self>,
13778    ) {
13779        if !self.input_enabled {
13780            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13781            return;
13782        }
13783
13784        self.transact(cx, |this, cx| {
13785            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13786                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13787                Some(this.selection_replacement_ranges(range_utf16, cx))
13788            } else {
13789                this.marked_text_ranges(cx)
13790            };
13791
13792            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13793                let newest_selection_id = this.selections.newest_anchor().id;
13794                this.selections
13795                    .all::<OffsetUtf16>(cx)
13796                    .iter()
13797                    .zip(ranges_to_replace.iter())
13798                    .find_map(|(selection, range)| {
13799                        if selection.id == newest_selection_id {
13800                            Some(
13801                                (range.start.0 as isize - selection.head().0 as isize)
13802                                    ..(range.end.0 as isize - selection.head().0 as isize),
13803                            )
13804                        } else {
13805                            None
13806                        }
13807                    })
13808            });
13809
13810            cx.emit(EditorEvent::InputHandled {
13811                utf16_range_to_replace: range_to_replace,
13812                text: text.into(),
13813            });
13814
13815            if let Some(new_selected_ranges) = new_selected_ranges {
13816                this.change_selections(None, cx, |selections| {
13817                    selections.select_ranges(new_selected_ranges)
13818                });
13819                this.backspace(&Default::default(), cx);
13820            }
13821
13822            this.handle_input(text, cx);
13823        });
13824
13825        if let Some(transaction) = self.ime_transaction {
13826            self.buffer.update(cx, |buffer, cx| {
13827                buffer.group_until_transaction(transaction, cx);
13828            });
13829        }
13830
13831        self.unmark_text(cx);
13832    }
13833
13834    fn replace_and_mark_text_in_range(
13835        &mut self,
13836        range_utf16: Option<Range<usize>>,
13837        text: &str,
13838        new_selected_range_utf16: Option<Range<usize>>,
13839        cx: &mut ViewContext<Self>,
13840    ) {
13841        if !self.input_enabled {
13842            return;
13843        }
13844
13845        let transaction = self.transact(cx, |this, cx| {
13846            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13847                let snapshot = this.buffer.read(cx).read(cx);
13848                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13849                    for marked_range in &mut marked_ranges {
13850                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13851                        marked_range.start.0 += relative_range_utf16.start;
13852                        marked_range.start =
13853                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13854                        marked_range.end =
13855                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13856                    }
13857                }
13858                Some(marked_ranges)
13859            } else if let Some(range_utf16) = range_utf16 {
13860                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13861                Some(this.selection_replacement_ranges(range_utf16, cx))
13862            } else {
13863                None
13864            };
13865
13866            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13867                let newest_selection_id = this.selections.newest_anchor().id;
13868                this.selections
13869                    .all::<OffsetUtf16>(cx)
13870                    .iter()
13871                    .zip(ranges_to_replace.iter())
13872                    .find_map(|(selection, range)| {
13873                        if selection.id == newest_selection_id {
13874                            Some(
13875                                (range.start.0 as isize - selection.head().0 as isize)
13876                                    ..(range.end.0 as isize - selection.head().0 as isize),
13877                            )
13878                        } else {
13879                            None
13880                        }
13881                    })
13882            });
13883
13884            cx.emit(EditorEvent::InputHandled {
13885                utf16_range_to_replace: range_to_replace,
13886                text: text.into(),
13887            });
13888
13889            if let Some(ranges) = ranges_to_replace {
13890                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13891            }
13892
13893            let marked_ranges = {
13894                let snapshot = this.buffer.read(cx).read(cx);
13895                this.selections
13896                    .disjoint_anchors()
13897                    .iter()
13898                    .map(|selection| {
13899                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13900                    })
13901                    .collect::<Vec<_>>()
13902            };
13903
13904            if text.is_empty() {
13905                this.unmark_text(cx);
13906            } else {
13907                this.highlight_text::<InputComposition>(
13908                    marked_ranges.clone(),
13909                    HighlightStyle {
13910                        underline: Some(UnderlineStyle {
13911                            thickness: px(1.),
13912                            color: None,
13913                            wavy: false,
13914                        }),
13915                        ..Default::default()
13916                    },
13917                    cx,
13918                );
13919            }
13920
13921            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13922            let use_autoclose = this.use_autoclose;
13923            let use_auto_surround = this.use_auto_surround;
13924            this.set_use_autoclose(false);
13925            this.set_use_auto_surround(false);
13926            this.handle_input(text, cx);
13927            this.set_use_autoclose(use_autoclose);
13928            this.set_use_auto_surround(use_auto_surround);
13929
13930            if let Some(new_selected_range) = new_selected_range_utf16 {
13931                let snapshot = this.buffer.read(cx).read(cx);
13932                let new_selected_ranges = marked_ranges
13933                    .into_iter()
13934                    .map(|marked_range| {
13935                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13936                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13937                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13938                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13939                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13940                    })
13941                    .collect::<Vec<_>>();
13942
13943                drop(snapshot);
13944                this.change_selections(None, cx, |selections| {
13945                    selections.select_ranges(new_selected_ranges)
13946                });
13947            }
13948        });
13949
13950        self.ime_transaction = self.ime_transaction.or(transaction);
13951        if let Some(transaction) = self.ime_transaction {
13952            self.buffer.update(cx, |buffer, cx| {
13953                buffer.group_until_transaction(transaction, cx);
13954            });
13955        }
13956
13957        if self.text_highlights::<InputComposition>(cx).is_none() {
13958            self.ime_transaction.take();
13959        }
13960    }
13961
13962    fn bounds_for_range(
13963        &mut self,
13964        range_utf16: Range<usize>,
13965        element_bounds: gpui::Bounds<Pixels>,
13966        cx: &mut ViewContext<Self>,
13967    ) -> Option<gpui::Bounds<Pixels>> {
13968        let text_layout_details = self.text_layout_details(cx);
13969        let style = &text_layout_details.editor_style;
13970        let font_id = cx.text_system().resolve_font(&style.text.font());
13971        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13972        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13973
13974        let em_width = cx
13975            .text_system()
13976            .typographic_bounds(font_id, font_size, 'm')
13977            .unwrap()
13978            .size
13979            .width;
13980
13981        let snapshot = self.snapshot(cx);
13982        let scroll_position = snapshot.scroll_position();
13983        let scroll_left = scroll_position.x * em_width;
13984
13985        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13986        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13987            + self.gutter_dimensions.width;
13988        let y = line_height * (start.row().as_f32() - scroll_position.y);
13989
13990        Some(Bounds {
13991            origin: element_bounds.origin + point(x, y),
13992            size: size(em_width, line_height),
13993        })
13994    }
13995}
13996
13997trait SelectionExt {
13998    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13999    fn spanned_rows(
14000        &self,
14001        include_end_if_at_line_start: bool,
14002        map: &DisplaySnapshot,
14003    ) -> Range<MultiBufferRow>;
14004}
14005
14006impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14007    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14008        let start = self
14009            .start
14010            .to_point(&map.buffer_snapshot)
14011            .to_display_point(map);
14012        let end = self
14013            .end
14014            .to_point(&map.buffer_snapshot)
14015            .to_display_point(map);
14016        if self.reversed {
14017            end..start
14018        } else {
14019            start..end
14020        }
14021    }
14022
14023    fn spanned_rows(
14024        &self,
14025        include_end_if_at_line_start: bool,
14026        map: &DisplaySnapshot,
14027    ) -> Range<MultiBufferRow> {
14028        let start = self.start.to_point(&map.buffer_snapshot);
14029        let mut end = self.end.to_point(&map.buffer_snapshot);
14030        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14031            end.row -= 1;
14032        }
14033
14034        let buffer_start = map.prev_line_boundary(start).0;
14035        let buffer_end = map.next_line_boundary(end).0;
14036        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14037    }
14038}
14039
14040impl<T: InvalidationRegion> InvalidationStack<T> {
14041    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14042    where
14043        S: Clone + ToOffset,
14044    {
14045        while let Some(region) = self.last() {
14046            let all_selections_inside_invalidation_ranges =
14047                if selections.len() == region.ranges().len() {
14048                    selections
14049                        .iter()
14050                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14051                        .all(|(selection, invalidation_range)| {
14052                            let head = selection.head().to_offset(buffer);
14053                            invalidation_range.start <= head && invalidation_range.end >= head
14054                        })
14055                } else {
14056                    false
14057                };
14058
14059            if all_selections_inside_invalidation_ranges {
14060                break;
14061            } else {
14062                self.pop();
14063            }
14064        }
14065    }
14066}
14067
14068impl<T> Default for InvalidationStack<T> {
14069    fn default() -> Self {
14070        Self(Default::default())
14071    }
14072}
14073
14074impl<T> Deref for InvalidationStack<T> {
14075    type Target = Vec<T>;
14076
14077    fn deref(&self) -> &Self::Target {
14078        &self.0
14079    }
14080}
14081
14082impl<T> DerefMut for InvalidationStack<T> {
14083    fn deref_mut(&mut self) -> &mut Self::Target {
14084        &mut self.0
14085    }
14086}
14087
14088impl InvalidationRegion for SnippetState {
14089    fn ranges(&self) -> &[Range<Anchor>] {
14090        &self.ranges[self.active_index]
14091    }
14092}
14093
14094pub fn diagnostic_block_renderer(
14095    diagnostic: Diagnostic,
14096    max_message_rows: Option<u8>,
14097    allow_closing: bool,
14098    _is_valid: bool,
14099) -> RenderBlock {
14100    let (text_without_backticks, code_ranges) =
14101        highlight_diagnostic_message(&diagnostic, max_message_rows);
14102
14103    Box::new(move |cx: &mut BlockContext| {
14104        let group_id: SharedString = cx.block_id.to_string().into();
14105
14106        let mut text_style = cx.text_style().clone();
14107        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14108        let theme_settings = ThemeSettings::get_global(cx);
14109        text_style.font_family = theme_settings.buffer_font.family.clone();
14110        text_style.font_style = theme_settings.buffer_font.style;
14111        text_style.font_features = theme_settings.buffer_font.features.clone();
14112        text_style.font_weight = theme_settings.buffer_font.weight;
14113
14114        let multi_line_diagnostic = diagnostic.message.contains('\n');
14115
14116        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
14117            if multi_line_diagnostic {
14118                v_flex()
14119            } else {
14120                h_flex()
14121            }
14122            .when(allow_closing, |div| {
14123                div.children(diagnostic.is_primary.then(|| {
14124                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
14125                        .icon_color(Color::Muted)
14126                        .size(ButtonSize::Compact)
14127                        .style(ButtonStyle::Transparent)
14128                        .visible_on_hover(group_id.clone())
14129                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14130                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14131                }))
14132            })
14133            .child(
14134                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
14135                    .icon_color(Color::Muted)
14136                    .size(ButtonSize::Compact)
14137                    .style(ButtonStyle::Transparent)
14138                    .visible_on_hover(group_id.clone())
14139                    .on_click({
14140                        let message = diagnostic.message.clone();
14141                        move |_click, cx| {
14142                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14143                        }
14144                    })
14145                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14146            )
14147        };
14148
14149        let icon_size = buttons(&diagnostic, cx.block_id)
14150            .into_any_element()
14151            .layout_as_root(AvailableSpace::min_size(), cx);
14152
14153        h_flex()
14154            .id(cx.block_id)
14155            .group(group_id.clone())
14156            .relative()
14157            .size_full()
14158            .pl(cx.gutter_dimensions.width)
14159            .w(cx.max_width + cx.gutter_dimensions.width)
14160            .child(
14161                div()
14162                    .flex()
14163                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14164                    .flex_shrink(),
14165            )
14166            .child(buttons(&diagnostic, cx.block_id))
14167            .child(div().flex().flex_shrink_0().child(
14168                StyledText::new(text_without_backticks.clone()).with_highlights(
14169                    &text_style,
14170                    code_ranges.iter().map(|range| {
14171                        (
14172                            range.clone(),
14173                            HighlightStyle {
14174                                font_weight: Some(FontWeight::BOLD),
14175                                ..Default::default()
14176                            },
14177                        )
14178                    }),
14179                ),
14180            ))
14181            .into_any_element()
14182    })
14183}
14184
14185pub fn highlight_diagnostic_message(
14186    diagnostic: &Diagnostic,
14187    mut max_message_rows: Option<u8>,
14188) -> (SharedString, Vec<Range<usize>>) {
14189    let mut text_without_backticks = String::new();
14190    let mut code_ranges = Vec::new();
14191
14192    if let Some(source) = &diagnostic.source {
14193        text_without_backticks.push_str(source);
14194        code_ranges.push(0..source.len());
14195        text_without_backticks.push_str(": ");
14196    }
14197
14198    let mut prev_offset = 0;
14199    let mut in_code_block = false;
14200    let has_row_limit = max_message_rows.is_some();
14201    let mut newline_indices = diagnostic
14202        .message
14203        .match_indices('\n')
14204        .filter(|_| has_row_limit)
14205        .map(|(ix, _)| ix)
14206        .fuse()
14207        .peekable();
14208
14209    for (quote_ix, _) in diagnostic
14210        .message
14211        .match_indices('`')
14212        .chain([(diagnostic.message.len(), "")])
14213    {
14214        let mut first_newline_ix = None;
14215        let mut last_newline_ix = None;
14216        while let Some(newline_ix) = newline_indices.peek() {
14217            if *newline_ix < quote_ix {
14218                if first_newline_ix.is_none() {
14219                    first_newline_ix = Some(*newline_ix);
14220                }
14221                last_newline_ix = Some(*newline_ix);
14222
14223                if let Some(rows_left) = &mut max_message_rows {
14224                    if *rows_left == 0 {
14225                        break;
14226                    } else {
14227                        *rows_left -= 1;
14228                    }
14229                }
14230                let _ = newline_indices.next();
14231            } else {
14232                break;
14233            }
14234        }
14235        let prev_len = text_without_backticks.len();
14236        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14237        text_without_backticks.push_str(new_text);
14238        if in_code_block {
14239            code_ranges.push(prev_len..text_without_backticks.len());
14240        }
14241        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14242        in_code_block = !in_code_block;
14243        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14244            text_without_backticks.push_str("...");
14245            break;
14246        }
14247    }
14248
14249    (text_without_backticks.into(), code_ranges)
14250}
14251
14252fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14253    match severity {
14254        DiagnosticSeverity::ERROR => colors.error,
14255        DiagnosticSeverity::WARNING => colors.warning,
14256        DiagnosticSeverity::INFORMATION => colors.info,
14257        DiagnosticSeverity::HINT => colors.info,
14258        _ => colors.ignored,
14259    }
14260}
14261
14262pub fn styled_runs_for_code_label<'a>(
14263    label: &'a CodeLabel,
14264    syntax_theme: &'a theme::SyntaxTheme,
14265) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14266    let fade_out = HighlightStyle {
14267        fade_out: Some(0.35),
14268        ..Default::default()
14269    };
14270
14271    let mut prev_end = label.filter_range.end;
14272    label
14273        .runs
14274        .iter()
14275        .enumerate()
14276        .flat_map(move |(ix, (range, highlight_id))| {
14277            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14278                style
14279            } else {
14280                return Default::default();
14281            };
14282            let mut muted_style = style;
14283            muted_style.highlight(fade_out);
14284
14285            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14286            if range.start >= label.filter_range.end {
14287                if range.start > prev_end {
14288                    runs.push((prev_end..range.start, fade_out));
14289                }
14290                runs.push((range.clone(), muted_style));
14291            } else if range.end <= label.filter_range.end {
14292                runs.push((range.clone(), style));
14293            } else {
14294                runs.push((range.start..label.filter_range.end, style));
14295                runs.push((label.filter_range.end..range.end, muted_style));
14296            }
14297            prev_end = cmp::max(prev_end, range.end);
14298
14299            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14300                runs.push((prev_end..label.text.len(), fade_out));
14301            }
14302
14303            runs
14304        })
14305}
14306
14307pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14308    let mut prev_index = 0;
14309    let mut prev_codepoint: Option<char> = None;
14310    text.char_indices()
14311        .chain([(text.len(), '\0')])
14312        .filter_map(move |(index, codepoint)| {
14313            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14314            let is_boundary = index == text.len()
14315                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14316                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14317            if is_boundary {
14318                let chunk = &text[prev_index..index];
14319                prev_index = index;
14320                Some(chunk)
14321            } else {
14322                None
14323            }
14324        })
14325}
14326
14327pub trait RangeToAnchorExt: Sized {
14328    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14329
14330    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14331        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14332        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14333    }
14334}
14335
14336impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14337    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14338        let start_offset = self.start.to_offset(snapshot);
14339        let end_offset = self.end.to_offset(snapshot);
14340        if start_offset == end_offset {
14341            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14342        } else {
14343            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14344        }
14345    }
14346}
14347
14348pub trait RowExt {
14349    fn as_f32(&self) -> f32;
14350
14351    fn next_row(&self) -> Self;
14352
14353    fn previous_row(&self) -> Self;
14354
14355    fn minus(&self, other: Self) -> u32;
14356}
14357
14358impl RowExt for DisplayRow {
14359    fn as_f32(&self) -> f32 {
14360        self.0 as f32
14361    }
14362
14363    fn next_row(&self) -> Self {
14364        Self(self.0 + 1)
14365    }
14366
14367    fn previous_row(&self) -> Self {
14368        Self(self.0.saturating_sub(1))
14369    }
14370
14371    fn minus(&self, other: Self) -> u32 {
14372        self.0 - other.0
14373    }
14374}
14375
14376impl RowExt for MultiBufferRow {
14377    fn as_f32(&self) -> f32 {
14378        self.0 as f32
14379    }
14380
14381    fn next_row(&self) -> Self {
14382        Self(self.0 + 1)
14383    }
14384
14385    fn previous_row(&self) -> Self {
14386        Self(self.0.saturating_sub(1))
14387    }
14388
14389    fn minus(&self, other: Self) -> u32 {
14390        self.0 - other.0
14391    }
14392}
14393
14394trait RowRangeExt {
14395    type Row;
14396
14397    fn len(&self) -> usize;
14398
14399    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14400}
14401
14402impl RowRangeExt for Range<MultiBufferRow> {
14403    type Row = MultiBufferRow;
14404
14405    fn len(&self) -> usize {
14406        (self.end.0 - self.start.0) as usize
14407    }
14408
14409    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14410        (self.start.0..self.end.0).map(MultiBufferRow)
14411    }
14412}
14413
14414impl RowRangeExt for Range<DisplayRow> {
14415    type Row = DisplayRow;
14416
14417    fn len(&self) -> usize {
14418        (self.end.0 - self.start.0) as usize
14419    }
14420
14421    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14422        (self.start.0..self.end.0).map(DisplayRow)
14423    }
14424}
14425
14426fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14427    if hunk.diff_base_byte_range.is_empty() {
14428        DiffHunkStatus::Added
14429    } else if hunk.row_range.is_empty() {
14430        DiffHunkStatus::Removed
14431    } else {
14432        DiffHunkStatus::Modified
14433    }
14434}
14435
14436/// If select range has more than one line, we
14437/// just point the cursor to range.start.
14438fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14439    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14440        range
14441    } else {
14442        range.start..range.start
14443    }
14444}