editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   79    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   80    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion_provider::*;
   90pub use items::MAX_TAB_TITLE_LEN;
   91use itertools::Itertools;
   92use language::{
   93    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   94    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   95    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   96    Point, Selection, SelectionGoal, TransactionId,
   97};
   98use language::{
   99    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  100};
  101use linked_editing_ranges::refresh_linked_ranges;
  102pub use proposed_changes_editor::{
  103    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  104};
  105use similar::{ChangeTag, TextDiff};
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  135use serde::{Deserialize, Serialize};
  136use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  137use smallvec::SmallVec;
  138use snippet::Snippet;
  139use std::{
  140    any::TypeId,
  141    borrow::Cow,
  142    cell::RefCell,
  143    cmp::{self, Ordering, Reverse},
  144    mem,
  145    num::NonZeroU32,
  146    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  147    path::{Path, PathBuf},
  148    rc::Rc,
  149    sync::Arc,
  150    time::{Duration, Instant},
  151};
  152pub use sum_tree::Bias;
  153use sum_tree::TreeMap;
  154use text::{BufferId, OffsetUtf16, Rope};
  155use theme::{
  156    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  157    ThemeColors, ThemeSettings,
  158};
  159use ui::{
  160    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  161    ListItem, Popover, PopoverMenuHandle, Tooltip,
  162};
  163use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  164use workspace::item::{ItemHandle, PreviewTabsSettings};
  165use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  166use workspace::{
  167    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  168};
  169use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  170
  171use crate::hover_links::find_url;
  172use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  173
  174pub const FILE_HEADER_HEIGHT: u32 = 2;
  175pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  176pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  177pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  178const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  179const MAX_LINE_LEN: usize = 1024;
  180const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  181const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  182pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  183#[doc(hidden)]
  184pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  185#[doc(hidden)]
  186pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  187
  188pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  189pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  190
  191pub fn render_parsed_markdown(
  192    element_id: impl Into<ElementId>,
  193    parsed: &language::ParsedMarkdown,
  194    editor_style: &EditorStyle,
  195    workspace: Option<WeakView<Workspace>>,
  196    cx: &mut WindowContext,
  197) -> InteractiveText {
  198    let code_span_background_color = cx
  199        .theme()
  200        .colors()
  201        .editor_document_highlight_read_background;
  202
  203    let highlights = gpui::combine_highlights(
  204        parsed.highlights.iter().filter_map(|(range, highlight)| {
  205            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  206            Some((range.clone(), highlight))
  207        }),
  208        parsed
  209            .regions
  210            .iter()
  211            .zip(&parsed.region_ranges)
  212            .filter_map(|(region, range)| {
  213                if region.code {
  214                    Some((
  215                        range.clone(),
  216                        HighlightStyle {
  217                            background_color: Some(code_span_background_color),
  218                            ..Default::default()
  219                        },
  220                    ))
  221                } else {
  222                    None
  223                }
  224            }),
  225    );
  226
  227    let mut links = Vec::new();
  228    let mut link_ranges = Vec::new();
  229    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  230        if let Some(link) = region.link.clone() {
  231            links.push(link);
  232            link_ranges.push(range.clone());
  233        }
  234    }
  235
  236    InteractiveText::new(
  237        element_id,
  238        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  239    )
  240    .on_click(link_ranges, move |clicked_range_ix, cx| {
  241        match &links[clicked_range_ix] {
  242            markdown::Link::Web { url } => cx.open_url(url),
  243            markdown::Link::Path { path } => {
  244                if let Some(workspace) = &workspace {
  245                    _ = workspace.update(cx, |workspace, cx| {
  246                        workspace.open_abs_path(path.clone(), false, cx).detach();
  247                    });
  248                }
  249            }
  250        }
  251    })
  252}
  253
  254#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  255pub(crate) enum InlayId {
  256    Suggestion(usize),
  257    Hint(usize),
  258}
  259
  260impl InlayId {
  261    fn id(&self) -> usize {
  262        match self {
  263            Self::Suggestion(id) => *id,
  264            Self::Hint(id) => *id,
  265        }
  266    }
  267}
  268
  269enum DiffRowHighlight {}
  270enum DocumentHighlightRead {}
  271enum DocumentHighlightWrite {}
  272enum InputComposition {}
  273
  274#[derive(Copy, Clone, PartialEq, Eq)]
  275pub enum Direction {
  276    Prev,
  277    Next,
  278}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334}
  335
  336pub struct SearchWithinRange;
  337
  338trait InvalidationRegion {
  339    fn ranges(&self) -> &[Range<Anchor>];
  340}
  341
  342#[derive(Clone, Debug, PartialEq)]
  343pub enum SelectPhase {
  344    Begin {
  345        position: DisplayPoint,
  346        add: bool,
  347        click_count: usize,
  348    },
  349    BeginColumnar {
  350        position: DisplayPoint,
  351        reset: bool,
  352        goal_column: u32,
  353    },
  354    Extend {
  355        position: DisplayPoint,
  356        click_count: usize,
  357    },
  358    Update {
  359        position: DisplayPoint,
  360        goal_column: u32,
  361        scroll_delta: gpui::Point<f32>,
  362    },
  363    End,
  364}
  365
  366#[derive(Clone, Debug)]
  367pub enum SelectMode {
  368    Character,
  369    Word(Range<Anchor>),
  370    Line(Range<Anchor>),
  371    All,
  372}
  373
  374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  375pub enum EditorMode {
  376    SingleLine { auto_width: bool },
  377    AutoHeight { max_lines: usize },
  378    Full,
  379}
  380
  381#[derive(Copy, Clone, Debug)]
  382pub enum SoftWrap {
  383    /// Prefer not to wrap at all.
  384    ///
  385    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  386    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  387    GitDiff,
  388    /// Prefer a single line generally, unless an overly long line is encountered.
  389    None,
  390    /// Soft wrap lines that exceed the editor width.
  391    EditorWidth,
  392    /// Soft wrap lines at the preferred line length.
  393    Column(u32),
  394    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  395    Bounded(u32),
  396}
  397
  398#[derive(Clone)]
  399pub struct EditorStyle {
  400    pub background: Hsla,
  401    pub local_player: PlayerColor,
  402    pub text: TextStyle,
  403    pub scrollbar_width: Pixels,
  404    pub syntax: Arc<SyntaxTheme>,
  405    pub status: StatusColors,
  406    pub inlay_hints_style: HighlightStyle,
  407    pub suggestions_style: HighlightStyle,
  408    pub unnecessary_code_fade: f32,
  409}
  410
  411impl Default for EditorStyle {
  412    fn default() -> Self {
  413        Self {
  414            background: Hsla::default(),
  415            local_player: PlayerColor::default(),
  416            text: TextStyle::default(),
  417            scrollbar_width: Pixels::default(),
  418            syntax: Default::default(),
  419            // HACK: Status colors don't have a real default.
  420            // We should look into removing the status colors from the editor
  421            // style and retrieve them directly from the theme.
  422            status: StatusColors::dark(),
  423            inlay_hints_style: HighlightStyle::default(),
  424            suggestions_style: HighlightStyle::default(),
  425            unnecessary_code_fade: Default::default(),
  426        }
  427    }
  428}
  429
  430pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  431    let show_background = language_settings::language_settings(None, None, cx)
  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
  550    project: Option<Model<Project>>,
  551    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  552    completion_provider: Option<Box<dyn CompletionProvider>>,
  553    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  554    blink_manager: Model<BlinkManager>,
  555    show_cursor_names: bool,
  556    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  557    pub show_local_selections: bool,
  558    mode: EditorMode,
  559    show_breadcrumbs: bool,
  560    show_gutter: bool,
  561    show_line_numbers: Option<bool>,
  562    use_relative_line_numbers: Option<bool>,
  563    show_git_diff_gutter: Option<bool>,
  564    show_code_actions: Option<bool>,
  565    show_runnables: Option<bool>,
  566    show_wrap_guides: Option<bool>,
  567    show_indent_guides: Option<bool>,
  568    placeholder_text: Option<Arc<str>>,
  569    highlight_order: usize,
  570    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  571    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  572    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  573    scrollbar_marker_state: ScrollbarMarkerState,
  574    active_indent_guides_state: ActiveIndentGuidesState,
  575    nav_history: Option<ItemNavHistory>,
  576    context_menu: RwLock<Option<ContextMenu>>,
  577    mouse_context_menu: Option<MouseContextMenu>,
  578    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  579    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  580    signature_help_state: SignatureHelpState,
  581    auto_signature_help: Option<bool>,
  582    find_all_references_task_sources: Vec<Anchor>,
  583    next_completion_id: CompletionId,
  584    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  585    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  586    code_actions_task: Option<Task<Result<()>>>,
  587    document_highlights_task: Option<Task<()>>,
  588    linked_editing_range_task: Option<Task<Option<()>>>,
  589    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  590    pending_rename: Option<RenameState>,
  591    searchable: bool,
  592    cursor_shape: CursorShape,
  593    current_line_highlight: Option<CurrentLineHighlight>,
  594    collapse_matches: bool,
  595    autoindent_mode: Option<AutoindentMode>,
  596    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  597    input_enabled: bool,
  598    use_modal_editing: bool,
  599    read_only: bool,
  600    leader_peer_id: Option<PeerId>,
  601    remote_id: Option<ViewId>,
  602    hover_state: HoverState,
  603    gutter_hovered: bool,
  604    hovered_link_state: Option<HoveredLinkState>,
  605    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  606    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  607    active_inline_completion: Option<CompletionState>,
  608    // enable_inline_completions is a switch that Vim can use to disable
  609    // inline completions based on its mode.
  610    enable_inline_completions: bool,
  611    show_inline_completions_override: Option<bool>,
  612    inlay_hint_cache: InlayHintCache,
  613    expanded_hunks: ExpandedHunks,
  614    next_inlay_id: usize,
  615    _subscriptions: Vec<Subscription>,
  616    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  617    gutter_dimensions: GutterDimensions,
  618    style: Option<EditorStyle>,
  619    text_style_refinement: Option<TextStyleRefinement>,
  620    next_editor_action_id: EditorActionId,
  621    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  622    use_autoclose: bool,
  623    use_auto_surround: bool,
  624    auto_replace_emoji_shortcode: bool,
  625    show_git_blame_gutter: bool,
  626    show_git_blame_inline: bool,
  627    show_git_blame_inline_delay_task: Option<Task<()>>,
  628    git_blame_inline_enabled: bool,
  629    serialize_dirty_buffers: bool,
  630    show_selection_menu: Option<bool>,
  631    blame: Option<Model<GitBlame>>,
  632    blame_subscription: Option<Subscription>,
  633    custom_context_menu: Option<
  634        Box<
  635            dyn 'static
  636                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  637        >,
  638    >,
  639    last_bounds: Option<Bounds<Pixels>>,
  640    expect_bounds_change: Option<Bounds<Pixels>>,
  641    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  642    tasks_update_task: Option<Task<()>>,
  643    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  644    breadcrumb_header: Option<String>,
  645    focused_block: Option<FocusedBlock>,
  646    next_scroll_position: NextScrollCursorCenterTopBottom,
  647    addons: HashMap<TypeId, Box<dyn Addon>>,
  648    _scroll_cursor_center_top_bottom_task: Task<()>,
  649}
  650
  651#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  652enum NextScrollCursorCenterTopBottom {
  653    #[default]
  654    Center,
  655    Top,
  656    Bottom,
  657}
  658
  659impl NextScrollCursorCenterTopBottom {
  660    fn next(&self) -> Self {
  661        match self {
  662            Self::Center => Self::Top,
  663            Self::Top => Self::Bottom,
  664            Self::Bottom => Self::Center,
  665        }
  666    }
  667}
  668
  669#[derive(Clone)]
  670pub struct EditorSnapshot {
  671    pub mode: EditorMode,
  672    show_gutter: bool,
  673    show_line_numbers: Option<bool>,
  674    show_git_diff_gutter: Option<bool>,
  675    show_code_actions: Option<bool>,
  676    show_runnables: Option<bool>,
  677    git_blame_gutter_max_author_length: Option<usize>,
  678    pub display_snapshot: DisplaySnapshot,
  679    pub placeholder_text: Option<Arc<str>>,
  680    is_focused: bool,
  681    scroll_anchor: ScrollAnchor,
  682    ongoing_scroll: OngoingScroll,
  683    current_line_highlight: CurrentLineHighlight,
  684    gutter_hovered: bool,
  685}
  686
  687const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  688
  689#[derive(Default, Debug, Clone, Copy)]
  690pub struct GutterDimensions {
  691    pub left_padding: Pixels,
  692    pub right_padding: Pixels,
  693    pub width: Pixels,
  694    pub margin: Pixels,
  695    pub git_blame_entries_width: Option<Pixels>,
  696}
  697
  698impl GutterDimensions {
  699    /// The full width of the space taken up by the gutter.
  700    pub fn full_width(&self) -> Pixels {
  701        self.margin + self.width
  702    }
  703
  704    /// The width of the space reserved for the fold indicators,
  705    /// use alongside 'justify_end' and `gutter_width` to
  706    /// right align content with the line numbers
  707    pub fn fold_area_width(&self) -> Pixels {
  708        self.margin + self.right_padding
  709    }
  710}
  711
  712#[derive(Debug)]
  713pub struct RemoteSelection {
  714    pub replica_id: ReplicaId,
  715    pub selection: Selection<Anchor>,
  716    pub cursor_shape: CursorShape,
  717    pub peer_id: PeerId,
  718    pub line_mode: bool,
  719    pub participant_index: Option<ParticipantIndex>,
  720    pub user_name: Option<SharedString>,
  721}
  722
  723#[derive(Clone, Debug)]
  724struct SelectionHistoryEntry {
  725    selections: Arc<[Selection<Anchor>]>,
  726    select_next_state: Option<SelectNextState>,
  727    select_prev_state: Option<SelectNextState>,
  728    add_selections_state: Option<AddSelectionsState>,
  729}
  730
  731enum SelectionHistoryMode {
  732    Normal,
  733    Undoing,
  734    Redoing,
  735}
  736
  737#[derive(Clone, PartialEq, Eq, Hash)]
  738struct HoveredCursor {
  739    replica_id: u16,
  740    selection_id: usize,
  741}
  742
  743impl Default for SelectionHistoryMode {
  744    fn default() -> Self {
  745        Self::Normal
  746    }
  747}
  748
  749#[derive(Default)]
  750struct SelectionHistory {
  751    #[allow(clippy::type_complexity)]
  752    selections_by_transaction:
  753        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  754    mode: SelectionHistoryMode,
  755    undo_stack: VecDeque<SelectionHistoryEntry>,
  756    redo_stack: VecDeque<SelectionHistoryEntry>,
  757}
  758
  759impl SelectionHistory {
  760    fn insert_transaction(
  761        &mut self,
  762        transaction_id: TransactionId,
  763        selections: Arc<[Selection<Anchor>]>,
  764    ) {
  765        self.selections_by_transaction
  766            .insert(transaction_id, (selections, None));
  767    }
  768
  769    #[allow(clippy::type_complexity)]
  770    fn transaction(
  771        &self,
  772        transaction_id: TransactionId,
  773    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  774        self.selections_by_transaction.get(&transaction_id)
  775    }
  776
  777    #[allow(clippy::type_complexity)]
  778    fn transaction_mut(
  779        &mut self,
  780        transaction_id: TransactionId,
  781    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  782        self.selections_by_transaction.get_mut(&transaction_id)
  783    }
  784
  785    fn push(&mut self, entry: SelectionHistoryEntry) {
  786        if !entry.selections.is_empty() {
  787            match self.mode {
  788                SelectionHistoryMode::Normal => {
  789                    self.push_undo(entry);
  790                    self.redo_stack.clear();
  791                }
  792                SelectionHistoryMode::Undoing => self.push_redo(entry),
  793                SelectionHistoryMode::Redoing => self.push_undo(entry),
  794            }
  795        }
  796    }
  797
  798    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  799        if self
  800            .undo_stack
  801            .back()
  802            .map_or(true, |e| e.selections != entry.selections)
  803        {
  804            self.undo_stack.push_back(entry);
  805            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  806                self.undo_stack.pop_front();
  807            }
  808        }
  809    }
  810
  811    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  812        if self
  813            .redo_stack
  814            .back()
  815            .map_or(true, |e| e.selections != entry.selections)
  816        {
  817            self.redo_stack.push_back(entry);
  818            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  819                self.redo_stack.pop_front();
  820            }
  821        }
  822    }
  823}
  824
  825struct RowHighlight {
  826    index: usize,
  827    range: Range<Anchor>,
  828    color: Hsla,
  829    should_autoscroll: bool,
  830}
  831
  832#[derive(Clone, Debug)]
  833struct AddSelectionsState {
  834    above: bool,
  835    stack: Vec<usize>,
  836}
  837
  838#[derive(Clone)]
  839struct SelectNextState {
  840    query: AhoCorasick,
  841    wordwise: bool,
  842    done: bool,
  843}
  844
  845impl std::fmt::Debug for SelectNextState {
  846    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  847        f.debug_struct(std::any::type_name::<Self>())
  848            .field("wordwise", &self.wordwise)
  849            .field("done", &self.done)
  850            .finish()
  851    }
  852}
  853
  854#[derive(Debug)]
  855struct AutocloseRegion {
  856    selection_id: usize,
  857    range: Range<Anchor>,
  858    pair: BracketPair,
  859}
  860
  861#[derive(Debug)]
  862struct SnippetState {
  863    ranges: Vec<Vec<Range<Anchor>>>,
  864    active_index: usize,
  865}
  866
  867#[doc(hidden)]
  868pub struct RenameState {
  869    pub range: Range<Anchor>,
  870    pub old_name: Arc<str>,
  871    pub editor: View<Editor>,
  872    block_id: CustomBlockId,
  873}
  874
  875struct InvalidationStack<T>(Vec<T>);
  876
  877struct RegisteredInlineCompletionProvider {
  878    provider: Arc<dyn InlineCompletionProviderHandle>,
  879    _subscription: Subscription,
  880}
  881
  882enum ContextMenu {
  883    Completions(CompletionsMenu),
  884    CodeActions(CodeActionsMenu),
  885}
  886
  887impl ContextMenu {
  888    fn select_first(
  889        &mut self,
  890        provider: Option<&dyn CompletionProvider>,
  891        cx: &mut ViewContext<Editor>,
  892    ) -> bool {
  893        if self.visible() {
  894            match self {
  895                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  896                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  897            }
  898            true
  899        } else {
  900            false
  901        }
  902    }
  903
  904    fn select_prev(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_next(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_last(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn visible(&self) -> bool {
  953        match self {
  954            ContextMenu::Completions(menu) => menu.visible(),
  955            ContextMenu::CodeActions(menu) => menu.visible(),
  956        }
  957    }
  958
  959    fn render(
  960        &self,
  961        cursor_position: DisplayPoint,
  962        style: &EditorStyle,
  963        max_height: Pixels,
  964        workspace: Option<WeakView<Workspace>>,
  965        cx: &mut ViewContext<Editor>,
  966    ) -> (ContextMenuOrigin, AnyElement) {
  967        match self {
  968            ContextMenu::Completions(menu) => (
  969                ContextMenuOrigin::EditorPoint(cursor_position),
  970                menu.render(style, max_height, workspace, cx),
  971            ),
  972            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  973        }
  974    }
  975}
  976
  977enum ContextMenuOrigin {
  978    EditorPoint(DisplayPoint),
  979    GutterIndicator(DisplayRow),
  980}
  981
  982#[derive(Clone)]
  983struct CompletionsMenu {
  984    id: CompletionId,
  985    sort_completions: bool,
  986    initial_position: Anchor,
  987    buffer: Model<Buffer>,
  988    completions: Arc<RwLock<Box<[Completion]>>>,
  989    match_candidates: Arc<[StringMatchCandidate]>,
  990    matches: Arc<[StringMatch]>,
  991    selected_item: usize,
  992    scroll_handle: UniformListScrollHandle,
  993    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  994}
  995
  996impl CompletionsMenu {
  997    fn select_first(
  998        &mut self,
  999        provider: Option<&dyn CompletionProvider>,
 1000        cx: &mut ViewContext<Editor>,
 1001    ) {
 1002        self.selected_item = 0;
 1003        self.scroll_handle.scroll_to_item(self.selected_item);
 1004        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1005        cx.notify();
 1006    }
 1007
 1008    fn select_prev(
 1009        &mut self,
 1010        provider: Option<&dyn CompletionProvider>,
 1011        cx: &mut ViewContext<Editor>,
 1012    ) {
 1013        if self.selected_item > 0 {
 1014            self.selected_item -= 1;
 1015        } else {
 1016            self.selected_item = self.matches.len() - 1;
 1017        }
 1018        self.scroll_handle.scroll_to_item(self.selected_item);
 1019        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1020        cx.notify();
 1021    }
 1022
 1023    fn select_next(
 1024        &mut self,
 1025        provider: Option<&dyn CompletionProvider>,
 1026        cx: &mut ViewContext<Editor>,
 1027    ) {
 1028        if self.selected_item + 1 < self.matches.len() {
 1029            self.selected_item += 1;
 1030        } else {
 1031            self.selected_item = 0;
 1032        }
 1033        self.scroll_handle.scroll_to_item(self.selected_item);
 1034        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1035        cx.notify();
 1036    }
 1037
 1038    fn select_last(
 1039        &mut self,
 1040        provider: Option<&dyn CompletionProvider>,
 1041        cx: &mut ViewContext<Editor>,
 1042    ) {
 1043        self.selected_item = self.matches.len() - 1;
 1044        self.scroll_handle.scroll_to_item(self.selected_item);
 1045        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1046        cx.notify();
 1047    }
 1048
 1049    fn pre_resolve_completion_documentation(
 1050        buffer: Model<Buffer>,
 1051        completions: Arc<RwLock<Box<[Completion]>>>,
 1052        matches: Arc<[StringMatch]>,
 1053        editor: &Editor,
 1054        cx: &mut ViewContext<Editor>,
 1055    ) -> Task<()> {
 1056        let settings = EditorSettings::get_global(cx);
 1057        if !settings.show_completion_documentation {
 1058            return Task::ready(());
 1059        }
 1060
 1061        let Some(provider) = editor.completion_provider.as_ref() else {
 1062            return Task::ready(());
 1063        };
 1064
 1065        let resolve_task = provider.resolve_completions(
 1066            buffer,
 1067            matches.iter().map(|m| m.candidate_id).collect(),
 1068            completions.clone(),
 1069            cx,
 1070        );
 1071
 1072        cx.spawn(move |this, mut cx| async move {
 1073            if let Some(true) = resolve_task.await.log_err() {
 1074                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1075            }
 1076        })
 1077    }
 1078
 1079    fn attempt_resolve_selected_completion_documentation(
 1080        &mut self,
 1081        provider: Option<&dyn CompletionProvider>,
 1082        cx: &mut ViewContext<Editor>,
 1083    ) {
 1084        let settings = EditorSettings::get_global(cx);
 1085        if !settings.show_completion_documentation {
 1086            return;
 1087        }
 1088
 1089        let completion_index = self.matches[self.selected_item].candidate_id;
 1090        let Some(provider) = provider else {
 1091            return;
 1092        };
 1093
 1094        let resolve_task = provider.resolve_completions(
 1095            self.buffer.clone(),
 1096            vec![completion_index],
 1097            self.completions.clone(),
 1098            cx,
 1099        );
 1100
 1101        let delay_ms =
 1102            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1103        let delay = Duration::from_millis(delay_ms);
 1104
 1105        self.selected_completion_documentation_resolve_debounce
 1106            .lock()
 1107            .fire_new(delay, cx, |_, cx| {
 1108                cx.spawn(move |this, mut cx| async move {
 1109                    if let Some(true) = resolve_task.await.log_err() {
 1110                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1111                    }
 1112                })
 1113            });
 1114    }
 1115
 1116    fn visible(&self) -> bool {
 1117        !self.matches.is_empty()
 1118    }
 1119
 1120    fn render(
 1121        &self,
 1122        style: &EditorStyle,
 1123        max_height: Pixels,
 1124        workspace: Option<WeakView<Workspace>>,
 1125        cx: &mut ViewContext<Editor>,
 1126    ) -> AnyElement {
 1127        let settings = EditorSettings::get_global(cx);
 1128        let show_completion_documentation = settings.show_completion_documentation;
 1129
 1130        let widest_completion_ix = self
 1131            .matches
 1132            .iter()
 1133            .enumerate()
 1134            .max_by_key(|(_, mat)| {
 1135                let completions = self.completions.read();
 1136                let completion = &completions[mat.candidate_id];
 1137                let documentation = &completion.documentation;
 1138
 1139                let mut len = completion.label.text.chars().count();
 1140                if let Some(Documentation::SingleLine(text)) = documentation {
 1141                    if show_completion_documentation {
 1142                        len += text.chars().count();
 1143                    }
 1144                }
 1145
 1146                len
 1147            })
 1148            .map(|(ix, _)| ix);
 1149
 1150        let completions = self.completions.clone();
 1151        let matches = self.matches.clone();
 1152        let selected_item = self.selected_item;
 1153        let style = style.clone();
 1154
 1155        let multiline_docs = if show_completion_documentation {
 1156            let mat = &self.matches[selected_item];
 1157            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1158                Some(Documentation::MultiLinePlainText(text)) => {
 1159                    Some(div().child(SharedString::from(text.clone())))
 1160                }
 1161                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1162                    Some(div().child(render_parsed_markdown(
 1163                        "completions_markdown",
 1164                        parsed,
 1165                        &style,
 1166                        workspace,
 1167                        cx,
 1168                    )))
 1169                }
 1170                _ => None,
 1171            };
 1172            multiline_docs.map(|div| {
 1173                div.id("multiline_docs")
 1174                    .max_h(max_height)
 1175                    .flex_1()
 1176                    .px_1p5()
 1177                    .py_1()
 1178                    .min_w(px(260.))
 1179                    .max_w(px(640.))
 1180                    .w(px(500.))
 1181                    .overflow_y_scroll()
 1182                    .occlude()
 1183            })
 1184        } else {
 1185            None
 1186        };
 1187
 1188        let list = uniform_list(
 1189            cx.view().clone(),
 1190            "completions",
 1191            matches.len(),
 1192            move |_editor, range, cx| {
 1193                let start_ix = range.start;
 1194                let completions_guard = completions.read();
 1195
 1196                matches[range]
 1197                    .iter()
 1198                    .enumerate()
 1199                    .map(|(ix, mat)| {
 1200                        let item_ix = start_ix + ix;
 1201                        let candidate_id = mat.candidate_id;
 1202                        let completion = &completions_guard[candidate_id];
 1203
 1204                        let documentation = if show_completion_documentation {
 1205                            &completion.documentation
 1206                        } else {
 1207                            &None
 1208                        };
 1209
 1210                        let highlights = gpui::combine_highlights(
 1211                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1212                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1213                                |(range, mut highlight)| {
 1214                                    // Ignore font weight for syntax highlighting, as we'll use it
 1215                                    // for fuzzy matches.
 1216                                    highlight.font_weight = None;
 1217
 1218                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1219                                        highlight.strikethrough = Some(StrikethroughStyle {
 1220                                            thickness: 1.0.into(),
 1221                                            ..Default::default()
 1222                                        });
 1223                                        highlight.color = Some(cx.theme().colors().text_muted);
 1224                                    }
 1225
 1226                                    (range, highlight)
 1227                                },
 1228                            ),
 1229                        );
 1230                        let completion_label = StyledText::new(completion.label.text.clone())
 1231                            .with_highlights(&style.text, highlights);
 1232                        let documentation_label =
 1233                            if let Some(Documentation::SingleLine(text)) = documentation {
 1234                                if text.trim().is_empty() {
 1235                                    None
 1236                                } else {
 1237                                    Some(
 1238                                        Label::new(text.clone())
 1239                                            .ml_4()
 1240                                            .size(LabelSize::Small)
 1241                                            .color(Color::Muted),
 1242                                    )
 1243                                }
 1244                            } else {
 1245                                None
 1246                            };
 1247
 1248                        let color_swatch = completion
 1249                            .color()
 1250                            .map(|color| div().size_4().bg(color).rounded_sm());
 1251
 1252                        div().min_w(px(220.)).max_w(px(540.)).child(
 1253                            ListItem::new(mat.candidate_id)
 1254                                .inset(true)
 1255                                .selected(item_ix == selected_item)
 1256                                .on_click(cx.listener(move |editor, _event, cx| {
 1257                                    cx.stop_propagation();
 1258                                    if let Some(task) = editor.confirm_completion(
 1259                                        &ConfirmCompletion {
 1260                                            item_ix: Some(item_ix),
 1261                                        },
 1262                                        cx,
 1263                                    ) {
 1264                                        task.detach_and_log_err(cx)
 1265                                    }
 1266                                }))
 1267                                .start_slot::<Div>(color_swatch)
 1268                                .child(h_flex().overflow_hidden().child(completion_label))
 1269                                .end_slot::<Label>(documentation_label),
 1270                        )
 1271                    })
 1272                    .collect()
 1273            },
 1274        )
 1275        .occlude()
 1276        .max_h(max_height)
 1277        .track_scroll(self.scroll_handle.clone())
 1278        .with_width_from_item(widest_completion_ix)
 1279        .with_sizing_behavior(ListSizingBehavior::Infer);
 1280
 1281        Popover::new()
 1282            .child(list)
 1283            .when_some(multiline_docs, |popover, multiline_docs| {
 1284                popover.aside(multiline_docs)
 1285            })
 1286            .into_any_element()
 1287    }
 1288
 1289    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1290        let mut matches = if let Some(query) = query {
 1291            fuzzy::match_strings(
 1292                &self.match_candidates,
 1293                query,
 1294                query.chars().any(|c| c.is_uppercase()),
 1295                100,
 1296                &Default::default(),
 1297                executor,
 1298            )
 1299            .await
 1300        } else {
 1301            self.match_candidates
 1302                .iter()
 1303                .enumerate()
 1304                .map(|(candidate_id, candidate)| StringMatch {
 1305                    candidate_id,
 1306                    score: Default::default(),
 1307                    positions: Default::default(),
 1308                    string: candidate.string.clone(),
 1309                })
 1310                .collect()
 1311        };
 1312
 1313        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1314        if let Some(query) = query {
 1315            if let Some(query_start) = query.chars().next() {
 1316                matches.retain(|string_match| {
 1317                    split_words(&string_match.string).any(|word| {
 1318                        // Check that the first codepoint of the word as lowercase matches the first
 1319                        // codepoint of the query as lowercase
 1320                        word.chars()
 1321                            .flat_map(|codepoint| codepoint.to_lowercase())
 1322                            .zip(query_start.to_lowercase())
 1323                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1324                    })
 1325                });
 1326            }
 1327        }
 1328
 1329        let completions = self.completions.read();
 1330        if self.sort_completions {
 1331            matches.sort_unstable_by_key(|mat| {
 1332                // We do want to strike a balance here between what the language server tells us
 1333                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1334                // `Creat` and there is a local variable called `CreateComponent`).
 1335                // So what we do is: we bucket all matches into two buckets
 1336                // - Strong matches
 1337                // - Weak matches
 1338                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1339                // and the Weak matches are the rest.
 1340                //
 1341                // For the strong matches, we sort by the language-servers score first and for the weak
 1342                // matches, we prefer our fuzzy finder first.
 1343                //
 1344                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1345                // us into account when it's obviously a bad match.
 1346
 1347                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1348                enum MatchScore<'a> {
 1349                    Strong {
 1350                        sort_text: Option<&'a str>,
 1351                        score: Reverse<OrderedFloat<f64>>,
 1352                        sort_key: (usize, &'a str),
 1353                    },
 1354                    Weak {
 1355                        score: Reverse<OrderedFloat<f64>>,
 1356                        sort_text: Option<&'a str>,
 1357                        sort_key: (usize, &'a str),
 1358                    },
 1359                }
 1360
 1361                let completion = &completions[mat.candidate_id];
 1362                let sort_key = completion.sort_key();
 1363                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1364                let score = Reverse(OrderedFloat(mat.score));
 1365
 1366                if mat.score >= 0.2 {
 1367                    MatchScore::Strong {
 1368                        sort_text,
 1369                        score,
 1370                        sort_key,
 1371                    }
 1372                } else {
 1373                    MatchScore::Weak {
 1374                        score,
 1375                        sort_text,
 1376                        sort_key,
 1377                    }
 1378                }
 1379            });
 1380        }
 1381
 1382        for mat in &mut matches {
 1383            let completion = &completions[mat.candidate_id];
 1384            mat.string.clone_from(&completion.label.text);
 1385            for position in &mut mat.positions {
 1386                *position += completion.label.filter_range.start;
 1387            }
 1388        }
 1389        drop(completions);
 1390
 1391        self.matches = matches.into();
 1392        self.selected_item = 0;
 1393    }
 1394}
 1395
 1396struct AvailableCodeAction {
 1397    excerpt_id: ExcerptId,
 1398    action: CodeAction,
 1399    provider: Arc<dyn CodeActionProvider>,
 1400}
 1401
 1402#[derive(Clone)]
 1403struct CodeActionContents {
 1404    tasks: Option<Arc<ResolvedTasks>>,
 1405    actions: Option<Arc<[AvailableCodeAction]>>,
 1406}
 1407
 1408impl CodeActionContents {
 1409    fn len(&self) -> usize {
 1410        match (&self.tasks, &self.actions) {
 1411            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1412            (Some(tasks), None) => tasks.templates.len(),
 1413            (None, Some(actions)) => actions.len(),
 1414            (None, None) => 0,
 1415        }
 1416    }
 1417
 1418    fn is_empty(&self) -> bool {
 1419        match (&self.tasks, &self.actions) {
 1420            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1421            (Some(tasks), None) => tasks.templates.is_empty(),
 1422            (None, Some(actions)) => actions.is_empty(),
 1423            (None, None) => true,
 1424        }
 1425    }
 1426
 1427    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1428        self.tasks
 1429            .iter()
 1430            .flat_map(|tasks| {
 1431                tasks
 1432                    .templates
 1433                    .iter()
 1434                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1435            })
 1436            .chain(self.actions.iter().flat_map(|actions| {
 1437                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1438                    excerpt_id: available.excerpt_id,
 1439                    action: available.action.clone(),
 1440                    provider: available.provider.clone(),
 1441                })
 1442            }))
 1443    }
 1444    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1445        match (&self.tasks, &self.actions) {
 1446            (Some(tasks), Some(actions)) => {
 1447                if index < tasks.templates.len() {
 1448                    tasks
 1449                        .templates
 1450                        .get(index)
 1451                        .cloned()
 1452                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1453                } else {
 1454                    actions.get(index - tasks.templates.len()).map(|available| {
 1455                        CodeActionsItem::CodeAction {
 1456                            excerpt_id: available.excerpt_id,
 1457                            action: available.action.clone(),
 1458                            provider: available.provider.clone(),
 1459                        }
 1460                    })
 1461                }
 1462            }
 1463            (Some(tasks), None) => tasks
 1464                .templates
 1465                .get(index)
 1466                .cloned()
 1467                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1468            (None, Some(actions)) => {
 1469                actions
 1470                    .get(index)
 1471                    .map(|available| CodeActionsItem::CodeAction {
 1472                        excerpt_id: available.excerpt_id,
 1473                        action: available.action.clone(),
 1474                        provider: available.provider.clone(),
 1475                    })
 1476            }
 1477            (None, None) => None,
 1478        }
 1479    }
 1480}
 1481
 1482#[allow(clippy::large_enum_variant)]
 1483#[derive(Clone)]
 1484enum CodeActionsItem {
 1485    Task(TaskSourceKind, ResolvedTask),
 1486    CodeAction {
 1487        excerpt_id: ExcerptId,
 1488        action: CodeAction,
 1489        provider: Arc<dyn CodeActionProvider>,
 1490    },
 1491}
 1492
 1493impl CodeActionsItem {
 1494    fn as_task(&self) -> Option<&ResolvedTask> {
 1495        let Self::Task(_, task) = self else {
 1496            return None;
 1497        };
 1498        Some(task)
 1499    }
 1500    fn as_code_action(&self) -> Option<&CodeAction> {
 1501        let Self::CodeAction { action, .. } = self else {
 1502            return None;
 1503        };
 1504        Some(action)
 1505    }
 1506    fn label(&self) -> String {
 1507        match self {
 1508            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1509            Self::Task(_, task) => task.resolved_label.clone(),
 1510        }
 1511    }
 1512}
 1513
 1514struct CodeActionsMenu {
 1515    actions: CodeActionContents,
 1516    buffer: Model<Buffer>,
 1517    selected_item: usize,
 1518    scroll_handle: UniformListScrollHandle,
 1519    deployed_from_indicator: Option<DisplayRow>,
 1520}
 1521
 1522impl CodeActionsMenu {
 1523    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1524        self.selected_item = 0;
 1525        self.scroll_handle.scroll_to_item(self.selected_item);
 1526        cx.notify()
 1527    }
 1528
 1529    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1530        if self.selected_item > 0 {
 1531            self.selected_item -= 1;
 1532        } else {
 1533            self.selected_item = self.actions.len() - 1;
 1534        }
 1535        self.scroll_handle.scroll_to_item(self.selected_item);
 1536        cx.notify();
 1537    }
 1538
 1539    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1540        if self.selected_item + 1 < self.actions.len() {
 1541            self.selected_item += 1;
 1542        } else {
 1543            self.selected_item = 0;
 1544        }
 1545        self.scroll_handle.scroll_to_item(self.selected_item);
 1546        cx.notify();
 1547    }
 1548
 1549    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1550        self.selected_item = self.actions.len() - 1;
 1551        self.scroll_handle.scroll_to_item(self.selected_item);
 1552        cx.notify()
 1553    }
 1554
 1555    fn visible(&self) -> bool {
 1556        !self.actions.is_empty()
 1557    }
 1558
 1559    fn render(
 1560        &self,
 1561        cursor_position: DisplayPoint,
 1562        _style: &EditorStyle,
 1563        max_height: Pixels,
 1564        cx: &mut ViewContext<Editor>,
 1565    ) -> (ContextMenuOrigin, AnyElement) {
 1566        let actions = self.actions.clone();
 1567        let selected_item = self.selected_item;
 1568        let element = uniform_list(
 1569            cx.view().clone(),
 1570            "code_actions_menu",
 1571            self.actions.len(),
 1572            move |_this, range, cx| {
 1573                actions
 1574                    .iter()
 1575                    .skip(range.start)
 1576                    .take(range.end - range.start)
 1577                    .enumerate()
 1578                    .map(|(ix, action)| {
 1579                        let item_ix = range.start + ix;
 1580                        let selected = selected_item == item_ix;
 1581                        let colors = cx.theme().colors();
 1582                        div()
 1583                            .px_1()
 1584                            .rounded_md()
 1585                            .text_color(colors.text)
 1586                            .when(selected, |style| {
 1587                                style
 1588                                    .bg(colors.element_active)
 1589                                    .text_color(colors.text_accent)
 1590                            })
 1591                            .hover(|style| {
 1592                                style
 1593                                    .bg(colors.element_hover)
 1594                                    .text_color(colors.text_accent)
 1595                            })
 1596                            .whitespace_nowrap()
 1597                            .when_some(action.as_code_action(), |this, action| {
 1598                                this.on_mouse_down(
 1599                                    MouseButton::Left,
 1600                                    cx.listener(move |editor, _, cx| {
 1601                                        cx.stop_propagation();
 1602                                        if let Some(task) = editor.confirm_code_action(
 1603                                            &ConfirmCodeAction {
 1604                                                item_ix: Some(item_ix),
 1605                                            },
 1606                                            cx,
 1607                                        ) {
 1608                                            task.detach_and_log_err(cx)
 1609                                        }
 1610                                    }),
 1611                                )
 1612                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1613                                .child(SharedString::from(action.lsp_action.title.clone()))
 1614                            })
 1615                            .when_some(action.as_task(), |this, task| {
 1616                                this.on_mouse_down(
 1617                                    MouseButton::Left,
 1618                                    cx.listener(move |editor, _, cx| {
 1619                                        cx.stop_propagation();
 1620                                        if let Some(task) = editor.confirm_code_action(
 1621                                            &ConfirmCodeAction {
 1622                                                item_ix: Some(item_ix),
 1623                                            },
 1624                                            cx,
 1625                                        ) {
 1626                                            task.detach_and_log_err(cx)
 1627                                        }
 1628                                    }),
 1629                                )
 1630                                .child(SharedString::from(task.resolved_label.clone()))
 1631                            })
 1632                    })
 1633                    .collect()
 1634            },
 1635        )
 1636        .elevation_1(cx)
 1637        .p_1()
 1638        .max_h(max_height)
 1639        .occlude()
 1640        .track_scroll(self.scroll_handle.clone())
 1641        .with_width_from_item(
 1642            self.actions
 1643                .iter()
 1644                .enumerate()
 1645                .max_by_key(|(_, action)| match action {
 1646                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1647                    CodeActionsItem::CodeAction { action, .. } => {
 1648                        action.lsp_action.title.chars().count()
 1649                    }
 1650                })
 1651                .map(|(ix, _)| ix),
 1652        )
 1653        .with_sizing_behavior(ListSizingBehavior::Infer)
 1654        .into_any_element();
 1655
 1656        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1657            ContextMenuOrigin::GutterIndicator(row)
 1658        } else {
 1659            ContextMenuOrigin::EditorPoint(cursor_position)
 1660        };
 1661
 1662        (cursor_position, element)
 1663    }
 1664}
 1665
 1666#[derive(Debug)]
 1667struct ActiveDiagnosticGroup {
 1668    primary_range: Range<Anchor>,
 1669    primary_message: String,
 1670    group_id: usize,
 1671    blocks: HashMap<CustomBlockId, Diagnostic>,
 1672    is_valid: bool,
 1673}
 1674
 1675#[derive(Serialize, Deserialize, Clone, Debug)]
 1676pub struct ClipboardSelection {
 1677    pub len: usize,
 1678    pub is_entire_line: bool,
 1679    pub first_line_indent: u32,
 1680}
 1681
 1682#[derive(Debug)]
 1683pub(crate) struct NavigationData {
 1684    cursor_anchor: Anchor,
 1685    cursor_position: Point,
 1686    scroll_anchor: ScrollAnchor,
 1687    scroll_top_row: u32,
 1688}
 1689
 1690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1691pub enum GotoDefinitionKind {
 1692    Symbol,
 1693    Declaration,
 1694    Type,
 1695    Implementation,
 1696}
 1697
 1698#[derive(Debug, Clone)]
 1699enum InlayHintRefreshReason {
 1700    Toggle(bool),
 1701    SettingsChange(InlayHintSettings),
 1702    NewLinesShown,
 1703    BufferEdited(HashSet<Arc<Language>>),
 1704    RefreshRequested,
 1705    ExcerptsRemoved(Vec<ExcerptId>),
 1706}
 1707
 1708impl InlayHintRefreshReason {
 1709    fn description(&self) -> &'static str {
 1710        match self {
 1711            Self::Toggle(_) => "toggle",
 1712            Self::SettingsChange(_) => "settings change",
 1713            Self::NewLinesShown => "new lines shown",
 1714            Self::BufferEdited(_) => "buffer edited",
 1715            Self::RefreshRequested => "refresh requested",
 1716            Self::ExcerptsRemoved(_) => "excerpts removed",
 1717        }
 1718    }
 1719}
 1720
 1721pub(crate) struct FocusedBlock {
 1722    id: BlockId,
 1723    focus_handle: WeakFocusHandle,
 1724}
 1725
 1726impl Editor {
 1727    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1728        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1729        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1730        Self::new(
 1731            EditorMode::SingleLine { auto_width: false },
 1732            buffer,
 1733            None,
 1734            false,
 1735            cx,
 1736        )
 1737    }
 1738
 1739    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1740        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1741        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1742        Self::new(EditorMode::Full, buffer, None, false, cx)
 1743    }
 1744
 1745    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1746        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1747        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1748        Self::new(
 1749            EditorMode::SingleLine { auto_width: true },
 1750            buffer,
 1751            None,
 1752            false,
 1753            cx,
 1754        )
 1755    }
 1756
 1757    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1758        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1759        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1760        Self::new(
 1761            EditorMode::AutoHeight { max_lines },
 1762            buffer,
 1763            None,
 1764            false,
 1765            cx,
 1766        )
 1767    }
 1768
 1769    pub fn for_buffer(
 1770        buffer: Model<Buffer>,
 1771        project: Option<Model<Project>>,
 1772        cx: &mut ViewContext<Self>,
 1773    ) -> Self {
 1774        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1775        Self::new(EditorMode::Full, buffer, project, false, cx)
 1776    }
 1777
 1778    pub fn for_multibuffer(
 1779        buffer: Model<MultiBuffer>,
 1780        project: Option<Model<Project>>,
 1781        show_excerpt_controls: bool,
 1782        cx: &mut ViewContext<Self>,
 1783    ) -> Self {
 1784        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1785    }
 1786
 1787    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1788        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1789        let mut clone = Self::new(
 1790            self.mode,
 1791            self.buffer.clone(),
 1792            self.project.clone(),
 1793            show_excerpt_controls,
 1794            cx,
 1795        );
 1796        self.display_map.update(cx, |display_map, cx| {
 1797            let snapshot = display_map.snapshot(cx);
 1798            clone.display_map.update(cx, |display_map, cx| {
 1799                display_map.set_state(&snapshot, cx);
 1800            });
 1801        });
 1802        clone.selections.clone_state(&self.selections);
 1803        clone.scroll_manager.clone_state(&self.scroll_manager);
 1804        clone.searchable = self.searchable;
 1805        clone
 1806    }
 1807
 1808    pub fn new(
 1809        mode: EditorMode,
 1810        buffer: Model<MultiBuffer>,
 1811        project: Option<Model<Project>>,
 1812        show_excerpt_controls: bool,
 1813        cx: &mut ViewContext<Self>,
 1814    ) -> Self {
 1815        let style = cx.text_style();
 1816        let font_size = style.font_size.to_pixels(cx.rem_size());
 1817        let editor = cx.view().downgrade();
 1818        let fold_placeholder = FoldPlaceholder {
 1819            constrain_width: true,
 1820            render: Arc::new(move |fold_id, fold_range, cx| {
 1821                let editor = editor.clone();
 1822                div()
 1823                    .id(fold_id)
 1824                    .bg(cx.theme().colors().ghost_element_background)
 1825                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1826                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1827                    .rounded_sm()
 1828                    .size_full()
 1829                    .cursor_pointer()
 1830                    .child("")
 1831                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1832                    .on_click(move |_, cx| {
 1833                        editor
 1834                            .update(cx, |editor, cx| {
 1835                                editor.unfold_ranges(
 1836                                    [fold_range.start..fold_range.end],
 1837                                    true,
 1838                                    false,
 1839                                    cx,
 1840                                );
 1841                                cx.stop_propagation();
 1842                            })
 1843                            .ok();
 1844                    })
 1845                    .into_any()
 1846            }),
 1847            merge_adjacent: true,
 1848        };
 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_HEIGHT,
 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            tasks: Default::default(),
 2041            _subscriptions: vec![
 2042                cx.observe(&buffer, Self::on_buffer_changed),
 2043                cx.subscribe(&buffer, Self::on_buffer_event),
 2044                cx.observe(&display_map, Self::on_display_map_changed),
 2045                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2046                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2047                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2048                cx.observe_window_activation(|editor, cx| {
 2049                    let active = cx.is_window_active();
 2050                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2051                        if active {
 2052                            blink_manager.enable(cx);
 2053                        } else {
 2054                            blink_manager.disable(cx);
 2055                        }
 2056                    });
 2057                }),
 2058            ],
 2059            tasks_update_task: None,
 2060            linked_edit_ranges: Default::default(),
 2061            previous_search_ranges: None,
 2062            breadcrumb_header: None,
 2063            focused_block: None,
 2064            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2065            addons: HashMap::default(),
 2066            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2067            text_style_refinement: None,
 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
 4254                .read(cx)
 4255                .language_at(buffer_position)
 4256                .map(|l| l.name()),
 4257            buffer.read(cx).file(),
 4258            cx,
 4259        );
 4260        if !settings.use_on_type_format {
 4261            return None;
 4262        }
 4263
 4264        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4265        // hence we do LSP request & edit on host side only — add formats to host's history.
 4266        let push_to_lsp_host_history = true;
 4267        // If this is not the host, append its history with new edits.
 4268        let push_to_client_history = project.read(cx).is_via_collab();
 4269
 4270        let on_type_formatting = project.update(cx, |project, cx| {
 4271            project.on_type_format(
 4272                buffer.clone(),
 4273                buffer_position,
 4274                input,
 4275                push_to_lsp_host_history,
 4276                cx,
 4277            )
 4278        });
 4279        Some(cx.spawn(|editor, mut cx| async move {
 4280            if let Some(transaction) = on_type_formatting.await? {
 4281                if push_to_client_history {
 4282                    buffer
 4283                        .update(&mut cx, |buffer, _| {
 4284                            buffer.push_transaction(transaction, Instant::now());
 4285                        })
 4286                        .ok();
 4287                }
 4288                editor.update(&mut cx, |editor, cx| {
 4289                    editor.refresh_document_highlights(cx);
 4290                })?;
 4291            }
 4292            Ok(())
 4293        }))
 4294    }
 4295
 4296    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4297        if self.pending_rename.is_some() {
 4298            return;
 4299        }
 4300
 4301        let Some(provider) = self.completion_provider.as_ref() else {
 4302            return;
 4303        };
 4304
 4305        let position = self.selections.newest_anchor().head();
 4306        let (buffer, buffer_position) =
 4307            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4308                output
 4309            } else {
 4310                return;
 4311            };
 4312
 4313        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4314        let is_followup_invoke = {
 4315            let context_menu_state = self.context_menu.read();
 4316            matches!(
 4317                context_menu_state.deref(),
 4318                Some(ContextMenu::Completions(_))
 4319            )
 4320        };
 4321        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4322            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4323            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4324                CompletionTriggerKind::TRIGGER_CHARACTER
 4325            }
 4326
 4327            _ => CompletionTriggerKind::INVOKED,
 4328        };
 4329        let completion_context = CompletionContext {
 4330            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4331                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4332                    Some(String::from(trigger))
 4333                } else {
 4334                    None
 4335                }
 4336            }),
 4337            trigger_kind,
 4338        };
 4339        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4340        let sort_completions = provider.sort_completions();
 4341
 4342        let id = post_inc(&mut self.next_completion_id);
 4343        let task = cx.spawn(|this, mut cx| {
 4344            async move {
 4345                this.update(&mut cx, |this, _| {
 4346                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4347                })?;
 4348                let completions = completions.await.log_err();
 4349                let menu = if let Some(completions) = completions {
 4350                    let mut menu = CompletionsMenu {
 4351                        id,
 4352                        sort_completions,
 4353                        initial_position: position,
 4354                        match_candidates: completions
 4355                            .iter()
 4356                            .enumerate()
 4357                            .map(|(id, completion)| {
 4358                                StringMatchCandidate::new(
 4359                                    id,
 4360                                    completion.label.text[completion.label.filter_range.clone()]
 4361                                        .into(),
 4362                                )
 4363                            })
 4364                            .collect(),
 4365                        buffer: buffer.clone(),
 4366                        completions: Arc::new(RwLock::new(completions.into())),
 4367                        matches: Vec::new().into(),
 4368                        selected_item: 0,
 4369                        scroll_handle: UniformListScrollHandle::new(),
 4370                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4371                            DebouncedDelay::new(),
 4372                        )),
 4373                    };
 4374                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4375                        .await;
 4376
 4377                    if menu.matches.is_empty() {
 4378                        None
 4379                    } else {
 4380                        this.update(&mut cx, |editor, cx| {
 4381                            let completions = menu.completions.clone();
 4382                            let matches = menu.matches.clone();
 4383
 4384                            let delay_ms = EditorSettings::get_global(cx)
 4385                                .completion_documentation_secondary_query_debounce;
 4386                            let delay = Duration::from_millis(delay_ms);
 4387                            editor
 4388                                .completion_documentation_pre_resolve_debounce
 4389                                .fire_new(delay, cx, |editor, cx| {
 4390                                    CompletionsMenu::pre_resolve_completion_documentation(
 4391                                        buffer,
 4392                                        completions,
 4393                                        matches,
 4394                                        editor,
 4395                                        cx,
 4396                                    )
 4397                                });
 4398                        })
 4399                        .ok();
 4400                        Some(menu)
 4401                    }
 4402                } else {
 4403                    None
 4404                };
 4405
 4406                this.update(&mut cx, |this, cx| {
 4407                    let mut context_menu = this.context_menu.write();
 4408                    match context_menu.as_ref() {
 4409                        None => {}
 4410
 4411                        Some(ContextMenu::Completions(prev_menu)) => {
 4412                            if prev_menu.id > id {
 4413                                return;
 4414                            }
 4415                        }
 4416
 4417                        _ => return,
 4418                    }
 4419
 4420                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4421                        let menu = menu.unwrap();
 4422                        *context_menu = Some(ContextMenu::Completions(menu));
 4423                        drop(context_menu);
 4424                        this.discard_inline_completion(false, cx);
 4425                        cx.notify();
 4426                    } else if this.completion_tasks.len() <= 1 {
 4427                        // If there are no more completion tasks and the last menu was
 4428                        // empty, we should hide it. If it was already hidden, we should
 4429                        // also show the copilot completion when available.
 4430                        drop(context_menu);
 4431                        if this.hide_context_menu(cx).is_none() {
 4432                            this.update_visible_inline_completion(cx);
 4433                        }
 4434                    }
 4435                })?;
 4436
 4437                Ok::<_, anyhow::Error>(())
 4438            }
 4439            .log_err()
 4440        });
 4441
 4442        self.completion_tasks.push((id, task));
 4443    }
 4444
 4445    pub fn confirm_completion(
 4446        &mut self,
 4447        action: &ConfirmCompletion,
 4448        cx: &mut ViewContext<Self>,
 4449    ) -> Option<Task<Result<()>>> {
 4450        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4451    }
 4452
 4453    pub fn compose_completion(
 4454        &mut self,
 4455        action: &ComposeCompletion,
 4456        cx: &mut ViewContext<Self>,
 4457    ) -> Option<Task<Result<()>>> {
 4458        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4459    }
 4460
 4461    fn do_completion(
 4462        &mut self,
 4463        item_ix: Option<usize>,
 4464        intent: CompletionIntent,
 4465        cx: &mut ViewContext<Editor>,
 4466    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4467        use language::ToOffset as _;
 4468
 4469        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4470            menu
 4471        } else {
 4472            return None;
 4473        };
 4474
 4475        let mat = completions_menu
 4476            .matches
 4477            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4478        let buffer_handle = completions_menu.buffer;
 4479        let completions = completions_menu.completions.read();
 4480        let completion = completions.get(mat.candidate_id)?;
 4481        cx.stop_propagation();
 4482
 4483        let snippet;
 4484        let text;
 4485
 4486        if completion.is_snippet() {
 4487            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4488            text = snippet.as_ref().unwrap().text.clone();
 4489        } else {
 4490            snippet = None;
 4491            text = completion.new_text.clone();
 4492        };
 4493        let selections = self.selections.all::<usize>(cx);
 4494        let buffer = buffer_handle.read(cx);
 4495        let old_range = completion.old_range.to_offset(buffer);
 4496        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4497
 4498        let newest_selection = self.selections.newest_anchor();
 4499        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4500            return None;
 4501        }
 4502
 4503        let lookbehind = newest_selection
 4504            .start
 4505            .text_anchor
 4506            .to_offset(buffer)
 4507            .saturating_sub(old_range.start);
 4508        let lookahead = old_range
 4509            .end
 4510            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4511        let mut common_prefix_len = old_text
 4512            .bytes()
 4513            .zip(text.bytes())
 4514            .take_while(|(a, b)| a == b)
 4515            .count();
 4516
 4517        let snapshot = self.buffer.read(cx).snapshot(cx);
 4518        let mut range_to_replace: Option<Range<isize>> = None;
 4519        let mut ranges = Vec::new();
 4520        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4521        for selection in &selections {
 4522            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4523                let start = selection.start.saturating_sub(lookbehind);
 4524                let end = selection.end + lookahead;
 4525                if selection.id == newest_selection.id {
 4526                    range_to_replace = Some(
 4527                        ((start + common_prefix_len) as isize - selection.start as isize)
 4528                            ..(end as isize - selection.start as isize),
 4529                    );
 4530                }
 4531                ranges.push(start + common_prefix_len..end);
 4532            } else {
 4533                common_prefix_len = 0;
 4534                ranges.clear();
 4535                ranges.extend(selections.iter().map(|s| {
 4536                    if s.id == newest_selection.id {
 4537                        range_to_replace = Some(
 4538                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4539                                - selection.start as isize
 4540                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4541                                    - selection.start as isize,
 4542                        );
 4543                        old_range.clone()
 4544                    } else {
 4545                        s.start..s.end
 4546                    }
 4547                }));
 4548                break;
 4549            }
 4550            if !self.linked_edit_ranges.is_empty() {
 4551                let start_anchor = snapshot.anchor_before(selection.head());
 4552                let end_anchor = snapshot.anchor_after(selection.tail());
 4553                if let Some(ranges) = self
 4554                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4555                {
 4556                    for (buffer, edits) in ranges {
 4557                        linked_edits.entry(buffer.clone()).or_default().extend(
 4558                            edits
 4559                                .into_iter()
 4560                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4561                        );
 4562                    }
 4563                }
 4564            }
 4565        }
 4566        let text = &text[common_prefix_len..];
 4567
 4568        cx.emit(EditorEvent::InputHandled {
 4569            utf16_range_to_replace: range_to_replace,
 4570            text: text.into(),
 4571        });
 4572
 4573        self.transact(cx, |this, cx| {
 4574            if let Some(mut snippet) = snippet {
 4575                snippet.text = text.to_string();
 4576                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4577                    tabstop.start -= common_prefix_len as isize;
 4578                    tabstop.end -= common_prefix_len as isize;
 4579                }
 4580
 4581                this.insert_snippet(&ranges, snippet, cx).log_err();
 4582            } else {
 4583                this.buffer.update(cx, |buffer, cx| {
 4584                    buffer.edit(
 4585                        ranges.iter().map(|range| (range.clone(), text)),
 4586                        this.autoindent_mode.clone(),
 4587                        cx,
 4588                    );
 4589                });
 4590            }
 4591            for (buffer, edits) in linked_edits {
 4592                buffer.update(cx, |buffer, cx| {
 4593                    let snapshot = buffer.snapshot();
 4594                    let edits = edits
 4595                        .into_iter()
 4596                        .map(|(range, text)| {
 4597                            use text::ToPoint as TP;
 4598                            let end_point = TP::to_point(&range.end, &snapshot);
 4599                            let start_point = TP::to_point(&range.start, &snapshot);
 4600                            (start_point..end_point, text)
 4601                        })
 4602                        .sorted_by_key(|(range, _)| range.start)
 4603                        .collect::<Vec<_>>();
 4604                    buffer.edit(edits, None, cx);
 4605                })
 4606            }
 4607
 4608            this.refresh_inline_completion(true, false, cx);
 4609        });
 4610
 4611        let show_new_completions_on_confirm = completion
 4612            .confirm
 4613            .as_ref()
 4614            .map_or(false, |confirm| confirm(intent, cx));
 4615        if show_new_completions_on_confirm {
 4616            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4617        }
 4618
 4619        let provider = self.completion_provider.as_ref()?;
 4620        let apply_edits = provider.apply_additional_edits_for_completion(
 4621            buffer_handle,
 4622            completion.clone(),
 4623            true,
 4624            cx,
 4625        );
 4626
 4627        let editor_settings = EditorSettings::get_global(cx);
 4628        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4629            // After the code completion is finished, users often want to know what signatures are needed.
 4630            // so we should automatically call signature_help
 4631            self.show_signature_help(&ShowSignatureHelp, cx);
 4632        }
 4633
 4634        Some(cx.foreground_executor().spawn(async move {
 4635            apply_edits.await?;
 4636            Ok(())
 4637        }))
 4638    }
 4639
 4640    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4641        let mut context_menu = self.context_menu.write();
 4642        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4643            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4644                // Toggle if we're selecting the same one
 4645                *context_menu = None;
 4646                cx.notify();
 4647                return;
 4648            } else {
 4649                // Otherwise, clear it and start a new one
 4650                *context_menu = None;
 4651                cx.notify();
 4652            }
 4653        }
 4654        drop(context_menu);
 4655        let snapshot = self.snapshot(cx);
 4656        let deployed_from_indicator = action.deployed_from_indicator;
 4657        let mut task = self.code_actions_task.take();
 4658        let action = action.clone();
 4659        cx.spawn(|editor, mut cx| async move {
 4660            while let Some(prev_task) = task {
 4661                prev_task.await.log_err();
 4662                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4663            }
 4664
 4665            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4666                if editor.focus_handle.is_focused(cx) {
 4667                    let multibuffer_point = action
 4668                        .deployed_from_indicator
 4669                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4670                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4671                    let (buffer, buffer_row) = snapshot
 4672                        .buffer_snapshot
 4673                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4674                        .and_then(|(buffer_snapshot, range)| {
 4675                            editor
 4676                                .buffer
 4677                                .read(cx)
 4678                                .buffer(buffer_snapshot.remote_id())
 4679                                .map(|buffer| (buffer, range.start.row))
 4680                        })?;
 4681                    let (_, code_actions) = editor
 4682                        .available_code_actions
 4683                        .clone()
 4684                        .and_then(|(location, code_actions)| {
 4685                            let snapshot = location.buffer.read(cx).snapshot();
 4686                            let point_range = location.range.to_point(&snapshot);
 4687                            let point_range = point_range.start.row..=point_range.end.row;
 4688                            if point_range.contains(&buffer_row) {
 4689                                Some((location, code_actions))
 4690                            } else {
 4691                                None
 4692                            }
 4693                        })
 4694                        .unzip();
 4695                    let buffer_id = buffer.read(cx).remote_id();
 4696                    let tasks = editor
 4697                        .tasks
 4698                        .get(&(buffer_id, buffer_row))
 4699                        .map(|t| Arc::new(t.to_owned()));
 4700                    if tasks.is_none() && code_actions.is_none() {
 4701                        return None;
 4702                    }
 4703
 4704                    editor.completion_tasks.clear();
 4705                    editor.discard_inline_completion(false, cx);
 4706                    let task_context =
 4707                        tasks
 4708                            .as_ref()
 4709                            .zip(editor.project.clone())
 4710                            .map(|(tasks, project)| {
 4711                                let position = Point::new(buffer_row, tasks.column);
 4712                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4713                                let location = Location {
 4714                                    buffer: buffer.clone(),
 4715                                    range: range_start..range_start,
 4716                                };
 4717                                // Fill in the environmental variables from the tree-sitter captures
 4718                                let mut captured_task_variables = TaskVariables::default();
 4719                                for (capture_name, value) in tasks.extra_variables.clone() {
 4720                                    captured_task_variables.insert(
 4721                                        task::VariableName::Custom(capture_name.into()),
 4722                                        value.clone(),
 4723                                    );
 4724                                }
 4725                                project.update(cx, |project, cx| {
 4726                                    project.task_store().update(cx, |task_store, cx| {
 4727                                        task_store.task_context_for_location(
 4728                                            captured_task_variables,
 4729                                            location,
 4730                                            cx,
 4731                                        )
 4732                                    })
 4733                                })
 4734                            });
 4735
 4736                    Some(cx.spawn(|editor, mut cx| async move {
 4737                        let task_context = match task_context {
 4738                            Some(task_context) => task_context.await,
 4739                            None => None,
 4740                        };
 4741                        let resolved_tasks =
 4742                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4743                                Arc::new(ResolvedTasks {
 4744                                    templates: tasks
 4745                                        .templates
 4746                                        .iter()
 4747                                        .filter_map(|(kind, template)| {
 4748                                            template
 4749                                                .resolve_task(&kind.to_id_base(), &task_context)
 4750                                                .map(|task| (kind.clone(), task))
 4751                                        })
 4752                                        .collect(),
 4753                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4754                                        multibuffer_point.row,
 4755                                        tasks.column,
 4756                                    )),
 4757                                })
 4758                            });
 4759                        let spawn_straight_away = resolved_tasks
 4760                            .as_ref()
 4761                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4762                            && code_actions
 4763                                .as_ref()
 4764                                .map_or(true, |actions| actions.is_empty());
 4765                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4766                            *editor.context_menu.write() =
 4767                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4768                                    buffer,
 4769                                    actions: CodeActionContents {
 4770                                        tasks: resolved_tasks,
 4771                                        actions: code_actions,
 4772                                    },
 4773                                    selected_item: Default::default(),
 4774                                    scroll_handle: UniformListScrollHandle::default(),
 4775                                    deployed_from_indicator,
 4776                                }));
 4777                            if spawn_straight_away {
 4778                                if let Some(task) = editor.confirm_code_action(
 4779                                    &ConfirmCodeAction { item_ix: Some(0) },
 4780                                    cx,
 4781                                ) {
 4782                                    cx.notify();
 4783                                    return task;
 4784                                }
 4785                            }
 4786                            cx.notify();
 4787                            Task::ready(Ok(()))
 4788                        }) {
 4789                            task.await
 4790                        } else {
 4791                            Ok(())
 4792                        }
 4793                    }))
 4794                } else {
 4795                    Some(Task::ready(Ok(())))
 4796                }
 4797            })?;
 4798            if let Some(task) = spawned_test_task {
 4799                task.await?;
 4800            }
 4801
 4802            Ok::<_, anyhow::Error>(())
 4803        })
 4804        .detach_and_log_err(cx);
 4805    }
 4806
 4807    pub fn confirm_code_action(
 4808        &mut self,
 4809        action: &ConfirmCodeAction,
 4810        cx: &mut ViewContext<Self>,
 4811    ) -> Option<Task<Result<()>>> {
 4812        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4813            menu
 4814        } else {
 4815            return None;
 4816        };
 4817        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4818        let action = actions_menu.actions.get(action_ix)?;
 4819        let title = action.label();
 4820        let buffer = actions_menu.buffer;
 4821        let workspace = self.workspace()?;
 4822
 4823        match action {
 4824            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4825                workspace.update(cx, |workspace, cx| {
 4826                    workspace::tasks::schedule_resolved_task(
 4827                        workspace,
 4828                        task_source_kind,
 4829                        resolved_task,
 4830                        false,
 4831                        cx,
 4832                    );
 4833
 4834                    Some(Task::ready(Ok(())))
 4835                })
 4836            }
 4837            CodeActionsItem::CodeAction {
 4838                excerpt_id,
 4839                action,
 4840                provider,
 4841            } => {
 4842                let apply_code_action =
 4843                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4844                let workspace = workspace.downgrade();
 4845                Some(cx.spawn(|editor, cx| async move {
 4846                    let project_transaction = apply_code_action.await?;
 4847                    Self::open_project_transaction(
 4848                        &editor,
 4849                        workspace,
 4850                        project_transaction,
 4851                        title,
 4852                        cx,
 4853                    )
 4854                    .await
 4855                }))
 4856            }
 4857        }
 4858    }
 4859
 4860    pub async fn open_project_transaction(
 4861        this: &WeakView<Editor>,
 4862        workspace: WeakView<Workspace>,
 4863        transaction: ProjectTransaction,
 4864        title: String,
 4865        mut cx: AsyncWindowContext,
 4866    ) -> Result<()> {
 4867        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4868        cx.update(|cx| {
 4869            entries.sort_unstable_by_key(|(buffer, _)| {
 4870                buffer.read(cx).file().map(|f| f.path().clone())
 4871            });
 4872        })?;
 4873
 4874        // If the project transaction's edits are all contained within this editor, then
 4875        // avoid opening a new editor to display them.
 4876
 4877        if let Some((buffer, transaction)) = entries.first() {
 4878            if entries.len() == 1 {
 4879                let excerpt = this.update(&mut cx, |editor, cx| {
 4880                    editor
 4881                        .buffer()
 4882                        .read(cx)
 4883                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4884                })?;
 4885                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4886                    if excerpted_buffer == *buffer {
 4887                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4888                            let excerpt_range = excerpt_range.to_offset(buffer);
 4889                            buffer
 4890                                .edited_ranges_for_transaction::<usize>(transaction)
 4891                                .all(|range| {
 4892                                    excerpt_range.start <= range.start
 4893                                        && excerpt_range.end >= range.end
 4894                                })
 4895                        })?;
 4896
 4897                        if all_edits_within_excerpt {
 4898                            return Ok(());
 4899                        }
 4900                    }
 4901                }
 4902            }
 4903        } else {
 4904            return Ok(());
 4905        }
 4906
 4907        let mut ranges_to_highlight = Vec::new();
 4908        let excerpt_buffer = cx.new_model(|cx| {
 4909            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4910            for (buffer_handle, transaction) in &entries {
 4911                let buffer = buffer_handle.read(cx);
 4912                ranges_to_highlight.extend(
 4913                    multibuffer.push_excerpts_with_context_lines(
 4914                        buffer_handle.clone(),
 4915                        buffer
 4916                            .edited_ranges_for_transaction::<usize>(transaction)
 4917                            .collect(),
 4918                        DEFAULT_MULTIBUFFER_CONTEXT,
 4919                        cx,
 4920                    ),
 4921                );
 4922            }
 4923            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4924            multibuffer
 4925        })?;
 4926
 4927        workspace.update(&mut cx, |workspace, cx| {
 4928            let project = workspace.project().clone();
 4929            let editor =
 4930                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4931            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4932            editor.update(cx, |editor, cx| {
 4933                editor.highlight_background::<Self>(
 4934                    &ranges_to_highlight,
 4935                    |theme| theme.editor_highlighted_line_background,
 4936                    cx,
 4937                );
 4938            });
 4939        })?;
 4940
 4941        Ok(())
 4942    }
 4943
 4944    pub fn clear_code_action_providers(&mut self) {
 4945        self.code_action_providers.clear();
 4946        self.available_code_actions.take();
 4947    }
 4948
 4949    pub fn push_code_action_provider(
 4950        &mut self,
 4951        provider: Arc<dyn CodeActionProvider>,
 4952        cx: &mut ViewContext<Self>,
 4953    ) {
 4954        self.code_action_providers.push(provider);
 4955        self.refresh_code_actions(cx);
 4956    }
 4957
 4958    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4959        let buffer = self.buffer.read(cx);
 4960        let newest_selection = self.selections.newest_anchor().clone();
 4961        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4962        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4963        if start_buffer != end_buffer {
 4964            return None;
 4965        }
 4966
 4967        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4968            cx.background_executor()
 4969                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4970                .await;
 4971
 4972            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4973                let providers = this.code_action_providers.clone();
 4974                let tasks = this
 4975                    .code_action_providers
 4976                    .iter()
 4977                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4978                    .collect::<Vec<_>>();
 4979                (providers, tasks)
 4980            })?;
 4981
 4982            let mut actions = Vec::new();
 4983            for (provider, provider_actions) in
 4984                providers.into_iter().zip(future::join_all(tasks).await)
 4985            {
 4986                if let Some(provider_actions) = provider_actions.log_err() {
 4987                    actions.extend(provider_actions.into_iter().map(|action| {
 4988                        AvailableCodeAction {
 4989                            excerpt_id: newest_selection.start.excerpt_id,
 4990                            action,
 4991                            provider: provider.clone(),
 4992                        }
 4993                    }));
 4994                }
 4995            }
 4996
 4997            this.update(&mut cx, |this, cx| {
 4998                this.available_code_actions = if actions.is_empty() {
 4999                    None
 5000                } else {
 5001                    Some((
 5002                        Location {
 5003                            buffer: start_buffer,
 5004                            range: start..end,
 5005                        },
 5006                        actions.into(),
 5007                    ))
 5008                };
 5009                cx.notify();
 5010            })
 5011        }));
 5012        None
 5013    }
 5014
 5015    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5016        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5017            self.show_git_blame_inline = false;
 5018
 5019            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5020                cx.background_executor().timer(delay).await;
 5021
 5022                this.update(&mut cx, |this, cx| {
 5023                    this.show_git_blame_inline = true;
 5024                    cx.notify();
 5025                })
 5026                .log_err();
 5027            }));
 5028        }
 5029    }
 5030
 5031    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5032        if self.pending_rename.is_some() {
 5033            return None;
 5034        }
 5035
 5036        let provider = self.semantics_provider.clone()?;
 5037        let buffer = self.buffer.read(cx);
 5038        let newest_selection = self.selections.newest_anchor().clone();
 5039        let cursor_position = newest_selection.head();
 5040        let (cursor_buffer, cursor_buffer_position) =
 5041            buffer.text_anchor_for_position(cursor_position, cx)?;
 5042        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5043        if cursor_buffer != tail_buffer {
 5044            return None;
 5045        }
 5046
 5047        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5048            cx.background_executor()
 5049                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5050                .await;
 5051
 5052            let highlights = if let Some(highlights) = cx
 5053                .update(|cx| {
 5054                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5055                })
 5056                .ok()
 5057                .flatten()
 5058            {
 5059                highlights.await.log_err()
 5060            } else {
 5061                None
 5062            };
 5063
 5064            if let Some(highlights) = highlights {
 5065                this.update(&mut cx, |this, cx| {
 5066                    if this.pending_rename.is_some() {
 5067                        return;
 5068                    }
 5069
 5070                    let buffer_id = cursor_position.buffer_id;
 5071                    let buffer = this.buffer.read(cx);
 5072                    if !buffer
 5073                        .text_anchor_for_position(cursor_position, cx)
 5074                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5075                    {
 5076                        return;
 5077                    }
 5078
 5079                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5080                    let mut write_ranges = Vec::new();
 5081                    let mut read_ranges = Vec::new();
 5082                    for highlight in highlights {
 5083                        for (excerpt_id, excerpt_range) in
 5084                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5085                        {
 5086                            let start = highlight
 5087                                .range
 5088                                .start
 5089                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5090                            let end = highlight
 5091                                .range
 5092                                .end
 5093                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5094                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5095                                continue;
 5096                            }
 5097
 5098                            let range = Anchor {
 5099                                buffer_id,
 5100                                excerpt_id,
 5101                                text_anchor: start,
 5102                            }..Anchor {
 5103                                buffer_id,
 5104                                excerpt_id,
 5105                                text_anchor: end,
 5106                            };
 5107                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5108                                write_ranges.push(range);
 5109                            } else {
 5110                                read_ranges.push(range);
 5111                            }
 5112                        }
 5113                    }
 5114
 5115                    this.highlight_background::<DocumentHighlightRead>(
 5116                        &read_ranges,
 5117                        |theme| theme.editor_document_highlight_read_background,
 5118                        cx,
 5119                    );
 5120                    this.highlight_background::<DocumentHighlightWrite>(
 5121                        &write_ranges,
 5122                        |theme| theme.editor_document_highlight_write_background,
 5123                        cx,
 5124                    );
 5125                    cx.notify();
 5126                })
 5127                .log_err();
 5128            }
 5129        }));
 5130        None
 5131    }
 5132
 5133    pub fn refresh_inline_completion(
 5134        &mut self,
 5135        debounce: bool,
 5136        user_requested: bool,
 5137        cx: &mut ViewContext<Self>,
 5138    ) -> Option<()> {
 5139        let provider = self.inline_completion_provider()?;
 5140        let cursor = self.selections.newest_anchor().head();
 5141        let (buffer, cursor_buffer_position) =
 5142            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5143
 5144        if !user_requested
 5145            && (!self.enable_inline_completions
 5146                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5147        {
 5148            self.discard_inline_completion(false, cx);
 5149            return None;
 5150        }
 5151
 5152        self.update_visible_inline_completion(cx);
 5153        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5154        Some(())
 5155    }
 5156
 5157    fn cycle_inline_completion(
 5158        &mut self,
 5159        direction: Direction,
 5160        cx: &mut ViewContext<Self>,
 5161    ) -> Option<()> {
 5162        let provider = self.inline_completion_provider()?;
 5163        let cursor = self.selections.newest_anchor().head();
 5164        let (buffer, cursor_buffer_position) =
 5165            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5166        if !self.enable_inline_completions
 5167            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5168        {
 5169            return None;
 5170        }
 5171
 5172        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5173        self.update_visible_inline_completion(cx);
 5174
 5175        Some(())
 5176    }
 5177
 5178    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5179        if !self.has_active_inline_completion(cx) {
 5180            self.refresh_inline_completion(false, true, cx);
 5181            return;
 5182        }
 5183
 5184        self.update_visible_inline_completion(cx);
 5185    }
 5186
 5187    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5188        self.show_cursor_names(cx);
 5189    }
 5190
 5191    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5192        self.show_cursor_names = true;
 5193        cx.notify();
 5194        cx.spawn(|this, mut cx| async move {
 5195            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5196            this.update(&mut cx, |this, cx| {
 5197                this.show_cursor_names = false;
 5198                cx.notify()
 5199            })
 5200            .ok()
 5201        })
 5202        .detach();
 5203    }
 5204
 5205    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5206        if self.has_active_inline_completion(cx) {
 5207            self.cycle_inline_completion(Direction::Next, cx);
 5208        } else {
 5209            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5210            if is_copilot_disabled {
 5211                cx.propagate();
 5212            }
 5213        }
 5214    }
 5215
 5216    pub fn previous_inline_completion(
 5217        &mut self,
 5218        _: &PreviousInlineCompletion,
 5219        cx: &mut ViewContext<Self>,
 5220    ) {
 5221        if self.has_active_inline_completion(cx) {
 5222            self.cycle_inline_completion(Direction::Prev, cx);
 5223        } else {
 5224            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5225            if is_copilot_disabled {
 5226                cx.propagate();
 5227            }
 5228        }
 5229    }
 5230
 5231    pub fn accept_inline_completion(
 5232        &mut self,
 5233        _: &AcceptInlineCompletion,
 5234        cx: &mut ViewContext<Self>,
 5235    ) {
 5236        let Some(completion) = self.take_active_inline_completion(cx) else {
 5237            return;
 5238        };
 5239        if let Some(provider) = self.inline_completion_provider() {
 5240            provider.accept(cx);
 5241        }
 5242
 5243        cx.emit(EditorEvent::InputHandled {
 5244            utf16_range_to_replace: None,
 5245            text: completion.text.to_string().into(),
 5246        });
 5247
 5248        if let Some(range) = completion.delete_range {
 5249            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5250        }
 5251        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5252        self.refresh_inline_completion(true, true, cx);
 5253        cx.notify();
 5254    }
 5255
 5256    pub fn accept_partial_inline_completion(
 5257        &mut self,
 5258        _: &AcceptPartialInlineCompletion,
 5259        cx: &mut ViewContext<Self>,
 5260    ) {
 5261        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5262            if let Some(completion) = self.take_active_inline_completion(cx) {
 5263                let mut partial_completion = completion
 5264                    .text
 5265                    .chars()
 5266                    .by_ref()
 5267                    .take_while(|c| c.is_alphabetic())
 5268                    .collect::<String>();
 5269                if partial_completion.is_empty() {
 5270                    partial_completion = completion
 5271                        .text
 5272                        .chars()
 5273                        .by_ref()
 5274                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5275                        .collect::<String>();
 5276                }
 5277
 5278                cx.emit(EditorEvent::InputHandled {
 5279                    utf16_range_to_replace: None,
 5280                    text: partial_completion.clone().into(),
 5281                });
 5282
 5283                if let Some(range) = completion.delete_range {
 5284                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5285                }
 5286                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5287
 5288                self.refresh_inline_completion(true, true, cx);
 5289                cx.notify();
 5290            }
 5291        }
 5292    }
 5293
 5294    fn discard_inline_completion(
 5295        &mut self,
 5296        should_report_inline_completion_event: bool,
 5297        cx: &mut ViewContext<Self>,
 5298    ) -> bool {
 5299        if let Some(provider) = self.inline_completion_provider() {
 5300            provider.discard(should_report_inline_completion_event, cx);
 5301        }
 5302
 5303        self.take_active_inline_completion(cx).is_some()
 5304    }
 5305
 5306    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5307        if let Some(completion) = self.active_inline_completion.as_ref() {
 5308            let buffer = self.buffer.read(cx).read(cx);
 5309            completion.position.is_valid(&buffer)
 5310        } else {
 5311            false
 5312        }
 5313    }
 5314
 5315    fn take_active_inline_completion(
 5316        &mut self,
 5317        cx: &mut ViewContext<Self>,
 5318    ) -> Option<CompletionState> {
 5319        let completion = self.active_inline_completion.take()?;
 5320        let render_inlay_ids = completion.render_inlay_ids.clone();
 5321        self.display_map.update(cx, |map, cx| {
 5322            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5323        });
 5324        let buffer = self.buffer.read(cx).read(cx);
 5325
 5326        if completion.position.is_valid(&buffer) {
 5327            Some(completion)
 5328        } else {
 5329            None
 5330        }
 5331    }
 5332
 5333    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5334        let selection = self.selections.newest_anchor();
 5335        let cursor = selection.head();
 5336
 5337        let excerpt_id = cursor.excerpt_id;
 5338
 5339        if self.context_menu.read().is_none()
 5340            && self.completion_tasks.is_empty()
 5341            && selection.start == selection.end
 5342        {
 5343            if let Some(provider) = self.inline_completion_provider() {
 5344                if let Some((buffer, cursor_buffer_position)) =
 5345                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5346                {
 5347                    if let Some(proposal) =
 5348                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5349                    {
 5350                        let mut to_remove = Vec::new();
 5351                        if let Some(completion) = self.active_inline_completion.take() {
 5352                            to_remove.extend(completion.render_inlay_ids.iter());
 5353                        }
 5354
 5355                        let to_add = proposal
 5356                            .inlays
 5357                            .iter()
 5358                            .filter_map(|inlay| {
 5359                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5360                                let id = post_inc(&mut self.next_inlay_id);
 5361                                match inlay {
 5362                                    InlayProposal::Hint(position, hint) => {
 5363                                        let position =
 5364                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5365                                        Some(Inlay::hint(id, position, hint))
 5366                                    }
 5367                                    InlayProposal::Suggestion(position, text) => {
 5368                                        let position =
 5369                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5370                                        Some(Inlay::suggestion(id, position, text.clone()))
 5371                                    }
 5372                                }
 5373                            })
 5374                            .collect_vec();
 5375
 5376                        self.active_inline_completion = Some(CompletionState {
 5377                            position: cursor,
 5378                            text: proposal.text,
 5379                            delete_range: proposal.delete_range.and_then(|range| {
 5380                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5381                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5382                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5383                                Some(start?..end?)
 5384                            }),
 5385                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5386                        });
 5387
 5388                        self.display_map
 5389                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5390
 5391                        cx.notify();
 5392                        return;
 5393                    }
 5394                }
 5395            }
 5396        }
 5397
 5398        self.discard_inline_completion(false, cx);
 5399    }
 5400
 5401    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5402        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5403    }
 5404
 5405    fn render_code_actions_indicator(
 5406        &self,
 5407        _style: &EditorStyle,
 5408        row: DisplayRow,
 5409        is_active: bool,
 5410        cx: &mut ViewContext<Self>,
 5411    ) -> Option<IconButton> {
 5412        if self.available_code_actions.is_some() {
 5413            Some(
 5414                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5415                    .shape(ui::IconButtonShape::Square)
 5416                    .icon_size(IconSize::XSmall)
 5417                    .icon_color(Color::Muted)
 5418                    .selected(is_active)
 5419                    .tooltip({
 5420                        let focus_handle = self.focus_handle.clone();
 5421                        move |cx| {
 5422                            Tooltip::for_action_in(
 5423                                "Toggle Code Actions",
 5424                                &ToggleCodeActions {
 5425                                    deployed_from_indicator: None,
 5426                                },
 5427                                &focus_handle,
 5428                                cx,
 5429                            )
 5430                        }
 5431                    })
 5432                    .on_click(cx.listener(move |editor, _e, cx| {
 5433                        editor.focus(cx);
 5434                        editor.toggle_code_actions(
 5435                            &ToggleCodeActions {
 5436                                deployed_from_indicator: Some(row),
 5437                            },
 5438                            cx,
 5439                        );
 5440                    })),
 5441            )
 5442        } else {
 5443            None
 5444        }
 5445    }
 5446
 5447    fn clear_tasks(&mut self) {
 5448        self.tasks.clear()
 5449    }
 5450
 5451    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5452        if self.tasks.insert(key, value).is_some() {
 5453            // This case should hopefully be rare, but just in case...
 5454            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5455        }
 5456    }
 5457
 5458    fn render_run_indicator(
 5459        &self,
 5460        _style: &EditorStyle,
 5461        is_active: bool,
 5462        row: DisplayRow,
 5463        cx: &mut ViewContext<Self>,
 5464    ) -> IconButton {
 5465        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5466            .shape(ui::IconButtonShape::Square)
 5467            .icon_size(IconSize::XSmall)
 5468            .icon_color(Color::Muted)
 5469            .selected(is_active)
 5470            .on_click(cx.listener(move |editor, _e, cx| {
 5471                editor.focus(cx);
 5472                editor.toggle_code_actions(
 5473                    &ToggleCodeActions {
 5474                        deployed_from_indicator: Some(row),
 5475                    },
 5476                    cx,
 5477                );
 5478            }))
 5479    }
 5480
 5481    pub fn context_menu_visible(&self) -> bool {
 5482        self.context_menu
 5483            .read()
 5484            .as_ref()
 5485            .map_or(false, |menu| menu.visible())
 5486    }
 5487
 5488    fn render_context_menu(
 5489        &self,
 5490        cursor_position: DisplayPoint,
 5491        style: &EditorStyle,
 5492        max_height: Pixels,
 5493        cx: &mut ViewContext<Editor>,
 5494    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5495        self.context_menu.read().as_ref().map(|menu| {
 5496            menu.render(
 5497                cursor_position,
 5498                style,
 5499                max_height,
 5500                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5501                cx,
 5502            )
 5503        })
 5504    }
 5505
 5506    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5507        cx.notify();
 5508        self.completion_tasks.clear();
 5509        let context_menu = self.context_menu.write().take();
 5510        if context_menu.is_some() {
 5511            self.update_visible_inline_completion(cx);
 5512        }
 5513        context_menu
 5514    }
 5515
 5516    pub fn insert_snippet(
 5517        &mut self,
 5518        insertion_ranges: &[Range<usize>],
 5519        snippet: Snippet,
 5520        cx: &mut ViewContext<Self>,
 5521    ) -> Result<()> {
 5522        struct Tabstop<T> {
 5523            is_end_tabstop: bool,
 5524            ranges: Vec<Range<T>>,
 5525        }
 5526
 5527        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5528            let snippet_text: Arc<str> = snippet.text.clone().into();
 5529            buffer.edit(
 5530                insertion_ranges
 5531                    .iter()
 5532                    .cloned()
 5533                    .map(|range| (range, snippet_text.clone())),
 5534                Some(AutoindentMode::EachLine),
 5535                cx,
 5536            );
 5537
 5538            let snapshot = &*buffer.read(cx);
 5539            let snippet = &snippet;
 5540            snippet
 5541                .tabstops
 5542                .iter()
 5543                .map(|tabstop| {
 5544                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5545                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5546                    });
 5547                    let mut tabstop_ranges = tabstop
 5548                        .iter()
 5549                        .flat_map(|tabstop_range| {
 5550                            let mut delta = 0_isize;
 5551                            insertion_ranges.iter().map(move |insertion_range| {
 5552                                let insertion_start = insertion_range.start as isize + delta;
 5553                                delta +=
 5554                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5555
 5556                                let start = ((insertion_start + tabstop_range.start) as usize)
 5557                                    .min(snapshot.len());
 5558                                let end = ((insertion_start + tabstop_range.end) as usize)
 5559                                    .min(snapshot.len());
 5560                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5561                            })
 5562                        })
 5563                        .collect::<Vec<_>>();
 5564                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5565
 5566                    Tabstop {
 5567                        is_end_tabstop,
 5568                        ranges: tabstop_ranges,
 5569                    }
 5570                })
 5571                .collect::<Vec<_>>()
 5572        });
 5573        if let Some(tabstop) = tabstops.first() {
 5574            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5575                s.select_ranges(tabstop.ranges.iter().cloned());
 5576            });
 5577
 5578            // If we're already at the last tabstop and it's at the end of the snippet,
 5579            // we're done, we don't need to keep the state around.
 5580            if !tabstop.is_end_tabstop {
 5581                let ranges = tabstops
 5582                    .into_iter()
 5583                    .map(|tabstop| tabstop.ranges)
 5584                    .collect::<Vec<_>>();
 5585                self.snippet_stack.push(SnippetState {
 5586                    active_index: 0,
 5587                    ranges,
 5588                });
 5589            }
 5590
 5591            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5592            if self.autoclose_regions.is_empty() {
 5593                let snapshot = self.buffer.read(cx).snapshot(cx);
 5594                for selection in &mut self.selections.all::<Point>(cx) {
 5595                    let selection_head = selection.head();
 5596                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5597                        continue;
 5598                    };
 5599
 5600                    let mut bracket_pair = None;
 5601                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5602                    let prev_chars = snapshot
 5603                        .reversed_chars_at(selection_head)
 5604                        .collect::<String>();
 5605                    for (pair, enabled) in scope.brackets() {
 5606                        if enabled
 5607                            && pair.close
 5608                            && prev_chars.starts_with(pair.start.as_str())
 5609                            && next_chars.starts_with(pair.end.as_str())
 5610                        {
 5611                            bracket_pair = Some(pair.clone());
 5612                            break;
 5613                        }
 5614                    }
 5615                    if let Some(pair) = bracket_pair {
 5616                        let start = snapshot.anchor_after(selection_head);
 5617                        let end = snapshot.anchor_after(selection_head);
 5618                        self.autoclose_regions.push(AutocloseRegion {
 5619                            selection_id: selection.id,
 5620                            range: start..end,
 5621                            pair,
 5622                        });
 5623                    }
 5624                }
 5625            }
 5626        }
 5627        Ok(())
 5628    }
 5629
 5630    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5631        self.move_to_snippet_tabstop(Bias::Right, cx)
 5632    }
 5633
 5634    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5635        self.move_to_snippet_tabstop(Bias::Left, cx)
 5636    }
 5637
 5638    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5639        if let Some(mut snippet) = self.snippet_stack.pop() {
 5640            match bias {
 5641                Bias::Left => {
 5642                    if snippet.active_index > 0 {
 5643                        snippet.active_index -= 1;
 5644                    } else {
 5645                        self.snippet_stack.push(snippet);
 5646                        return false;
 5647                    }
 5648                }
 5649                Bias::Right => {
 5650                    if snippet.active_index + 1 < snippet.ranges.len() {
 5651                        snippet.active_index += 1;
 5652                    } else {
 5653                        self.snippet_stack.push(snippet);
 5654                        return false;
 5655                    }
 5656                }
 5657            }
 5658            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5659                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5660                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5661                });
 5662                // If snippet state is not at the last tabstop, push it back on the stack
 5663                if snippet.active_index + 1 < snippet.ranges.len() {
 5664                    self.snippet_stack.push(snippet);
 5665                }
 5666                return true;
 5667            }
 5668        }
 5669
 5670        false
 5671    }
 5672
 5673    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5674        self.transact(cx, |this, cx| {
 5675            this.select_all(&SelectAll, cx);
 5676            this.insert("", cx);
 5677        });
 5678    }
 5679
 5680    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5681        self.transact(cx, |this, cx| {
 5682            this.select_autoclose_pair(cx);
 5683            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5684            if !this.linked_edit_ranges.is_empty() {
 5685                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5686                let snapshot = this.buffer.read(cx).snapshot(cx);
 5687
 5688                for selection in selections.iter() {
 5689                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5690                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5691                    if selection_start.buffer_id != selection_end.buffer_id {
 5692                        continue;
 5693                    }
 5694                    if let Some(ranges) =
 5695                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5696                    {
 5697                        for (buffer, entries) in ranges {
 5698                            linked_ranges.entry(buffer).or_default().extend(entries);
 5699                        }
 5700                    }
 5701                }
 5702            }
 5703
 5704            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5705            if !this.selections.line_mode {
 5706                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5707                for selection in &mut selections {
 5708                    if selection.is_empty() {
 5709                        let old_head = selection.head();
 5710                        let mut new_head =
 5711                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5712                                .to_point(&display_map);
 5713                        if let Some((buffer, line_buffer_range)) = display_map
 5714                            .buffer_snapshot
 5715                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5716                        {
 5717                            let indent_size =
 5718                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5719                            let indent_len = match indent_size.kind {
 5720                                IndentKind::Space => {
 5721                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5722                                }
 5723                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5724                            };
 5725                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5726                                let indent_len = indent_len.get();
 5727                                new_head = cmp::min(
 5728                                    new_head,
 5729                                    MultiBufferPoint::new(
 5730                                        old_head.row,
 5731                                        ((old_head.column - 1) / indent_len) * indent_len,
 5732                                    ),
 5733                                );
 5734                            }
 5735                        }
 5736
 5737                        selection.set_head(new_head, SelectionGoal::None);
 5738                    }
 5739                }
 5740            }
 5741
 5742            this.signature_help_state.set_backspace_pressed(true);
 5743            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5744            this.insert("", cx);
 5745            let empty_str: Arc<str> = Arc::from("");
 5746            for (buffer, edits) in linked_ranges {
 5747                let snapshot = buffer.read(cx).snapshot();
 5748                use text::ToPoint as TP;
 5749
 5750                let edits = edits
 5751                    .into_iter()
 5752                    .map(|range| {
 5753                        let end_point = TP::to_point(&range.end, &snapshot);
 5754                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5755
 5756                        if end_point == start_point {
 5757                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5758                                .saturating_sub(1);
 5759                            start_point = TP::to_point(&offset, &snapshot);
 5760                        };
 5761
 5762                        (start_point..end_point, empty_str.clone())
 5763                    })
 5764                    .sorted_by_key(|(range, _)| range.start)
 5765                    .collect::<Vec<_>>();
 5766                buffer.update(cx, |this, cx| {
 5767                    this.edit(edits, None, cx);
 5768                })
 5769            }
 5770            this.refresh_inline_completion(true, false, cx);
 5771            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5772        });
 5773    }
 5774
 5775    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5776        self.transact(cx, |this, cx| {
 5777            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5778                let line_mode = s.line_mode;
 5779                s.move_with(|map, selection| {
 5780                    if selection.is_empty() && !line_mode {
 5781                        let cursor = movement::right(map, selection.head());
 5782                        selection.end = cursor;
 5783                        selection.reversed = true;
 5784                        selection.goal = SelectionGoal::None;
 5785                    }
 5786                })
 5787            });
 5788            this.insert("", cx);
 5789            this.refresh_inline_completion(true, false, cx);
 5790        });
 5791    }
 5792
 5793    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5794        if self.move_to_prev_snippet_tabstop(cx) {
 5795            return;
 5796        }
 5797
 5798        self.outdent(&Outdent, cx);
 5799    }
 5800
 5801    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5802        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5803            return;
 5804        }
 5805
 5806        let mut selections = self.selections.all_adjusted(cx);
 5807        let buffer = self.buffer.read(cx);
 5808        let snapshot = buffer.snapshot(cx);
 5809        let rows_iter = selections.iter().map(|s| s.head().row);
 5810        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5811
 5812        let mut edits = Vec::new();
 5813        let mut prev_edited_row = 0;
 5814        let mut row_delta = 0;
 5815        for selection in &mut selections {
 5816            if selection.start.row != prev_edited_row {
 5817                row_delta = 0;
 5818            }
 5819            prev_edited_row = selection.end.row;
 5820
 5821            // If the selection is non-empty, then increase the indentation of the selected lines.
 5822            if !selection.is_empty() {
 5823                row_delta =
 5824                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5825                continue;
 5826            }
 5827
 5828            // If the selection is empty and the cursor is in the leading whitespace before the
 5829            // suggested indentation, then auto-indent the line.
 5830            let cursor = selection.head();
 5831            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5832            if let Some(suggested_indent) =
 5833                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5834            {
 5835                if cursor.column < suggested_indent.len
 5836                    && cursor.column <= current_indent.len
 5837                    && current_indent.len <= suggested_indent.len
 5838                {
 5839                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5840                    selection.end = selection.start;
 5841                    if row_delta == 0 {
 5842                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5843                            cursor.row,
 5844                            current_indent,
 5845                            suggested_indent,
 5846                        ));
 5847                        row_delta = suggested_indent.len - current_indent.len;
 5848                    }
 5849                    continue;
 5850                }
 5851            }
 5852
 5853            // Otherwise, insert a hard or soft tab.
 5854            let settings = buffer.settings_at(cursor, cx);
 5855            let tab_size = if settings.hard_tabs {
 5856                IndentSize::tab()
 5857            } else {
 5858                let tab_size = settings.tab_size.get();
 5859                let char_column = snapshot
 5860                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5861                    .flat_map(str::chars)
 5862                    .count()
 5863                    + row_delta as usize;
 5864                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5865                IndentSize::spaces(chars_to_next_tab_stop)
 5866            };
 5867            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5868            selection.end = selection.start;
 5869            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5870            row_delta += tab_size.len;
 5871        }
 5872
 5873        self.transact(cx, |this, cx| {
 5874            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5875            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5876            this.refresh_inline_completion(true, false, cx);
 5877        });
 5878    }
 5879
 5880    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5881        if self.read_only(cx) {
 5882            return;
 5883        }
 5884        let mut selections = self.selections.all::<Point>(cx);
 5885        let mut prev_edited_row = 0;
 5886        let mut row_delta = 0;
 5887        let mut edits = Vec::new();
 5888        let buffer = self.buffer.read(cx);
 5889        let snapshot = buffer.snapshot(cx);
 5890        for selection in &mut selections {
 5891            if selection.start.row != prev_edited_row {
 5892                row_delta = 0;
 5893            }
 5894            prev_edited_row = selection.end.row;
 5895
 5896            row_delta =
 5897                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5898        }
 5899
 5900        self.transact(cx, |this, cx| {
 5901            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5902            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5903        });
 5904    }
 5905
 5906    fn indent_selection(
 5907        buffer: &MultiBuffer,
 5908        snapshot: &MultiBufferSnapshot,
 5909        selection: &mut Selection<Point>,
 5910        edits: &mut Vec<(Range<Point>, String)>,
 5911        delta_for_start_row: u32,
 5912        cx: &AppContext,
 5913    ) -> u32 {
 5914        let settings = buffer.settings_at(selection.start, cx);
 5915        let tab_size = settings.tab_size.get();
 5916        let indent_kind = if settings.hard_tabs {
 5917            IndentKind::Tab
 5918        } else {
 5919            IndentKind::Space
 5920        };
 5921        let mut start_row = selection.start.row;
 5922        let mut end_row = selection.end.row + 1;
 5923
 5924        // If a selection ends at the beginning of a line, don't indent
 5925        // that last line.
 5926        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5927            end_row -= 1;
 5928        }
 5929
 5930        // Avoid re-indenting a row that has already been indented by a
 5931        // previous selection, but still update this selection's column
 5932        // to reflect that indentation.
 5933        if delta_for_start_row > 0 {
 5934            start_row += 1;
 5935            selection.start.column += delta_for_start_row;
 5936            if selection.end.row == selection.start.row {
 5937                selection.end.column += delta_for_start_row;
 5938            }
 5939        }
 5940
 5941        let mut delta_for_end_row = 0;
 5942        let has_multiple_rows = start_row + 1 != end_row;
 5943        for row in start_row..end_row {
 5944            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5945            let indent_delta = match (current_indent.kind, indent_kind) {
 5946                (IndentKind::Space, IndentKind::Space) => {
 5947                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5948                    IndentSize::spaces(columns_to_next_tab_stop)
 5949                }
 5950                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5951                (_, IndentKind::Tab) => IndentSize::tab(),
 5952            };
 5953
 5954            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5955                0
 5956            } else {
 5957                selection.start.column
 5958            };
 5959            let row_start = Point::new(row, start);
 5960            edits.push((
 5961                row_start..row_start,
 5962                indent_delta.chars().collect::<String>(),
 5963            ));
 5964
 5965            // Update this selection's endpoints to reflect the indentation.
 5966            if row == selection.start.row {
 5967                selection.start.column += indent_delta.len;
 5968            }
 5969            if row == selection.end.row {
 5970                selection.end.column += indent_delta.len;
 5971                delta_for_end_row = indent_delta.len;
 5972            }
 5973        }
 5974
 5975        if selection.start.row == selection.end.row {
 5976            delta_for_start_row + delta_for_end_row
 5977        } else {
 5978            delta_for_end_row
 5979        }
 5980    }
 5981
 5982    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5983        if self.read_only(cx) {
 5984            return;
 5985        }
 5986        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5987        let selections = self.selections.all::<Point>(cx);
 5988        let mut deletion_ranges = Vec::new();
 5989        let mut last_outdent = None;
 5990        {
 5991            let buffer = self.buffer.read(cx);
 5992            let snapshot = buffer.snapshot(cx);
 5993            for selection in &selections {
 5994                let settings = buffer.settings_at(selection.start, cx);
 5995                let tab_size = settings.tab_size.get();
 5996                let mut rows = selection.spanned_rows(false, &display_map);
 5997
 5998                // Avoid re-outdenting a row that has already been outdented by a
 5999                // previous selection.
 6000                if let Some(last_row) = last_outdent {
 6001                    if last_row == rows.start {
 6002                        rows.start = rows.start.next_row();
 6003                    }
 6004                }
 6005                let has_multiple_rows = rows.len() > 1;
 6006                for row in rows.iter_rows() {
 6007                    let indent_size = snapshot.indent_size_for_line(row);
 6008                    if indent_size.len > 0 {
 6009                        let deletion_len = match indent_size.kind {
 6010                            IndentKind::Space => {
 6011                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6012                                if columns_to_prev_tab_stop == 0 {
 6013                                    tab_size
 6014                                } else {
 6015                                    columns_to_prev_tab_stop
 6016                                }
 6017                            }
 6018                            IndentKind::Tab => 1,
 6019                        };
 6020                        let start = if has_multiple_rows
 6021                            || deletion_len > selection.start.column
 6022                            || indent_size.len < selection.start.column
 6023                        {
 6024                            0
 6025                        } else {
 6026                            selection.start.column - deletion_len
 6027                        };
 6028                        deletion_ranges.push(
 6029                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6030                        );
 6031                        last_outdent = Some(row);
 6032                    }
 6033                }
 6034            }
 6035        }
 6036
 6037        self.transact(cx, |this, cx| {
 6038            this.buffer.update(cx, |buffer, cx| {
 6039                let empty_str: Arc<str> = Arc::default();
 6040                buffer.edit(
 6041                    deletion_ranges
 6042                        .into_iter()
 6043                        .map(|range| (range, empty_str.clone())),
 6044                    None,
 6045                    cx,
 6046                );
 6047            });
 6048            let selections = this.selections.all::<usize>(cx);
 6049            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6050        });
 6051    }
 6052
 6053    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6054        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6055        let selections = self.selections.all::<Point>(cx);
 6056
 6057        let mut new_cursors = Vec::new();
 6058        let mut edit_ranges = Vec::new();
 6059        let mut selections = selections.iter().peekable();
 6060        while let Some(selection) = selections.next() {
 6061            let mut rows = selection.spanned_rows(false, &display_map);
 6062            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6063
 6064            // Accumulate contiguous regions of rows that we want to delete.
 6065            while let Some(next_selection) = selections.peek() {
 6066                let next_rows = next_selection.spanned_rows(false, &display_map);
 6067                if next_rows.start <= rows.end {
 6068                    rows.end = next_rows.end;
 6069                    selections.next().unwrap();
 6070                } else {
 6071                    break;
 6072                }
 6073            }
 6074
 6075            let buffer = &display_map.buffer_snapshot;
 6076            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6077            let edit_end;
 6078            let cursor_buffer_row;
 6079            if buffer.max_point().row >= rows.end.0 {
 6080                // If there's a line after the range, delete the \n from the end of the row range
 6081                // and position the cursor on the next line.
 6082                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6083                cursor_buffer_row = rows.end;
 6084            } else {
 6085                // If there isn't a line after the range, delete the \n from the line before the
 6086                // start of the row range and position the cursor there.
 6087                edit_start = edit_start.saturating_sub(1);
 6088                edit_end = buffer.len();
 6089                cursor_buffer_row = rows.start.previous_row();
 6090            }
 6091
 6092            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6093            *cursor.column_mut() =
 6094                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6095
 6096            new_cursors.push((
 6097                selection.id,
 6098                buffer.anchor_after(cursor.to_point(&display_map)),
 6099            ));
 6100            edit_ranges.push(edit_start..edit_end);
 6101        }
 6102
 6103        self.transact(cx, |this, cx| {
 6104            let buffer = this.buffer.update(cx, |buffer, cx| {
 6105                let empty_str: Arc<str> = Arc::default();
 6106                buffer.edit(
 6107                    edit_ranges
 6108                        .into_iter()
 6109                        .map(|range| (range, empty_str.clone())),
 6110                    None,
 6111                    cx,
 6112                );
 6113                buffer.snapshot(cx)
 6114            });
 6115            let new_selections = new_cursors
 6116                .into_iter()
 6117                .map(|(id, cursor)| {
 6118                    let cursor = cursor.to_point(&buffer);
 6119                    Selection {
 6120                        id,
 6121                        start: cursor,
 6122                        end: cursor,
 6123                        reversed: false,
 6124                        goal: SelectionGoal::None,
 6125                    }
 6126                })
 6127                .collect();
 6128
 6129            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6130                s.select(new_selections);
 6131            });
 6132        });
 6133    }
 6134
 6135    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6136        if self.read_only(cx) {
 6137            return;
 6138        }
 6139        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6140        for selection in self.selections.all::<Point>(cx) {
 6141            let start = MultiBufferRow(selection.start.row);
 6142            let end = if selection.start.row == selection.end.row {
 6143                MultiBufferRow(selection.start.row + 1)
 6144            } else {
 6145                MultiBufferRow(selection.end.row)
 6146            };
 6147
 6148            if let Some(last_row_range) = row_ranges.last_mut() {
 6149                if start <= last_row_range.end {
 6150                    last_row_range.end = end;
 6151                    continue;
 6152                }
 6153            }
 6154            row_ranges.push(start..end);
 6155        }
 6156
 6157        let snapshot = self.buffer.read(cx).snapshot(cx);
 6158        let mut cursor_positions = Vec::new();
 6159        for row_range in &row_ranges {
 6160            let anchor = snapshot.anchor_before(Point::new(
 6161                row_range.end.previous_row().0,
 6162                snapshot.line_len(row_range.end.previous_row()),
 6163            ));
 6164            cursor_positions.push(anchor..anchor);
 6165        }
 6166
 6167        self.transact(cx, |this, cx| {
 6168            for row_range in row_ranges.into_iter().rev() {
 6169                for row in row_range.iter_rows().rev() {
 6170                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6171                    let next_line_row = row.next_row();
 6172                    let indent = snapshot.indent_size_for_line(next_line_row);
 6173                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6174
 6175                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6176                        " "
 6177                    } else {
 6178                        ""
 6179                    };
 6180
 6181                    this.buffer.update(cx, |buffer, cx| {
 6182                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6183                    });
 6184                }
 6185            }
 6186
 6187            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6188                s.select_anchor_ranges(cursor_positions)
 6189            });
 6190        });
 6191    }
 6192
 6193    pub fn sort_lines_case_sensitive(
 6194        &mut self,
 6195        _: &SortLinesCaseSensitive,
 6196        cx: &mut ViewContext<Self>,
 6197    ) {
 6198        self.manipulate_lines(cx, |lines| lines.sort())
 6199    }
 6200
 6201    pub fn sort_lines_case_insensitive(
 6202        &mut self,
 6203        _: &SortLinesCaseInsensitive,
 6204        cx: &mut ViewContext<Self>,
 6205    ) {
 6206        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6207    }
 6208
 6209    pub fn unique_lines_case_insensitive(
 6210        &mut self,
 6211        _: &UniqueLinesCaseInsensitive,
 6212        cx: &mut ViewContext<Self>,
 6213    ) {
 6214        self.manipulate_lines(cx, |lines| {
 6215            let mut seen = HashSet::default();
 6216            lines.retain(|line| seen.insert(line.to_lowercase()));
 6217        })
 6218    }
 6219
 6220    pub fn unique_lines_case_sensitive(
 6221        &mut self,
 6222        _: &UniqueLinesCaseSensitive,
 6223        cx: &mut ViewContext<Self>,
 6224    ) {
 6225        self.manipulate_lines(cx, |lines| {
 6226            let mut seen = HashSet::default();
 6227            lines.retain(|line| seen.insert(*line));
 6228        })
 6229    }
 6230
 6231    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6232        let mut revert_changes = HashMap::default();
 6233        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6234        for hunk in hunks_for_rows(
 6235            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6236            &multi_buffer_snapshot,
 6237        ) {
 6238            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6239        }
 6240        if !revert_changes.is_empty() {
 6241            self.transact(cx, |editor, cx| {
 6242                editor.revert(revert_changes, cx);
 6243            });
 6244        }
 6245    }
 6246
 6247    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6248        let Some(project) = self.project.clone() else {
 6249            return;
 6250        };
 6251        self.reload(project, cx).detach_and_notify_err(cx);
 6252    }
 6253
 6254    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6255        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6256        if !revert_changes.is_empty() {
 6257            self.transact(cx, |editor, cx| {
 6258                editor.revert(revert_changes, cx);
 6259            });
 6260        }
 6261    }
 6262
 6263    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6264        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6265            let project_path = buffer.read(cx).project_path(cx)?;
 6266            let project = self.project.as_ref()?.read(cx);
 6267            let entry = project.entry_for_path(&project_path, cx)?;
 6268            let parent = match &entry.canonical_path {
 6269                Some(canonical_path) => canonical_path.to_path_buf(),
 6270                None => project.absolute_path(&project_path, cx)?,
 6271            }
 6272            .parent()?
 6273            .to_path_buf();
 6274            Some(parent)
 6275        }) {
 6276            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6277        }
 6278    }
 6279
 6280    fn gather_revert_changes(
 6281        &mut self,
 6282        selections: &[Selection<Anchor>],
 6283        cx: &mut ViewContext<'_, Editor>,
 6284    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6285        let mut revert_changes = HashMap::default();
 6286        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6287        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6288            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6289        }
 6290        revert_changes
 6291    }
 6292
 6293    pub fn prepare_revert_change(
 6294        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6295        multi_buffer: &Model<MultiBuffer>,
 6296        hunk: &MultiBufferDiffHunk,
 6297        cx: &AppContext,
 6298    ) -> Option<()> {
 6299        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6300        let buffer = buffer.read(cx);
 6301        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6302        let buffer_snapshot = buffer.snapshot();
 6303        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6304        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6305            probe
 6306                .0
 6307                .start
 6308                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6309                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6310        }) {
 6311            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6312            Some(())
 6313        } else {
 6314            None
 6315        }
 6316    }
 6317
 6318    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6319        self.manipulate_lines(cx, |lines| lines.reverse())
 6320    }
 6321
 6322    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6323        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6324    }
 6325
 6326    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6327    where
 6328        Fn: FnMut(&mut Vec<&str>),
 6329    {
 6330        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6331        let buffer = self.buffer.read(cx).snapshot(cx);
 6332
 6333        let mut edits = Vec::new();
 6334
 6335        let selections = self.selections.all::<Point>(cx);
 6336        let mut selections = selections.iter().peekable();
 6337        let mut contiguous_row_selections = Vec::new();
 6338        let mut new_selections = Vec::new();
 6339        let mut added_lines = 0;
 6340        let mut removed_lines = 0;
 6341
 6342        while let Some(selection) = selections.next() {
 6343            let (start_row, end_row) = consume_contiguous_rows(
 6344                &mut contiguous_row_selections,
 6345                selection,
 6346                &display_map,
 6347                &mut selections,
 6348            );
 6349
 6350            let start_point = Point::new(start_row.0, 0);
 6351            let end_point = Point::new(
 6352                end_row.previous_row().0,
 6353                buffer.line_len(end_row.previous_row()),
 6354            );
 6355            let text = buffer
 6356                .text_for_range(start_point..end_point)
 6357                .collect::<String>();
 6358
 6359            let mut lines = text.split('\n').collect_vec();
 6360
 6361            let lines_before = lines.len();
 6362            callback(&mut lines);
 6363            let lines_after = lines.len();
 6364
 6365            edits.push((start_point..end_point, lines.join("\n")));
 6366
 6367            // Selections must change based on added and removed line count
 6368            let start_row =
 6369                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6370            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6371            new_selections.push(Selection {
 6372                id: selection.id,
 6373                start: start_row,
 6374                end: end_row,
 6375                goal: SelectionGoal::None,
 6376                reversed: selection.reversed,
 6377            });
 6378
 6379            if lines_after > lines_before {
 6380                added_lines += lines_after - lines_before;
 6381            } else if lines_before > lines_after {
 6382                removed_lines += lines_before - lines_after;
 6383            }
 6384        }
 6385
 6386        self.transact(cx, |this, cx| {
 6387            let buffer = this.buffer.update(cx, |buffer, cx| {
 6388                buffer.edit(edits, None, cx);
 6389                buffer.snapshot(cx)
 6390            });
 6391
 6392            // Recalculate offsets on newly edited buffer
 6393            let new_selections = new_selections
 6394                .iter()
 6395                .map(|s| {
 6396                    let start_point = Point::new(s.start.0, 0);
 6397                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6398                    Selection {
 6399                        id: s.id,
 6400                        start: buffer.point_to_offset(start_point),
 6401                        end: buffer.point_to_offset(end_point),
 6402                        goal: s.goal,
 6403                        reversed: s.reversed,
 6404                    }
 6405                })
 6406                .collect();
 6407
 6408            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6409                s.select(new_selections);
 6410            });
 6411
 6412            this.request_autoscroll(Autoscroll::fit(), cx);
 6413        });
 6414    }
 6415
 6416    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6417        self.manipulate_text(cx, |text| text.to_uppercase())
 6418    }
 6419
 6420    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6421        self.manipulate_text(cx, |text| text.to_lowercase())
 6422    }
 6423
 6424    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6425        self.manipulate_text(cx, |text| {
 6426            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6427            // https://github.com/rutrum/convert-case/issues/16
 6428            text.split('\n')
 6429                .map(|line| line.to_case(Case::Title))
 6430                .join("\n")
 6431        })
 6432    }
 6433
 6434    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6435        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6436    }
 6437
 6438    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6439        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6440    }
 6441
 6442    pub fn convert_to_upper_camel_case(
 6443        &mut self,
 6444        _: &ConvertToUpperCamelCase,
 6445        cx: &mut ViewContext<Self>,
 6446    ) {
 6447        self.manipulate_text(cx, |text| {
 6448            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6449            // https://github.com/rutrum/convert-case/issues/16
 6450            text.split('\n')
 6451                .map(|line| line.to_case(Case::UpperCamel))
 6452                .join("\n")
 6453        })
 6454    }
 6455
 6456    pub fn convert_to_lower_camel_case(
 6457        &mut self,
 6458        _: &ConvertToLowerCamelCase,
 6459        cx: &mut ViewContext<Self>,
 6460    ) {
 6461        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6462    }
 6463
 6464    pub fn convert_to_opposite_case(
 6465        &mut self,
 6466        _: &ConvertToOppositeCase,
 6467        cx: &mut ViewContext<Self>,
 6468    ) {
 6469        self.manipulate_text(cx, |text| {
 6470            text.chars()
 6471                .fold(String::with_capacity(text.len()), |mut t, c| {
 6472                    if c.is_uppercase() {
 6473                        t.extend(c.to_lowercase());
 6474                    } else {
 6475                        t.extend(c.to_uppercase());
 6476                    }
 6477                    t
 6478                })
 6479        })
 6480    }
 6481
 6482    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6483    where
 6484        Fn: FnMut(&str) -> String,
 6485    {
 6486        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6487        let buffer = self.buffer.read(cx).snapshot(cx);
 6488
 6489        let mut new_selections = Vec::new();
 6490        let mut edits = Vec::new();
 6491        let mut selection_adjustment = 0i32;
 6492
 6493        for selection in self.selections.all::<usize>(cx) {
 6494            let selection_is_empty = selection.is_empty();
 6495
 6496            let (start, end) = if selection_is_empty {
 6497                let word_range = movement::surrounding_word(
 6498                    &display_map,
 6499                    selection.start.to_display_point(&display_map),
 6500                );
 6501                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6502                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6503                (start, end)
 6504            } else {
 6505                (selection.start, selection.end)
 6506            };
 6507
 6508            let text = buffer.text_for_range(start..end).collect::<String>();
 6509            let old_length = text.len() as i32;
 6510            let text = callback(&text);
 6511
 6512            new_selections.push(Selection {
 6513                start: (start as i32 - selection_adjustment) as usize,
 6514                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6515                goal: SelectionGoal::None,
 6516                ..selection
 6517            });
 6518
 6519            selection_adjustment += old_length - text.len() as i32;
 6520
 6521            edits.push((start..end, text));
 6522        }
 6523
 6524        self.transact(cx, |this, cx| {
 6525            this.buffer.update(cx, |buffer, cx| {
 6526                buffer.edit(edits, None, cx);
 6527            });
 6528
 6529            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6530                s.select(new_selections);
 6531            });
 6532
 6533            this.request_autoscroll(Autoscroll::fit(), cx);
 6534        });
 6535    }
 6536
 6537    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6539        let buffer = &display_map.buffer_snapshot;
 6540        let selections = self.selections.all::<Point>(cx);
 6541
 6542        let mut edits = Vec::new();
 6543        let mut selections_iter = selections.iter().peekable();
 6544        while let Some(selection) = selections_iter.next() {
 6545            // Avoid duplicating the same lines twice.
 6546            let mut rows = selection.spanned_rows(false, &display_map);
 6547
 6548            while let Some(next_selection) = selections_iter.peek() {
 6549                let next_rows = next_selection.spanned_rows(false, &display_map);
 6550                if next_rows.start < rows.end {
 6551                    rows.end = next_rows.end;
 6552                    selections_iter.next().unwrap();
 6553                } else {
 6554                    break;
 6555                }
 6556            }
 6557
 6558            // Copy the text from the selected row region and splice it either at the start
 6559            // or end of the region.
 6560            let start = Point::new(rows.start.0, 0);
 6561            let end = Point::new(
 6562                rows.end.previous_row().0,
 6563                buffer.line_len(rows.end.previous_row()),
 6564            );
 6565            let text = buffer
 6566                .text_for_range(start..end)
 6567                .chain(Some("\n"))
 6568                .collect::<String>();
 6569            let insert_location = if upwards {
 6570                Point::new(rows.end.0, 0)
 6571            } else {
 6572                start
 6573            };
 6574            edits.push((insert_location..insert_location, text));
 6575        }
 6576
 6577        self.transact(cx, |this, cx| {
 6578            this.buffer.update(cx, |buffer, cx| {
 6579                buffer.edit(edits, None, cx);
 6580            });
 6581
 6582            this.request_autoscroll(Autoscroll::fit(), cx);
 6583        });
 6584    }
 6585
 6586    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6587        self.duplicate_line(true, cx);
 6588    }
 6589
 6590    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6591        self.duplicate_line(false, cx);
 6592    }
 6593
 6594    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6595        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6596        let buffer = self.buffer.read(cx).snapshot(cx);
 6597
 6598        let mut edits = Vec::new();
 6599        let mut unfold_ranges = Vec::new();
 6600        let mut refold_ranges = Vec::new();
 6601
 6602        let selections = self.selections.all::<Point>(cx);
 6603        let mut selections = selections.iter().peekable();
 6604        let mut contiguous_row_selections = Vec::new();
 6605        let mut new_selections = Vec::new();
 6606
 6607        while let Some(selection) = selections.next() {
 6608            // Find all the selections that span a contiguous row range
 6609            let (start_row, end_row) = consume_contiguous_rows(
 6610                &mut contiguous_row_selections,
 6611                selection,
 6612                &display_map,
 6613                &mut selections,
 6614            );
 6615
 6616            // Move the text spanned by the row range to be before the line preceding the row range
 6617            if start_row.0 > 0 {
 6618                let range_to_move = Point::new(
 6619                    start_row.previous_row().0,
 6620                    buffer.line_len(start_row.previous_row()),
 6621                )
 6622                    ..Point::new(
 6623                        end_row.previous_row().0,
 6624                        buffer.line_len(end_row.previous_row()),
 6625                    );
 6626                let insertion_point = display_map
 6627                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6628                    .0;
 6629
 6630                // Don't move lines across excerpts
 6631                if buffer
 6632                    .excerpt_boundaries_in_range((
 6633                        Bound::Excluded(insertion_point),
 6634                        Bound::Included(range_to_move.end),
 6635                    ))
 6636                    .next()
 6637                    .is_none()
 6638                {
 6639                    let text = buffer
 6640                        .text_for_range(range_to_move.clone())
 6641                        .flat_map(|s| s.chars())
 6642                        .skip(1)
 6643                        .chain(['\n'])
 6644                        .collect::<String>();
 6645
 6646                    edits.push((
 6647                        buffer.anchor_after(range_to_move.start)
 6648                            ..buffer.anchor_before(range_to_move.end),
 6649                        String::new(),
 6650                    ));
 6651                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6652                    edits.push((insertion_anchor..insertion_anchor, text));
 6653
 6654                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6655
 6656                    // Move selections up
 6657                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6658                        |mut selection| {
 6659                            selection.start.row -= row_delta;
 6660                            selection.end.row -= row_delta;
 6661                            selection
 6662                        },
 6663                    ));
 6664
 6665                    // Move folds up
 6666                    unfold_ranges.push(range_to_move.clone());
 6667                    for fold in display_map.folds_in_range(
 6668                        buffer.anchor_before(range_to_move.start)
 6669                            ..buffer.anchor_after(range_to_move.end),
 6670                    ) {
 6671                        let mut start = fold.range.start.to_point(&buffer);
 6672                        let mut end = fold.range.end.to_point(&buffer);
 6673                        start.row -= row_delta;
 6674                        end.row -= row_delta;
 6675                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6676                    }
 6677                }
 6678            }
 6679
 6680            // If we didn't move line(s), preserve the existing selections
 6681            new_selections.append(&mut contiguous_row_selections);
 6682        }
 6683
 6684        self.transact(cx, |this, cx| {
 6685            this.unfold_ranges(unfold_ranges, true, true, cx);
 6686            this.buffer.update(cx, |buffer, cx| {
 6687                for (range, text) in edits {
 6688                    buffer.edit([(range, text)], None, cx);
 6689                }
 6690            });
 6691            this.fold_ranges(refold_ranges, true, cx);
 6692            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6693                s.select(new_selections);
 6694            })
 6695        });
 6696    }
 6697
 6698    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6699        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6700        let buffer = self.buffer.read(cx).snapshot(cx);
 6701
 6702        let mut edits = Vec::new();
 6703        let mut unfold_ranges = Vec::new();
 6704        let mut refold_ranges = Vec::new();
 6705
 6706        let selections = self.selections.all::<Point>(cx);
 6707        let mut selections = selections.iter().peekable();
 6708        let mut contiguous_row_selections = Vec::new();
 6709        let mut new_selections = Vec::new();
 6710
 6711        while let Some(selection) = selections.next() {
 6712            // Find all the selections that span a contiguous row range
 6713            let (start_row, end_row) = consume_contiguous_rows(
 6714                &mut contiguous_row_selections,
 6715                selection,
 6716                &display_map,
 6717                &mut selections,
 6718            );
 6719
 6720            // Move the text spanned by the row range to be after the last line of the row range
 6721            if end_row.0 <= buffer.max_point().row {
 6722                let range_to_move =
 6723                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6724                let insertion_point = display_map
 6725                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6726                    .0;
 6727
 6728                // Don't move lines across excerpt boundaries
 6729                if buffer
 6730                    .excerpt_boundaries_in_range((
 6731                        Bound::Excluded(range_to_move.start),
 6732                        Bound::Included(insertion_point),
 6733                    ))
 6734                    .next()
 6735                    .is_none()
 6736                {
 6737                    let mut text = String::from("\n");
 6738                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6739                    text.pop(); // Drop trailing newline
 6740                    edits.push((
 6741                        buffer.anchor_after(range_to_move.start)
 6742                            ..buffer.anchor_before(range_to_move.end),
 6743                        String::new(),
 6744                    ));
 6745                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6746                    edits.push((insertion_anchor..insertion_anchor, text));
 6747
 6748                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6749
 6750                    // Move selections down
 6751                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6752                        |mut selection| {
 6753                            selection.start.row += row_delta;
 6754                            selection.end.row += row_delta;
 6755                            selection
 6756                        },
 6757                    ));
 6758
 6759                    // Move folds down
 6760                    unfold_ranges.push(range_to_move.clone());
 6761                    for fold in display_map.folds_in_range(
 6762                        buffer.anchor_before(range_to_move.start)
 6763                            ..buffer.anchor_after(range_to_move.end),
 6764                    ) {
 6765                        let mut start = fold.range.start.to_point(&buffer);
 6766                        let mut end = fold.range.end.to_point(&buffer);
 6767                        start.row += row_delta;
 6768                        end.row += row_delta;
 6769                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6770                    }
 6771                }
 6772            }
 6773
 6774            // If we didn't move line(s), preserve the existing selections
 6775            new_selections.append(&mut contiguous_row_selections);
 6776        }
 6777
 6778        self.transact(cx, |this, cx| {
 6779            this.unfold_ranges(unfold_ranges, true, true, cx);
 6780            this.buffer.update(cx, |buffer, cx| {
 6781                for (range, text) in edits {
 6782                    buffer.edit([(range, text)], None, cx);
 6783                }
 6784            });
 6785            this.fold_ranges(refold_ranges, true, cx);
 6786            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6787        });
 6788    }
 6789
 6790    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6791        let text_layout_details = &self.text_layout_details(cx);
 6792        self.transact(cx, |this, cx| {
 6793            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6794                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6795                let line_mode = s.line_mode;
 6796                s.move_with(|display_map, selection| {
 6797                    if !selection.is_empty() || line_mode {
 6798                        return;
 6799                    }
 6800
 6801                    let mut head = selection.head();
 6802                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6803                    if head.column() == display_map.line_len(head.row()) {
 6804                        transpose_offset = display_map
 6805                            .buffer_snapshot
 6806                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6807                    }
 6808
 6809                    if transpose_offset == 0 {
 6810                        return;
 6811                    }
 6812
 6813                    *head.column_mut() += 1;
 6814                    head = display_map.clip_point(head, Bias::Right);
 6815                    let goal = SelectionGoal::HorizontalPosition(
 6816                        display_map
 6817                            .x_for_display_point(head, text_layout_details)
 6818                            .into(),
 6819                    );
 6820                    selection.collapse_to(head, goal);
 6821
 6822                    let transpose_start = display_map
 6823                        .buffer_snapshot
 6824                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6825                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6826                        let transpose_end = display_map
 6827                            .buffer_snapshot
 6828                            .clip_offset(transpose_offset + 1, Bias::Right);
 6829                        if let Some(ch) =
 6830                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6831                        {
 6832                            edits.push((transpose_start..transpose_offset, String::new()));
 6833                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6834                        }
 6835                    }
 6836                });
 6837                edits
 6838            });
 6839            this.buffer
 6840                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6841            let selections = this.selections.all::<usize>(cx);
 6842            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6843                s.select(selections);
 6844            });
 6845        });
 6846    }
 6847
 6848    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6849        self.rewrap_impl(true, cx)
 6850    }
 6851
 6852    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6853        let buffer = self.buffer.read(cx).snapshot(cx);
 6854        let selections = self.selections.all::<Point>(cx);
 6855        let mut selections = selections.iter().peekable();
 6856
 6857        let mut edits = Vec::new();
 6858        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6859
 6860        while let Some(selection) = selections.next() {
 6861            let mut start_row = selection.start.row;
 6862            let mut end_row = selection.end.row;
 6863
 6864            // Skip selections that overlap with a range that has already been rewrapped.
 6865            let selection_range = start_row..end_row;
 6866            if rewrapped_row_ranges
 6867                .iter()
 6868                .any(|range| range.overlaps(&selection_range))
 6869            {
 6870                continue;
 6871            }
 6872
 6873            let mut should_rewrap = !only_text;
 6874
 6875            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6876                match language_scope.language_name().0.as_ref() {
 6877                    "Markdown" | "Plain Text" => {
 6878                        should_rewrap = true;
 6879                    }
 6880                    _ => {}
 6881                }
 6882            }
 6883
 6884            // Since not all lines in the selection may be at the same indent
 6885            // level, choose the indent size that is the most common between all
 6886            // of the lines.
 6887            //
 6888            // If there is a tie, we use the deepest indent.
 6889            let (indent_size, indent_end) = {
 6890                let mut indent_size_occurrences = HashMap::default();
 6891                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6892
 6893                for row in start_row..=end_row {
 6894                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6895                    rows_by_indent_size.entry(indent).or_default().push(row);
 6896                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6897                }
 6898
 6899                let indent_size = indent_size_occurrences
 6900                    .into_iter()
 6901                    .max_by_key(|(indent, count)| (*count, indent.len))
 6902                    .map(|(indent, _)| indent)
 6903                    .unwrap_or_default();
 6904                let row = rows_by_indent_size[&indent_size][0];
 6905                let indent_end = Point::new(row, indent_size.len);
 6906
 6907                (indent_size, indent_end)
 6908            };
 6909
 6910            let mut line_prefix = indent_size.chars().collect::<String>();
 6911
 6912            if let Some(comment_prefix) =
 6913                buffer
 6914                    .language_scope_at(selection.head())
 6915                    .and_then(|language| {
 6916                        language
 6917                            .line_comment_prefixes()
 6918                            .iter()
 6919                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6920                            .cloned()
 6921                    })
 6922            {
 6923                line_prefix.push_str(&comment_prefix);
 6924                should_rewrap = true;
 6925            }
 6926
 6927            if selection.is_empty() {
 6928                'expand_upwards: while start_row > 0 {
 6929                    let prev_row = start_row - 1;
 6930                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6931                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6932                    {
 6933                        start_row = prev_row;
 6934                    } else {
 6935                        break 'expand_upwards;
 6936                    }
 6937                }
 6938
 6939                'expand_downwards: while end_row < buffer.max_point().row {
 6940                    let next_row = end_row + 1;
 6941                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6942                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6943                    {
 6944                        end_row = next_row;
 6945                    } else {
 6946                        break 'expand_downwards;
 6947                    }
 6948                }
 6949            }
 6950
 6951            if !should_rewrap {
 6952                continue;
 6953            }
 6954
 6955            let start = Point::new(start_row, 0);
 6956            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6957            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6958            let Some(lines_without_prefixes) = selection_text
 6959                .lines()
 6960                .map(|line| {
 6961                    line.strip_prefix(&line_prefix)
 6962                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6963                        .ok_or_else(|| {
 6964                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6965                        })
 6966                })
 6967                .collect::<Result<Vec<_>, _>>()
 6968                .log_err()
 6969            else {
 6970                continue;
 6971            };
 6972
 6973            let unwrapped_text = lines_without_prefixes.join(" ");
 6974            let wrap_column = buffer
 6975                .settings_at(Point::new(start_row, 0), cx)
 6976                .preferred_line_length as usize;
 6977            let mut wrapped_text = String::new();
 6978            let mut current_line = line_prefix.clone();
 6979            for word in unwrapped_text.split_whitespace() {
 6980                if current_line.len() + word.len() >= wrap_column {
 6981                    wrapped_text.push_str(&current_line);
 6982                    wrapped_text.push('\n');
 6983                    current_line.truncate(line_prefix.len());
 6984                }
 6985
 6986                if current_line.len() > line_prefix.len() {
 6987                    current_line.push(' ');
 6988                }
 6989
 6990                current_line.push_str(word);
 6991            }
 6992
 6993            if !current_line.is_empty() {
 6994                wrapped_text.push_str(&current_line);
 6995            }
 6996
 6997            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6998            let mut offset = start.to_offset(&buffer);
 6999            let mut moved_since_edit = true;
 7000
 7001            for change in diff.iter_all_changes() {
 7002                let value = change.value();
 7003                match change.tag() {
 7004                    ChangeTag::Equal => {
 7005                        offset += value.len();
 7006                        moved_since_edit = true;
 7007                    }
 7008                    ChangeTag::Delete => {
 7009                        let start = buffer.anchor_after(offset);
 7010                        let end = buffer.anchor_before(offset + value.len());
 7011
 7012                        if moved_since_edit {
 7013                            edits.push((start..end, String::new()));
 7014                        } else {
 7015                            edits.last_mut().unwrap().0.end = end;
 7016                        }
 7017
 7018                        offset += value.len();
 7019                        moved_since_edit = false;
 7020                    }
 7021                    ChangeTag::Insert => {
 7022                        if moved_since_edit {
 7023                            let anchor = buffer.anchor_after(offset);
 7024                            edits.push((anchor..anchor, value.to_string()));
 7025                        } else {
 7026                            edits.last_mut().unwrap().1.push_str(value);
 7027                        }
 7028
 7029                        moved_since_edit = false;
 7030                    }
 7031                }
 7032            }
 7033
 7034            rewrapped_row_ranges.push(start_row..=end_row);
 7035        }
 7036
 7037        self.buffer
 7038            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7039    }
 7040
 7041    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7042        let mut text = String::new();
 7043        let buffer = self.buffer.read(cx).snapshot(cx);
 7044        let mut selections = self.selections.all::<Point>(cx);
 7045        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7046        {
 7047            let max_point = buffer.max_point();
 7048            let mut is_first = true;
 7049            for selection in &mut selections {
 7050                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7051                if is_entire_line {
 7052                    selection.start = Point::new(selection.start.row, 0);
 7053                    if !selection.is_empty() && selection.end.column == 0 {
 7054                        selection.end = cmp::min(max_point, selection.end);
 7055                    } else {
 7056                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7057                    }
 7058                    selection.goal = SelectionGoal::None;
 7059                }
 7060                if is_first {
 7061                    is_first = false;
 7062                } else {
 7063                    text += "\n";
 7064                }
 7065                let mut len = 0;
 7066                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7067                    text.push_str(chunk);
 7068                    len += chunk.len();
 7069                }
 7070                clipboard_selections.push(ClipboardSelection {
 7071                    len,
 7072                    is_entire_line,
 7073                    first_line_indent: buffer
 7074                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7075                        .len,
 7076                });
 7077            }
 7078        }
 7079
 7080        self.transact(cx, |this, cx| {
 7081            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7082                s.select(selections);
 7083            });
 7084            this.insert("", cx);
 7085            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7086                text,
 7087                clipboard_selections,
 7088            ));
 7089        });
 7090    }
 7091
 7092    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7093        let selections = self.selections.all::<Point>(cx);
 7094        let buffer = self.buffer.read(cx).read(cx);
 7095        let mut text = String::new();
 7096
 7097        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7098        {
 7099            let max_point = buffer.max_point();
 7100            let mut is_first = true;
 7101            for selection in selections.iter() {
 7102                let mut start = selection.start;
 7103                let mut end = selection.end;
 7104                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7105                if is_entire_line {
 7106                    start = Point::new(start.row, 0);
 7107                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7108                }
 7109                if is_first {
 7110                    is_first = false;
 7111                } else {
 7112                    text += "\n";
 7113                }
 7114                let mut len = 0;
 7115                for chunk in buffer.text_for_range(start..end) {
 7116                    text.push_str(chunk);
 7117                    len += chunk.len();
 7118                }
 7119                clipboard_selections.push(ClipboardSelection {
 7120                    len,
 7121                    is_entire_line,
 7122                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7123                });
 7124            }
 7125        }
 7126
 7127        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7128            text,
 7129            clipboard_selections,
 7130        ));
 7131    }
 7132
 7133    pub fn do_paste(
 7134        &mut self,
 7135        text: &String,
 7136        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7137        handle_entire_lines: bool,
 7138        cx: &mut ViewContext<Self>,
 7139    ) {
 7140        if self.read_only(cx) {
 7141            return;
 7142        }
 7143
 7144        let clipboard_text = Cow::Borrowed(text);
 7145
 7146        self.transact(cx, |this, cx| {
 7147            if let Some(mut clipboard_selections) = clipboard_selections {
 7148                let old_selections = this.selections.all::<usize>(cx);
 7149                let all_selections_were_entire_line =
 7150                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7151                let first_selection_indent_column =
 7152                    clipboard_selections.first().map(|s| s.first_line_indent);
 7153                if clipboard_selections.len() != old_selections.len() {
 7154                    clipboard_selections.drain(..);
 7155                }
 7156
 7157                this.buffer.update(cx, |buffer, cx| {
 7158                    let snapshot = buffer.read(cx);
 7159                    let mut start_offset = 0;
 7160                    let mut edits = Vec::new();
 7161                    let mut original_indent_columns = Vec::new();
 7162                    for (ix, selection) in old_selections.iter().enumerate() {
 7163                        let to_insert;
 7164                        let entire_line;
 7165                        let original_indent_column;
 7166                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7167                            let end_offset = start_offset + clipboard_selection.len;
 7168                            to_insert = &clipboard_text[start_offset..end_offset];
 7169                            entire_line = clipboard_selection.is_entire_line;
 7170                            start_offset = end_offset + 1;
 7171                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7172                        } else {
 7173                            to_insert = clipboard_text.as_str();
 7174                            entire_line = all_selections_were_entire_line;
 7175                            original_indent_column = first_selection_indent_column
 7176                        }
 7177
 7178                        // If the corresponding selection was empty when this slice of the
 7179                        // clipboard text was written, then the entire line containing the
 7180                        // selection was copied. If this selection is also currently empty,
 7181                        // then paste the line before the current line of the buffer.
 7182                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7183                            let column = selection.start.to_point(&snapshot).column as usize;
 7184                            let line_start = selection.start - column;
 7185                            line_start..line_start
 7186                        } else {
 7187                            selection.range()
 7188                        };
 7189
 7190                        edits.push((range, to_insert));
 7191                        original_indent_columns.extend(original_indent_column);
 7192                    }
 7193                    drop(snapshot);
 7194
 7195                    buffer.edit(
 7196                        edits,
 7197                        Some(AutoindentMode::Block {
 7198                            original_indent_columns,
 7199                        }),
 7200                        cx,
 7201                    );
 7202                });
 7203
 7204                let selections = this.selections.all::<usize>(cx);
 7205                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7206            } else {
 7207                this.insert(&clipboard_text, cx);
 7208            }
 7209        });
 7210    }
 7211
 7212    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7213        if let Some(item) = cx.read_from_clipboard() {
 7214            let entries = item.entries();
 7215
 7216            match entries.first() {
 7217                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7218                // of all the pasted entries.
 7219                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7220                    .do_paste(
 7221                        clipboard_string.text(),
 7222                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7223                        true,
 7224                        cx,
 7225                    ),
 7226                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7227            }
 7228        }
 7229    }
 7230
 7231    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7232        if self.read_only(cx) {
 7233            return;
 7234        }
 7235
 7236        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7237            if let Some((selections, _)) =
 7238                self.selection_history.transaction(transaction_id).cloned()
 7239            {
 7240                self.change_selections(None, cx, |s| {
 7241                    s.select_anchors(selections.to_vec());
 7242                });
 7243            }
 7244            self.request_autoscroll(Autoscroll::fit(), cx);
 7245            self.unmark_text(cx);
 7246            self.refresh_inline_completion(true, false, cx);
 7247            cx.emit(EditorEvent::Edited { transaction_id });
 7248            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7249        }
 7250    }
 7251
 7252    pub fn redo(&mut self, _: &Redo, 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.redo(cx)) {
 7258            if let Some((_, 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        }
 7270    }
 7271
 7272    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7273        self.buffer
 7274            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7275    }
 7276
 7277    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7278        self.buffer
 7279            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7280    }
 7281
 7282    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7284            let line_mode = s.line_mode;
 7285            s.move_with(|map, selection| {
 7286                let cursor = if selection.is_empty() && !line_mode {
 7287                    movement::left(map, selection.start)
 7288                } else {
 7289                    selection.start
 7290                };
 7291                selection.collapse_to(cursor, SelectionGoal::None);
 7292            });
 7293        })
 7294    }
 7295
 7296    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7297        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7298            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7299        })
 7300    }
 7301
 7302    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7304            let line_mode = s.line_mode;
 7305            s.move_with(|map, selection| {
 7306                let cursor = if selection.is_empty() && !line_mode {
 7307                    movement::right(map, selection.end)
 7308                } else {
 7309                    selection.end
 7310                };
 7311                selection.collapse_to(cursor, SelectionGoal::None)
 7312            });
 7313        })
 7314    }
 7315
 7316    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7317        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7318            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7319        })
 7320    }
 7321
 7322    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7323        if self.take_rename(true, cx).is_some() {
 7324            return;
 7325        }
 7326
 7327        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7328            cx.propagate();
 7329            return;
 7330        }
 7331
 7332        let text_layout_details = &self.text_layout_details(cx);
 7333        let selection_count = self.selections.count();
 7334        let first_selection = self.selections.first_anchor();
 7335
 7336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7337            let line_mode = s.line_mode;
 7338            s.move_with(|map, selection| {
 7339                if !selection.is_empty() && !line_mode {
 7340                    selection.goal = SelectionGoal::None;
 7341                }
 7342                let (cursor, goal) = movement::up(
 7343                    map,
 7344                    selection.start,
 7345                    selection.goal,
 7346                    false,
 7347                    text_layout_details,
 7348                );
 7349                selection.collapse_to(cursor, goal);
 7350            });
 7351        });
 7352
 7353        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7354        {
 7355            cx.propagate();
 7356        }
 7357    }
 7358
 7359    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7360        if self.take_rename(true, cx).is_some() {
 7361            return;
 7362        }
 7363
 7364        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7365            cx.propagate();
 7366            return;
 7367        }
 7368
 7369        let text_layout_details = &self.text_layout_details(cx);
 7370
 7371        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7372            let line_mode = s.line_mode;
 7373            s.move_with(|map, selection| {
 7374                if !selection.is_empty() && !line_mode {
 7375                    selection.goal = SelectionGoal::None;
 7376                }
 7377                let (cursor, goal) = movement::up_by_rows(
 7378                    map,
 7379                    selection.start,
 7380                    action.lines,
 7381                    selection.goal,
 7382                    false,
 7383                    text_layout_details,
 7384                );
 7385                selection.collapse_to(cursor, goal);
 7386            });
 7387        })
 7388    }
 7389
 7390    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7391        if self.take_rename(true, cx).is_some() {
 7392            return;
 7393        }
 7394
 7395        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7396            cx.propagate();
 7397            return;
 7398        }
 7399
 7400        let text_layout_details = &self.text_layout_details(cx);
 7401
 7402        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7403            let line_mode = s.line_mode;
 7404            s.move_with(|map, selection| {
 7405                if !selection.is_empty() && !line_mode {
 7406                    selection.goal = SelectionGoal::None;
 7407                }
 7408                let (cursor, goal) = movement::down_by_rows(
 7409                    map,
 7410                    selection.start,
 7411                    action.lines,
 7412                    selection.goal,
 7413                    false,
 7414                    text_layout_details,
 7415                );
 7416                selection.collapse_to(cursor, goal);
 7417            });
 7418        })
 7419    }
 7420
 7421    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7422        let text_layout_details = &self.text_layout_details(cx);
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            s.move_heads_with(|map, head, goal| {
 7425                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7426            })
 7427        })
 7428    }
 7429
 7430    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7431        let text_layout_details = &self.text_layout_details(cx);
 7432        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7433            s.move_heads_with(|map, head, goal| {
 7434                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7435            })
 7436        })
 7437    }
 7438
 7439    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7440        let Some(row_count) = self.visible_row_count() else {
 7441            return;
 7442        };
 7443
 7444        let text_layout_details = &self.text_layout_details(cx);
 7445
 7446        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7447            s.move_heads_with(|map, head, goal| {
 7448                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7449            })
 7450        })
 7451    }
 7452
 7453    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7454        if self.take_rename(true, cx).is_some() {
 7455            return;
 7456        }
 7457
 7458        if self
 7459            .context_menu
 7460            .write()
 7461            .as_mut()
 7462            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7463            .unwrap_or(false)
 7464        {
 7465            return;
 7466        }
 7467
 7468        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7469            cx.propagate();
 7470            return;
 7471        }
 7472
 7473        let Some(row_count) = self.visible_row_count() else {
 7474            return;
 7475        };
 7476
 7477        let autoscroll = if action.center_cursor {
 7478            Autoscroll::center()
 7479        } else {
 7480            Autoscroll::fit()
 7481        };
 7482
 7483        let text_layout_details = &self.text_layout_details(cx);
 7484
 7485        self.change_selections(Some(autoscroll), cx, |s| {
 7486            let line_mode = s.line_mode;
 7487            s.move_with(|map, selection| {
 7488                if !selection.is_empty() && !line_mode {
 7489                    selection.goal = SelectionGoal::None;
 7490                }
 7491                let (cursor, goal) = movement::up_by_rows(
 7492                    map,
 7493                    selection.end,
 7494                    row_count,
 7495                    selection.goal,
 7496                    false,
 7497                    text_layout_details,
 7498                );
 7499                selection.collapse_to(cursor, goal);
 7500            });
 7501        });
 7502    }
 7503
 7504    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7505        let text_layout_details = &self.text_layout_details(cx);
 7506        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7507            s.move_heads_with(|map, head, goal| {
 7508                movement::up(map, head, goal, false, text_layout_details)
 7509            })
 7510        })
 7511    }
 7512
 7513    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7514        self.take_rename(true, cx);
 7515
 7516        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7517            cx.propagate();
 7518            return;
 7519        }
 7520
 7521        let text_layout_details = &self.text_layout_details(cx);
 7522        let selection_count = self.selections.count();
 7523        let first_selection = self.selections.first_anchor();
 7524
 7525        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7526            let line_mode = s.line_mode;
 7527            s.move_with(|map, selection| {
 7528                if !selection.is_empty() && !line_mode {
 7529                    selection.goal = SelectionGoal::None;
 7530                }
 7531                let (cursor, goal) = movement::down(
 7532                    map,
 7533                    selection.end,
 7534                    selection.goal,
 7535                    false,
 7536                    text_layout_details,
 7537                );
 7538                selection.collapse_to(cursor, goal);
 7539            });
 7540        });
 7541
 7542        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7543        {
 7544            cx.propagate();
 7545        }
 7546    }
 7547
 7548    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7549        let Some(row_count) = self.visible_row_count() else {
 7550            return;
 7551        };
 7552
 7553        let text_layout_details = &self.text_layout_details(cx);
 7554
 7555        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7556            s.move_heads_with(|map, head, goal| {
 7557                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7558            })
 7559        })
 7560    }
 7561
 7562    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7563        if self.take_rename(true, cx).is_some() {
 7564            return;
 7565        }
 7566
 7567        if self
 7568            .context_menu
 7569            .write()
 7570            .as_mut()
 7571            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7572            .unwrap_or(false)
 7573        {
 7574            return;
 7575        }
 7576
 7577        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7578            cx.propagate();
 7579            return;
 7580        }
 7581
 7582        let Some(row_count) = self.visible_row_count() else {
 7583            return;
 7584        };
 7585
 7586        let autoscroll = if action.center_cursor {
 7587            Autoscroll::center()
 7588        } else {
 7589            Autoscroll::fit()
 7590        };
 7591
 7592        let text_layout_details = &self.text_layout_details(cx);
 7593        self.change_selections(Some(autoscroll), cx, |s| {
 7594            let line_mode = s.line_mode;
 7595            s.move_with(|map, selection| {
 7596                if !selection.is_empty() && !line_mode {
 7597                    selection.goal = SelectionGoal::None;
 7598                }
 7599                let (cursor, goal) = movement::down_by_rows(
 7600                    map,
 7601                    selection.end,
 7602                    row_count,
 7603                    selection.goal,
 7604                    false,
 7605                    text_layout_details,
 7606                );
 7607                selection.collapse_to(cursor, goal);
 7608            });
 7609        });
 7610    }
 7611
 7612    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7613        let text_layout_details = &self.text_layout_details(cx);
 7614        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7615            s.move_heads_with(|map, head, goal| {
 7616                movement::down(map, head, goal, false, text_layout_details)
 7617            })
 7618        });
 7619    }
 7620
 7621    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7622        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7623            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7624        }
 7625    }
 7626
 7627    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7628        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7629            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7630        }
 7631    }
 7632
 7633    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7634        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7635            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7636        }
 7637    }
 7638
 7639    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7640        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7641            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7642        }
 7643    }
 7644
 7645    pub fn move_to_previous_word_start(
 7646        &mut self,
 7647        _: &MoveToPreviousWordStart,
 7648        cx: &mut ViewContext<Self>,
 7649    ) {
 7650        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7651            s.move_cursors_with(|map, head, _| {
 7652                (
 7653                    movement::previous_word_start(map, head),
 7654                    SelectionGoal::None,
 7655                )
 7656            });
 7657        })
 7658    }
 7659
 7660    pub fn move_to_previous_subword_start(
 7661        &mut self,
 7662        _: &MoveToPreviousSubwordStart,
 7663        cx: &mut ViewContext<Self>,
 7664    ) {
 7665        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7666            s.move_cursors_with(|map, head, _| {
 7667                (
 7668                    movement::previous_subword_start(map, head),
 7669                    SelectionGoal::None,
 7670                )
 7671            });
 7672        })
 7673    }
 7674
 7675    pub fn select_to_previous_word_start(
 7676        &mut self,
 7677        _: &SelectToPreviousWordStart,
 7678        cx: &mut ViewContext<Self>,
 7679    ) {
 7680        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7681            s.move_heads_with(|map, head, _| {
 7682                (
 7683                    movement::previous_word_start(map, head),
 7684                    SelectionGoal::None,
 7685                )
 7686            });
 7687        })
 7688    }
 7689
 7690    pub fn select_to_previous_subword_start(
 7691        &mut self,
 7692        _: &SelectToPreviousSubwordStart,
 7693        cx: &mut ViewContext<Self>,
 7694    ) {
 7695        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7696            s.move_heads_with(|map, head, _| {
 7697                (
 7698                    movement::previous_subword_start(map, head),
 7699                    SelectionGoal::None,
 7700                )
 7701            });
 7702        })
 7703    }
 7704
 7705    pub fn delete_to_previous_word_start(
 7706        &mut self,
 7707        action: &DeleteToPreviousWordStart,
 7708        cx: &mut ViewContext<Self>,
 7709    ) {
 7710        self.transact(cx, |this, cx| {
 7711            this.select_autoclose_pair(cx);
 7712            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7713                let line_mode = s.line_mode;
 7714                s.move_with(|map, selection| {
 7715                    if selection.is_empty() && !line_mode {
 7716                        let cursor = if action.ignore_newlines {
 7717                            movement::previous_word_start(map, selection.head())
 7718                        } else {
 7719                            movement::previous_word_start_or_newline(map, selection.head())
 7720                        };
 7721                        selection.set_head(cursor, SelectionGoal::None);
 7722                    }
 7723                });
 7724            });
 7725            this.insert("", cx);
 7726        });
 7727    }
 7728
 7729    pub fn delete_to_previous_subword_start(
 7730        &mut self,
 7731        _: &DeleteToPreviousSubwordStart,
 7732        cx: &mut ViewContext<Self>,
 7733    ) {
 7734        self.transact(cx, |this, cx| {
 7735            this.select_autoclose_pair(cx);
 7736            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7737                let line_mode = s.line_mode;
 7738                s.move_with(|map, selection| {
 7739                    if selection.is_empty() && !line_mode {
 7740                        let cursor = movement::previous_subword_start(map, selection.head());
 7741                        selection.set_head(cursor, SelectionGoal::None);
 7742                    }
 7743                });
 7744            });
 7745            this.insert("", cx);
 7746        });
 7747    }
 7748
 7749    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7750        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7751            s.move_cursors_with(|map, head, _| {
 7752                (movement::next_word_end(map, head), SelectionGoal::None)
 7753            });
 7754        })
 7755    }
 7756
 7757    pub fn move_to_next_subword_end(
 7758        &mut self,
 7759        _: &MoveToNextSubwordEnd,
 7760        cx: &mut ViewContext<Self>,
 7761    ) {
 7762        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7763            s.move_cursors_with(|map, head, _| {
 7764                (movement::next_subword_end(map, head), SelectionGoal::None)
 7765            });
 7766        })
 7767    }
 7768
 7769    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7770        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7771            s.move_heads_with(|map, head, _| {
 7772                (movement::next_word_end(map, head), SelectionGoal::None)
 7773            });
 7774        })
 7775    }
 7776
 7777    pub fn select_to_next_subword_end(
 7778        &mut self,
 7779        _: &SelectToNextSubwordEnd,
 7780        cx: &mut ViewContext<Self>,
 7781    ) {
 7782        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7783            s.move_heads_with(|map, head, _| {
 7784                (movement::next_subword_end(map, head), SelectionGoal::None)
 7785            });
 7786        })
 7787    }
 7788
 7789    pub fn delete_to_next_word_end(
 7790        &mut self,
 7791        action: &DeleteToNextWordEnd,
 7792        cx: &mut ViewContext<Self>,
 7793    ) {
 7794        self.transact(cx, |this, cx| {
 7795            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7796                let line_mode = s.line_mode;
 7797                s.move_with(|map, selection| {
 7798                    if selection.is_empty() && !line_mode {
 7799                        let cursor = if action.ignore_newlines {
 7800                            movement::next_word_end(map, selection.head())
 7801                        } else {
 7802                            movement::next_word_end_or_newline(map, selection.head())
 7803                        };
 7804                        selection.set_head(cursor, SelectionGoal::None);
 7805                    }
 7806                });
 7807            });
 7808            this.insert("", cx);
 7809        });
 7810    }
 7811
 7812    pub fn delete_to_next_subword_end(
 7813        &mut self,
 7814        _: &DeleteToNextSubwordEnd,
 7815        cx: &mut ViewContext<Self>,
 7816    ) {
 7817        self.transact(cx, |this, cx| {
 7818            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7819                s.move_with(|map, selection| {
 7820                    if selection.is_empty() {
 7821                        let cursor = movement::next_subword_end(map, selection.head());
 7822                        selection.set_head(cursor, SelectionGoal::None);
 7823                    }
 7824                });
 7825            });
 7826            this.insert("", cx);
 7827        });
 7828    }
 7829
 7830    pub fn move_to_beginning_of_line(
 7831        &mut self,
 7832        action: &MoveToBeginningOfLine,
 7833        cx: &mut ViewContext<Self>,
 7834    ) {
 7835        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7836            s.move_cursors_with(|map, head, _| {
 7837                (
 7838                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7839                    SelectionGoal::None,
 7840                )
 7841            });
 7842        })
 7843    }
 7844
 7845    pub fn select_to_beginning_of_line(
 7846        &mut self,
 7847        action: &SelectToBeginningOfLine,
 7848        cx: &mut ViewContext<Self>,
 7849    ) {
 7850        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7851            s.move_heads_with(|map, head, _| {
 7852                (
 7853                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7854                    SelectionGoal::None,
 7855                )
 7856            });
 7857        });
 7858    }
 7859
 7860    pub fn delete_to_beginning_of_line(
 7861        &mut self,
 7862        _: &DeleteToBeginningOfLine,
 7863        cx: &mut ViewContext<Self>,
 7864    ) {
 7865        self.transact(cx, |this, cx| {
 7866            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7867                s.move_with(|_, selection| {
 7868                    selection.reversed = true;
 7869                });
 7870            });
 7871
 7872            this.select_to_beginning_of_line(
 7873                &SelectToBeginningOfLine {
 7874                    stop_at_soft_wraps: false,
 7875                },
 7876                cx,
 7877            );
 7878            this.backspace(&Backspace, cx);
 7879        });
 7880    }
 7881
 7882    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7883        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7884            s.move_cursors_with(|map, head, _| {
 7885                (
 7886                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7887                    SelectionGoal::None,
 7888                )
 7889            });
 7890        })
 7891    }
 7892
 7893    pub fn select_to_end_of_line(
 7894        &mut self,
 7895        action: &SelectToEndOfLine,
 7896        cx: &mut ViewContext<Self>,
 7897    ) {
 7898        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7899            s.move_heads_with(|map, head, _| {
 7900                (
 7901                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7902                    SelectionGoal::None,
 7903                )
 7904            });
 7905        })
 7906    }
 7907
 7908    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7909        self.transact(cx, |this, cx| {
 7910            this.select_to_end_of_line(
 7911                &SelectToEndOfLine {
 7912                    stop_at_soft_wraps: false,
 7913                },
 7914                cx,
 7915            );
 7916            this.delete(&Delete, cx);
 7917        });
 7918    }
 7919
 7920    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7921        self.transact(cx, |this, cx| {
 7922            this.select_to_end_of_line(
 7923                &SelectToEndOfLine {
 7924                    stop_at_soft_wraps: false,
 7925                },
 7926                cx,
 7927            );
 7928            this.cut(&Cut, cx);
 7929        });
 7930    }
 7931
 7932    pub fn move_to_start_of_paragraph(
 7933        &mut self,
 7934        _: &MoveToStartOfParagraph,
 7935        cx: &mut ViewContext<Self>,
 7936    ) {
 7937        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7938            cx.propagate();
 7939            return;
 7940        }
 7941
 7942        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7943            s.move_with(|map, selection| {
 7944                selection.collapse_to(
 7945                    movement::start_of_paragraph(map, selection.head(), 1),
 7946                    SelectionGoal::None,
 7947                )
 7948            });
 7949        })
 7950    }
 7951
 7952    pub fn move_to_end_of_paragraph(
 7953        &mut self,
 7954        _: &MoveToEndOfParagraph,
 7955        cx: &mut ViewContext<Self>,
 7956    ) {
 7957        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7958            cx.propagate();
 7959            return;
 7960        }
 7961
 7962        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7963            s.move_with(|map, selection| {
 7964                selection.collapse_to(
 7965                    movement::end_of_paragraph(map, selection.head(), 1),
 7966                    SelectionGoal::None,
 7967                )
 7968            });
 7969        })
 7970    }
 7971
 7972    pub fn select_to_start_of_paragraph(
 7973        &mut self,
 7974        _: &SelectToStartOfParagraph,
 7975        cx: &mut ViewContext<Self>,
 7976    ) {
 7977        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7978            cx.propagate();
 7979            return;
 7980        }
 7981
 7982        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7983            s.move_heads_with(|map, head, _| {
 7984                (
 7985                    movement::start_of_paragraph(map, head, 1),
 7986                    SelectionGoal::None,
 7987                )
 7988            });
 7989        })
 7990    }
 7991
 7992    pub fn select_to_end_of_paragraph(
 7993        &mut self,
 7994        _: &SelectToEndOfParagraph,
 7995        cx: &mut ViewContext<Self>,
 7996    ) {
 7997        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7998            cx.propagate();
 7999            return;
 8000        }
 8001
 8002        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8003            s.move_heads_with(|map, head, _| {
 8004                (
 8005                    movement::end_of_paragraph(map, head, 1),
 8006                    SelectionGoal::None,
 8007                )
 8008            });
 8009        })
 8010    }
 8011
 8012    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8013        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8014            cx.propagate();
 8015            return;
 8016        }
 8017
 8018        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8019            s.select_ranges(vec![0..0]);
 8020        });
 8021    }
 8022
 8023    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8024        let mut selection = self.selections.last::<Point>(cx);
 8025        selection.set_head(Point::zero(), SelectionGoal::None);
 8026
 8027        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8028            s.select(vec![selection]);
 8029        });
 8030    }
 8031
 8032    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8033        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8034            cx.propagate();
 8035            return;
 8036        }
 8037
 8038        let cursor = self.buffer.read(cx).read(cx).len();
 8039        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8040            s.select_ranges(vec![cursor..cursor])
 8041        });
 8042    }
 8043
 8044    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8045        self.nav_history = nav_history;
 8046    }
 8047
 8048    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8049        self.nav_history.as_ref()
 8050    }
 8051
 8052    fn push_to_nav_history(
 8053        &mut self,
 8054        cursor_anchor: Anchor,
 8055        new_position: Option<Point>,
 8056        cx: &mut ViewContext<Self>,
 8057    ) {
 8058        if let Some(nav_history) = self.nav_history.as_mut() {
 8059            let buffer = self.buffer.read(cx).read(cx);
 8060            let cursor_position = cursor_anchor.to_point(&buffer);
 8061            let scroll_state = self.scroll_manager.anchor();
 8062            let scroll_top_row = scroll_state.top_row(&buffer);
 8063            drop(buffer);
 8064
 8065            if let Some(new_position) = new_position {
 8066                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8067                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8068                    return;
 8069                }
 8070            }
 8071
 8072            nav_history.push(
 8073                Some(NavigationData {
 8074                    cursor_anchor,
 8075                    cursor_position,
 8076                    scroll_anchor: scroll_state,
 8077                    scroll_top_row,
 8078                }),
 8079                cx,
 8080            );
 8081        }
 8082    }
 8083
 8084    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8085        let buffer = self.buffer.read(cx).snapshot(cx);
 8086        let mut selection = self.selections.first::<usize>(cx);
 8087        selection.set_head(buffer.len(), SelectionGoal::None);
 8088        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8089            s.select(vec![selection]);
 8090        });
 8091    }
 8092
 8093    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8094        let end = self.buffer.read(cx).read(cx).len();
 8095        self.change_selections(None, cx, |s| {
 8096            s.select_ranges(vec![0..end]);
 8097        });
 8098    }
 8099
 8100    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8102        let mut selections = self.selections.all::<Point>(cx);
 8103        let max_point = display_map.buffer_snapshot.max_point();
 8104        for selection in &mut selections {
 8105            let rows = selection.spanned_rows(true, &display_map);
 8106            selection.start = Point::new(rows.start.0, 0);
 8107            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8108            selection.reversed = false;
 8109        }
 8110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8111            s.select(selections);
 8112        });
 8113    }
 8114
 8115    pub fn split_selection_into_lines(
 8116        &mut self,
 8117        _: &SplitSelectionIntoLines,
 8118        cx: &mut ViewContext<Self>,
 8119    ) {
 8120        let mut to_unfold = Vec::new();
 8121        let mut new_selection_ranges = Vec::new();
 8122        {
 8123            let selections = self.selections.all::<Point>(cx);
 8124            let buffer = self.buffer.read(cx).read(cx);
 8125            for selection in selections {
 8126                for row in selection.start.row..selection.end.row {
 8127                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8128                    new_selection_ranges.push(cursor..cursor);
 8129                }
 8130                new_selection_ranges.push(selection.end..selection.end);
 8131                to_unfold.push(selection.start..selection.end);
 8132            }
 8133        }
 8134        self.unfold_ranges(to_unfold, true, true, cx);
 8135        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8136            s.select_ranges(new_selection_ranges);
 8137        });
 8138    }
 8139
 8140    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8141        self.add_selection(true, cx);
 8142    }
 8143
 8144    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8145        self.add_selection(false, cx);
 8146    }
 8147
 8148    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8150        let mut selections = self.selections.all::<Point>(cx);
 8151        let text_layout_details = self.text_layout_details(cx);
 8152        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8153            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8154            let range = oldest_selection.display_range(&display_map).sorted();
 8155
 8156            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8157            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8158            let positions = start_x.min(end_x)..start_x.max(end_x);
 8159
 8160            selections.clear();
 8161            let mut stack = Vec::new();
 8162            for row in range.start.row().0..=range.end.row().0 {
 8163                if let Some(selection) = self.selections.build_columnar_selection(
 8164                    &display_map,
 8165                    DisplayRow(row),
 8166                    &positions,
 8167                    oldest_selection.reversed,
 8168                    &text_layout_details,
 8169                ) {
 8170                    stack.push(selection.id);
 8171                    selections.push(selection);
 8172                }
 8173            }
 8174
 8175            if above {
 8176                stack.reverse();
 8177            }
 8178
 8179            AddSelectionsState { above, stack }
 8180        });
 8181
 8182        let last_added_selection = *state.stack.last().unwrap();
 8183        let mut new_selections = Vec::new();
 8184        if above == state.above {
 8185            let end_row = if above {
 8186                DisplayRow(0)
 8187            } else {
 8188                display_map.max_point().row()
 8189            };
 8190
 8191            'outer: for selection in selections {
 8192                if selection.id == last_added_selection {
 8193                    let range = selection.display_range(&display_map).sorted();
 8194                    debug_assert_eq!(range.start.row(), range.end.row());
 8195                    let mut row = range.start.row();
 8196                    let positions =
 8197                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8198                            px(start)..px(end)
 8199                        } else {
 8200                            let start_x =
 8201                                display_map.x_for_display_point(range.start, &text_layout_details);
 8202                            let end_x =
 8203                                display_map.x_for_display_point(range.end, &text_layout_details);
 8204                            start_x.min(end_x)..start_x.max(end_x)
 8205                        };
 8206
 8207                    while row != end_row {
 8208                        if above {
 8209                            row.0 -= 1;
 8210                        } else {
 8211                            row.0 += 1;
 8212                        }
 8213
 8214                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8215                            &display_map,
 8216                            row,
 8217                            &positions,
 8218                            selection.reversed,
 8219                            &text_layout_details,
 8220                        ) {
 8221                            state.stack.push(new_selection.id);
 8222                            if above {
 8223                                new_selections.push(new_selection);
 8224                                new_selections.push(selection);
 8225                            } else {
 8226                                new_selections.push(selection);
 8227                                new_selections.push(new_selection);
 8228                            }
 8229
 8230                            continue 'outer;
 8231                        }
 8232                    }
 8233                }
 8234
 8235                new_selections.push(selection);
 8236            }
 8237        } else {
 8238            new_selections = selections;
 8239            new_selections.retain(|s| s.id != last_added_selection);
 8240            state.stack.pop();
 8241        }
 8242
 8243        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8244            s.select(new_selections);
 8245        });
 8246        if state.stack.len() > 1 {
 8247            self.add_selections_state = Some(state);
 8248        }
 8249    }
 8250
 8251    pub fn select_next_match_internal(
 8252        &mut self,
 8253        display_map: &DisplaySnapshot,
 8254        replace_newest: bool,
 8255        autoscroll: Option<Autoscroll>,
 8256        cx: &mut ViewContext<Self>,
 8257    ) -> Result<()> {
 8258        fn select_next_match_ranges(
 8259            this: &mut Editor,
 8260            range: Range<usize>,
 8261            replace_newest: bool,
 8262            auto_scroll: Option<Autoscroll>,
 8263            cx: &mut ViewContext<Editor>,
 8264        ) {
 8265            this.unfold_ranges([range.clone()], false, true, cx);
 8266            this.change_selections(auto_scroll, cx, |s| {
 8267                if replace_newest {
 8268                    s.delete(s.newest_anchor().id);
 8269                }
 8270                s.insert_range(range.clone());
 8271            });
 8272        }
 8273
 8274        let buffer = &display_map.buffer_snapshot;
 8275        let mut selections = self.selections.all::<usize>(cx);
 8276        if let Some(mut select_next_state) = self.select_next_state.take() {
 8277            let query = &select_next_state.query;
 8278            if !select_next_state.done {
 8279                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8280                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8281                let mut next_selected_range = None;
 8282
 8283                let bytes_after_last_selection =
 8284                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8285                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8286                let query_matches = query
 8287                    .stream_find_iter(bytes_after_last_selection)
 8288                    .map(|result| (last_selection.end, result))
 8289                    .chain(
 8290                        query
 8291                            .stream_find_iter(bytes_before_first_selection)
 8292                            .map(|result| (0, result)),
 8293                    );
 8294
 8295                for (start_offset, query_match) in query_matches {
 8296                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8297                    let offset_range =
 8298                        start_offset + query_match.start()..start_offset + query_match.end();
 8299                    let display_range = offset_range.start.to_display_point(display_map)
 8300                        ..offset_range.end.to_display_point(display_map);
 8301
 8302                    if !select_next_state.wordwise
 8303                        || (!movement::is_inside_word(display_map, display_range.start)
 8304                            && !movement::is_inside_word(display_map, display_range.end))
 8305                    {
 8306                        // TODO: This is n^2, because we might check all the selections
 8307                        if !selections
 8308                            .iter()
 8309                            .any(|selection| selection.range().overlaps(&offset_range))
 8310                        {
 8311                            next_selected_range = Some(offset_range);
 8312                            break;
 8313                        }
 8314                    }
 8315                }
 8316
 8317                if let Some(next_selected_range) = next_selected_range {
 8318                    select_next_match_ranges(
 8319                        self,
 8320                        next_selected_range,
 8321                        replace_newest,
 8322                        autoscroll,
 8323                        cx,
 8324                    );
 8325                } else {
 8326                    select_next_state.done = true;
 8327                }
 8328            }
 8329
 8330            self.select_next_state = Some(select_next_state);
 8331        } else {
 8332            let mut only_carets = true;
 8333            let mut same_text_selected = true;
 8334            let mut selected_text = None;
 8335
 8336            let mut selections_iter = selections.iter().peekable();
 8337            while let Some(selection) = selections_iter.next() {
 8338                if selection.start != selection.end {
 8339                    only_carets = false;
 8340                }
 8341
 8342                if same_text_selected {
 8343                    if selected_text.is_none() {
 8344                        selected_text =
 8345                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8346                    }
 8347
 8348                    if let Some(next_selection) = selections_iter.peek() {
 8349                        if next_selection.range().len() == selection.range().len() {
 8350                            let next_selected_text = buffer
 8351                                .text_for_range(next_selection.range())
 8352                                .collect::<String>();
 8353                            if Some(next_selected_text) != selected_text {
 8354                                same_text_selected = false;
 8355                                selected_text = None;
 8356                            }
 8357                        } else {
 8358                            same_text_selected = false;
 8359                            selected_text = None;
 8360                        }
 8361                    }
 8362                }
 8363            }
 8364
 8365            if only_carets {
 8366                for selection in &mut selections {
 8367                    let word_range = movement::surrounding_word(
 8368                        display_map,
 8369                        selection.start.to_display_point(display_map),
 8370                    );
 8371                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8372                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8373                    selection.goal = SelectionGoal::None;
 8374                    selection.reversed = false;
 8375                    select_next_match_ranges(
 8376                        self,
 8377                        selection.start..selection.end,
 8378                        replace_newest,
 8379                        autoscroll,
 8380                        cx,
 8381                    );
 8382                }
 8383
 8384                if selections.len() == 1 {
 8385                    let selection = selections
 8386                        .last()
 8387                        .expect("ensured that there's only one selection");
 8388                    let query = buffer
 8389                        .text_for_range(selection.start..selection.end)
 8390                        .collect::<String>();
 8391                    let is_empty = query.is_empty();
 8392                    let select_state = SelectNextState {
 8393                        query: AhoCorasick::new(&[query])?,
 8394                        wordwise: true,
 8395                        done: is_empty,
 8396                    };
 8397                    self.select_next_state = Some(select_state);
 8398                } else {
 8399                    self.select_next_state = None;
 8400                }
 8401            } else if let Some(selected_text) = selected_text {
 8402                self.select_next_state = Some(SelectNextState {
 8403                    query: AhoCorasick::new(&[selected_text])?,
 8404                    wordwise: false,
 8405                    done: false,
 8406                });
 8407                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8408            }
 8409        }
 8410        Ok(())
 8411    }
 8412
 8413    pub fn select_all_matches(
 8414        &mut self,
 8415        _action: &SelectAllMatches,
 8416        cx: &mut ViewContext<Self>,
 8417    ) -> Result<()> {
 8418        self.push_to_selection_history();
 8419        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8420
 8421        self.select_next_match_internal(&display_map, false, None, cx)?;
 8422        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8423            return Ok(());
 8424        };
 8425        if select_next_state.done {
 8426            return Ok(());
 8427        }
 8428
 8429        let mut new_selections = self.selections.all::<usize>(cx);
 8430
 8431        let buffer = &display_map.buffer_snapshot;
 8432        let query_matches = select_next_state
 8433            .query
 8434            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8435
 8436        for query_match in query_matches {
 8437            let query_match = query_match.unwrap(); // can only fail due to I/O
 8438            let offset_range = query_match.start()..query_match.end();
 8439            let display_range = offset_range.start.to_display_point(&display_map)
 8440                ..offset_range.end.to_display_point(&display_map);
 8441
 8442            if !select_next_state.wordwise
 8443                || (!movement::is_inside_word(&display_map, display_range.start)
 8444                    && !movement::is_inside_word(&display_map, display_range.end))
 8445            {
 8446                self.selections.change_with(cx, |selections| {
 8447                    new_selections.push(Selection {
 8448                        id: selections.new_selection_id(),
 8449                        start: offset_range.start,
 8450                        end: offset_range.end,
 8451                        reversed: false,
 8452                        goal: SelectionGoal::None,
 8453                    });
 8454                });
 8455            }
 8456        }
 8457
 8458        new_selections.sort_by_key(|selection| selection.start);
 8459        let mut ix = 0;
 8460        while ix + 1 < new_selections.len() {
 8461            let current_selection = &new_selections[ix];
 8462            let next_selection = &new_selections[ix + 1];
 8463            if current_selection.range().overlaps(&next_selection.range()) {
 8464                if current_selection.id < next_selection.id {
 8465                    new_selections.remove(ix + 1);
 8466                } else {
 8467                    new_selections.remove(ix);
 8468                }
 8469            } else {
 8470                ix += 1;
 8471            }
 8472        }
 8473
 8474        select_next_state.done = true;
 8475        self.unfold_ranges(
 8476            new_selections.iter().map(|selection| selection.range()),
 8477            false,
 8478            false,
 8479            cx,
 8480        );
 8481        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8482            selections.select(new_selections)
 8483        });
 8484
 8485        Ok(())
 8486    }
 8487
 8488    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8489        self.push_to_selection_history();
 8490        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8491        self.select_next_match_internal(
 8492            &display_map,
 8493            action.replace_newest,
 8494            Some(Autoscroll::newest()),
 8495            cx,
 8496        )?;
 8497        Ok(())
 8498    }
 8499
 8500    pub fn select_previous(
 8501        &mut self,
 8502        action: &SelectPrevious,
 8503        cx: &mut ViewContext<Self>,
 8504    ) -> Result<()> {
 8505        self.push_to_selection_history();
 8506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8507        let buffer = &display_map.buffer_snapshot;
 8508        let mut selections = self.selections.all::<usize>(cx);
 8509        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8510            let query = &select_prev_state.query;
 8511            if !select_prev_state.done {
 8512                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8513                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8514                let mut next_selected_range = None;
 8515                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8516                let bytes_before_last_selection =
 8517                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8518                let bytes_after_first_selection =
 8519                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8520                let query_matches = query
 8521                    .stream_find_iter(bytes_before_last_selection)
 8522                    .map(|result| (last_selection.start, result))
 8523                    .chain(
 8524                        query
 8525                            .stream_find_iter(bytes_after_first_selection)
 8526                            .map(|result| (buffer.len(), result)),
 8527                    );
 8528                for (end_offset, query_match) in query_matches {
 8529                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8530                    let offset_range =
 8531                        end_offset - query_match.end()..end_offset - query_match.start();
 8532                    let display_range = offset_range.start.to_display_point(&display_map)
 8533                        ..offset_range.end.to_display_point(&display_map);
 8534
 8535                    if !select_prev_state.wordwise
 8536                        || (!movement::is_inside_word(&display_map, display_range.start)
 8537                            && !movement::is_inside_word(&display_map, display_range.end))
 8538                    {
 8539                        next_selected_range = Some(offset_range);
 8540                        break;
 8541                    }
 8542                }
 8543
 8544                if let Some(next_selected_range) = next_selected_range {
 8545                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8546                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8547                        if action.replace_newest {
 8548                            s.delete(s.newest_anchor().id);
 8549                        }
 8550                        s.insert_range(next_selected_range);
 8551                    });
 8552                } else {
 8553                    select_prev_state.done = true;
 8554                }
 8555            }
 8556
 8557            self.select_prev_state = Some(select_prev_state);
 8558        } else {
 8559            let mut only_carets = true;
 8560            let mut same_text_selected = true;
 8561            let mut selected_text = None;
 8562
 8563            let mut selections_iter = selections.iter().peekable();
 8564            while let Some(selection) = selections_iter.next() {
 8565                if selection.start != selection.end {
 8566                    only_carets = false;
 8567                }
 8568
 8569                if same_text_selected {
 8570                    if selected_text.is_none() {
 8571                        selected_text =
 8572                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8573                    }
 8574
 8575                    if let Some(next_selection) = selections_iter.peek() {
 8576                        if next_selection.range().len() == selection.range().len() {
 8577                            let next_selected_text = buffer
 8578                                .text_for_range(next_selection.range())
 8579                                .collect::<String>();
 8580                            if Some(next_selected_text) != selected_text {
 8581                                same_text_selected = false;
 8582                                selected_text = None;
 8583                            }
 8584                        } else {
 8585                            same_text_selected = false;
 8586                            selected_text = None;
 8587                        }
 8588                    }
 8589                }
 8590            }
 8591
 8592            if only_carets {
 8593                for selection in &mut selections {
 8594                    let word_range = movement::surrounding_word(
 8595                        &display_map,
 8596                        selection.start.to_display_point(&display_map),
 8597                    );
 8598                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8599                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8600                    selection.goal = SelectionGoal::None;
 8601                    selection.reversed = false;
 8602                }
 8603                if selections.len() == 1 {
 8604                    let selection = selections
 8605                        .last()
 8606                        .expect("ensured that there's only one selection");
 8607                    let query = buffer
 8608                        .text_for_range(selection.start..selection.end)
 8609                        .collect::<String>();
 8610                    let is_empty = query.is_empty();
 8611                    let select_state = SelectNextState {
 8612                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8613                        wordwise: true,
 8614                        done: is_empty,
 8615                    };
 8616                    self.select_prev_state = Some(select_state);
 8617                } else {
 8618                    self.select_prev_state = None;
 8619                }
 8620
 8621                self.unfold_ranges(
 8622                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8623                    false,
 8624                    true,
 8625                    cx,
 8626                );
 8627                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8628                    s.select(selections);
 8629                });
 8630            } else if let Some(selected_text) = selected_text {
 8631                self.select_prev_state = Some(SelectNextState {
 8632                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8633                    wordwise: false,
 8634                    done: false,
 8635                });
 8636                self.select_previous(action, cx)?;
 8637            }
 8638        }
 8639        Ok(())
 8640    }
 8641
 8642    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8643        let text_layout_details = &self.text_layout_details(cx);
 8644        self.transact(cx, |this, cx| {
 8645            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8646            let mut edits = Vec::new();
 8647            let mut selection_edit_ranges = Vec::new();
 8648            let mut last_toggled_row = None;
 8649            let snapshot = this.buffer.read(cx).read(cx);
 8650            let empty_str: Arc<str> = Arc::default();
 8651            let mut suffixes_inserted = Vec::new();
 8652
 8653            fn comment_prefix_range(
 8654                snapshot: &MultiBufferSnapshot,
 8655                row: MultiBufferRow,
 8656                comment_prefix: &str,
 8657                comment_prefix_whitespace: &str,
 8658            ) -> Range<Point> {
 8659                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8660
 8661                let mut line_bytes = snapshot
 8662                    .bytes_in_range(start..snapshot.max_point())
 8663                    .flatten()
 8664                    .copied();
 8665
 8666                // If this line currently begins with the line comment prefix, then record
 8667                // the range containing the prefix.
 8668                if line_bytes
 8669                    .by_ref()
 8670                    .take(comment_prefix.len())
 8671                    .eq(comment_prefix.bytes())
 8672                {
 8673                    // Include any whitespace that matches the comment prefix.
 8674                    let matching_whitespace_len = line_bytes
 8675                        .zip(comment_prefix_whitespace.bytes())
 8676                        .take_while(|(a, b)| a == b)
 8677                        .count() as u32;
 8678                    let end = Point::new(
 8679                        start.row,
 8680                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8681                    );
 8682                    start..end
 8683                } else {
 8684                    start..start
 8685                }
 8686            }
 8687
 8688            fn comment_suffix_range(
 8689                snapshot: &MultiBufferSnapshot,
 8690                row: MultiBufferRow,
 8691                comment_suffix: &str,
 8692                comment_suffix_has_leading_space: bool,
 8693            ) -> Range<Point> {
 8694                let end = Point::new(row.0, snapshot.line_len(row));
 8695                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8696
 8697                let mut line_end_bytes = snapshot
 8698                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8699                    .flatten()
 8700                    .copied();
 8701
 8702                let leading_space_len = if suffix_start_column > 0
 8703                    && line_end_bytes.next() == Some(b' ')
 8704                    && comment_suffix_has_leading_space
 8705                {
 8706                    1
 8707                } else {
 8708                    0
 8709                };
 8710
 8711                // If this line currently begins with the line comment prefix, then record
 8712                // the range containing the prefix.
 8713                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8714                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8715                    start..end
 8716                } else {
 8717                    end..end
 8718                }
 8719            }
 8720
 8721            // TODO: Handle selections that cross excerpts
 8722            for selection in &mut selections {
 8723                let start_column = snapshot
 8724                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8725                    .len;
 8726                let language = if let Some(language) =
 8727                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8728                {
 8729                    language
 8730                } else {
 8731                    continue;
 8732                };
 8733
 8734                selection_edit_ranges.clear();
 8735
 8736                // If multiple selections contain a given row, avoid processing that
 8737                // row more than once.
 8738                let mut start_row = MultiBufferRow(selection.start.row);
 8739                if last_toggled_row == Some(start_row) {
 8740                    start_row = start_row.next_row();
 8741                }
 8742                let end_row =
 8743                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8744                        MultiBufferRow(selection.end.row - 1)
 8745                    } else {
 8746                        MultiBufferRow(selection.end.row)
 8747                    };
 8748                last_toggled_row = Some(end_row);
 8749
 8750                if start_row > end_row {
 8751                    continue;
 8752                }
 8753
 8754                // If the language has line comments, toggle those.
 8755                let full_comment_prefixes = language.line_comment_prefixes();
 8756                if !full_comment_prefixes.is_empty() {
 8757                    let first_prefix = full_comment_prefixes
 8758                        .first()
 8759                        .expect("prefixes is non-empty");
 8760                    let prefix_trimmed_lengths = full_comment_prefixes
 8761                        .iter()
 8762                        .map(|p| p.trim_end_matches(' ').len())
 8763                        .collect::<SmallVec<[usize; 4]>>();
 8764
 8765                    let mut all_selection_lines_are_comments = true;
 8766
 8767                    for row in start_row.0..=end_row.0 {
 8768                        let row = MultiBufferRow(row);
 8769                        if start_row < end_row && snapshot.is_line_blank(row) {
 8770                            continue;
 8771                        }
 8772
 8773                        let prefix_range = full_comment_prefixes
 8774                            .iter()
 8775                            .zip(prefix_trimmed_lengths.iter().copied())
 8776                            .map(|(prefix, trimmed_prefix_len)| {
 8777                                comment_prefix_range(
 8778                                    snapshot.deref(),
 8779                                    row,
 8780                                    &prefix[..trimmed_prefix_len],
 8781                                    &prefix[trimmed_prefix_len..],
 8782                                )
 8783                            })
 8784                            .max_by_key(|range| range.end.column - range.start.column)
 8785                            .expect("prefixes is non-empty");
 8786
 8787                        if prefix_range.is_empty() {
 8788                            all_selection_lines_are_comments = false;
 8789                        }
 8790
 8791                        selection_edit_ranges.push(prefix_range);
 8792                    }
 8793
 8794                    if all_selection_lines_are_comments {
 8795                        edits.extend(
 8796                            selection_edit_ranges
 8797                                .iter()
 8798                                .cloned()
 8799                                .map(|range| (range, empty_str.clone())),
 8800                        );
 8801                    } else {
 8802                        let min_column = selection_edit_ranges
 8803                            .iter()
 8804                            .map(|range| range.start.column)
 8805                            .min()
 8806                            .unwrap_or(0);
 8807                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8808                            let position = Point::new(range.start.row, min_column);
 8809                            (position..position, first_prefix.clone())
 8810                        }));
 8811                    }
 8812                } else if let Some((full_comment_prefix, comment_suffix)) =
 8813                    language.block_comment_delimiters()
 8814                {
 8815                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8816                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8817                    let prefix_range = comment_prefix_range(
 8818                        snapshot.deref(),
 8819                        start_row,
 8820                        comment_prefix,
 8821                        comment_prefix_whitespace,
 8822                    );
 8823                    let suffix_range = comment_suffix_range(
 8824                        snapshot.deref(),
 8825                        end_row,
 8826                        comment_suffix.trim_start_matches(' '),
 8827                        comment_suffix.starts_with(' '),
 8828                    );
 8829
 8830                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8831                        edits.push((
 8832                            prefix_range.start..prefix_range.start,
 8833                            full_comment_prefix.clone(),
 8834                        ));
 8835                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8836                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8837                    } else {
 8838                        edits.push((prefix_range, empty_str.clone()));
 8839                        edits.push((suffix_range, empty_str.clone()));
 8840                    }
 8841                } else {
 8842                    continue;
 8843                }
 8844            }
 8845
 8846            drop(snapshot);
 8847            this.buffer.update(cx, |buffer, cx| {
 8848                buffer.edit(edits, None, cx);
 8849            });
 8850
 8851            // Adjust selections so that they end before any comment suffixes that
 8852            // were inserted.
 8853            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8854            let mut selections = this.selections.all::<Point>(cx);
 8855            let snapshot = this.buffer.read(cx).read(cx);
 8856            for selection in &mut selections {
 8857                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8858                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8859                        Ordering::Less => {
 8860                            suffixes_inserted.next();
 8861                            continue;
 8862                        }
 8863                        Ordering::Greater => break,
 8864                        Ordering::Equal => {
 8865                            if selection.end.column == snapshot.line_len(row) {
 8866                                if selection.is_empty() {
 8867                                    selection.start.column -= suffix_len as u32;
 8868                                }
 8869                                selection.end.column -= suffix_len as u32;
 8870                            }
 8871                            break;
 8872                        }
 8873                    }
 8874                }
 8875            }
 8876
 8877            drop(snapshot);
 8878            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8879
 8880            let selections = this.selections.all::<Point>(cx);
 8881            let selections_on_single_row = selections.windows(2).all(|selections| {
 8882                selections[0].start.row == selections[1].start.row
 8883                    && selections[0].end.row == selections[1].end.row
 8884                    && selections[0].start.row == selections[0].end.row
 8885            });
 8886            let selections_selecting = selections
 8887                .iter()
 8888                .any(|selection| selection.start != selection.end);
 8889            let advance_downwards = action.advance_downwards
 8890                && selections_on_single_row
 8891                && !selections_selecting
 8892                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8893
 8894            if advance_downwards {
 8895                let snapshot = this.buffer.read(cx).snapshot(cx);
 8896
 8897                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8898                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8899                        let mut point = display_point.to_point(display_snapshot);
 8900                        point.row += 1;
 8901                        point = snapshot.clip_point(point, Bias::Left);
 8902                        let display_point = point.to_display_point(display_snapshot);
 8903                        let goal = SelectionGoal::HorizontalPosition(
 8904                            display_snapshot
 8905                                .x_for_display_point(display_point, text_layout_details)
 8906                                .into(),
 8907                        );
 8908                        (display_point, goal)
 8909                    })
 8910                });
 8911            }
 8912        });
 8913    }
 8914
 8915    pub fn select_enclosing_symbol(
 8916        &mut self,
 8917        _: &SelectEnclosingSymbol,
 8918        cx: &mut ViewContext<Self>,
 8919    ) {
 8920        let buffer = self.buffer.read(cx).snapshot(cx);
 8921        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8922
 8923        fn update_selection(
 8924            selection: &Selection<usize>,
 8925            buffer_snap: &MultiBufferSnapshot,
 8926        ) -> Option<Selection<usize>> {
 8927            let cursor = selection.head();
 8928            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8929            for symbol in symbols.iter().rev() {
 8930                let start = symbol.range.start.to_offset(buffer_snap);
 8931                let end = symbol.range.end.to_offset(buffer_snap);
 8932                let new_range = start..end;
 8933                if start < selection.start || end > selection.end {
 8934                    return Some(Selection {
 8935                        id: selection.id,
 8936                        start: new_range.start,
 8937                        end: new_range.end,
 8938                        goal: SelectionGoal::None,
 8939                        reversed: selection.reversed,
 8940                    });
 8941                }
 8942            }
 8943            None
 8944        }
 8945
 8946        let mut selected_larger_symbol = false;
 8947        let new_selections = old_selections
 8948            .iter()
 8949            .map(|selection| match update_selection(selection, &buffer) {
 8950                Some(new_selection) => {
 8951                    if new_selection.range() != selection.range() {
 8952                        selected_larger_symbol = true;
 8953                    }
 8954                    new_selection
 8955                }
 8956                None => selection.clone(),
 8957            })
 8958            .collect::<Vec<_>>();
 8959
 8960        if selected_larger_symbol {
 8961            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8962                s.select(new_selections);
 8963            });
 8964        }
 8965    }
 8966
 8967    pub fn select_larger_syntax_node(
 8968        &mut self,
 8969        _: &SelectLargerSyntaxNode,
 8970        cx: &mut ViewContext<Self>,
 8971    ) {
 8972        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8973        let buffer = self.buffer.read(cx).snapshot(cx);
 8974        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8975
 8976        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8977        let mut selected_larger_node = false;
 8978        let new_selections = old_selections
 8979            .iter()
 8980            .map(|selection| {
 8981                let old_range = selection.start..selection.end;
 8982                let mut new_range = old_range.clone();
 8983                while let Some(containing_range) =
 8984                    buffer.range_for_syntax_ancestor(new_range.clone())
 8985                {
 8986                    new_range = containing_range;
 8987                    if !display_map.intersects_fold(new_range.start)
 8988                        && !display_map.intersects_fold(new_range.end)
 8989                    {
 8990                        break;
 8991                    }
 8992                }
 8993
 8994                selected_larger_node |= new_range != old_range;
 8995                Selection {
 8996                    id: selection.id,
 8997                    start: new_range.start,
 8998                    end: new_range.end,
 8999                    goal: SelectionGoal::None,
 9000                    reversed: selection.reversed,
 9001                }
 9002            })
 9003            .collect::<Vec<_>>();
 9004
 9005        if selected_larger_node {
 9006            stack.push(old_selections);
 9007            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9008                s.select(new_selections);
 9009            });
 9010        }
 9011        self.select_larger_syntax_node_stack = stack;
 9012    }
 9013
 9014    pub fn select_smaller_syntax_node(
 9015        &mut self,
 9016        _: &SelectSmallerSyntaxNode,
 9017        cx: &mut ViewContext<Self>,
 9018    ) {
 9019        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9020        if let Some(selections) = stack.pop() {
 9021            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9022                s.select(selections.to_vec());
 9023            });
 9024        }
 9025        self.select_larger_syntax_node_stack = stack;
 9026    }
 9027
 9028    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9029        if !EditorSettings::get_global(cx).gutter.runnables {
 9030            self.clear_tasks();
 9031            return Task::ready(());
 9032        }
 9033        let project = self.project.clone();
 9034        cx.spawn(|this, mut cx| async move {
 9035            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9036                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9037            }) else {
 9038                return;
 9039            };
 9040
 9041            let Some(project) = project else {
 9042                return;
 9043            };
 9044
 9045            let hide_runnables = project
 9046                .update(&mut cx, |project, cx| {
 9047                    // Do not display any test indicators in non-dev server remote projects.
 9048                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9049                })
 9050                .unwrap_or(true);
 9051            if hide_runnables {
 9052                return;
 9053            }
 9054            let new_rows =
 9055                cx.background_executor()
 9056                    .spawn({
 9057                        let snapshot = display_snapshot.clone();
 9058                        async move {
 9059                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9060                        }
 9061                    })
 9062                    .await;
 9063            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9064
 9065            this.update(&mut cx, |this, _| {
 9066                this.clear_tasks();
 9067                for (key, value) in rows {
 9068                    this.insert_tasks(key, value);
 9069                }
 9070            })
 9071            .ok();
 9072        })
 9073    }
 9074    fn fetch_runnable_ranges(
 9075        snapshot: &DisplaySnapshot,
 9076        range: Range<Anchor>,
 9077    ) -> Vec<language::RunnableRange> {
 9078        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9079    }
 9080
 9081    fn runnable_rows(
 9082        project: Model<Project>,
 9083        snapshot: DisplaySnapshot,
 9084        runnable_ranges: Vec<RunnableRange>,
 9085        mut cx: AsyncWindowContext,
 9086    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9087        runnable_ranges
 9088            .into_iter()
 9089            .filter_map(|mut runnable| {
 9090                let tasks = cx
 9091                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9092                    .ok()?;
 9093                if tasks.is_empty() {
 9094                    return None;
 9095                }
 9096
 9097                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9098
 9099                let row = snapshot
 9100                    .buffer_snapshot
 9101                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9102                    .1
 9103                    .start
 9104                    .row;
 9105
 9106                let context_range =
 9107                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9108                Some((
 9109                    (runnable.buffer_id, row),
 9110                    RunnableTasks {
 9111                        templates: tasks,
 9112                        offset: MultiBufferOffset(runnable.run_range.start),
 9113                        context_range,
 9114                        column: point.column,
 9115                        extra_variables: runnable.extra_captures,
 9116                    },
 9117                ))
 9118            })
 9119            .collect()
 9120    }
 9121
 9122    fn templates_with_tags(
 9123        project: &Model<Project>,
 9124        runnable: &mut Runnable,
 9125        cx: &WindowContext<'_>,
 9126    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9127        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9128            let (worktree_id, file) = project
 9129                .buffer_for_id(runnable.buffer, cx)
 9130                .and_then(|buffer| buffer.read(cx).file())
 9131                .map(|file| (file.worktree_id(cx), file.clone()))
 9132                .unzip();
 9133
 9134            (
 9135                project.task_store().read(cx).task_inventory().cloned(),
 9136                worktree_id,
 9137                file,
 9138            )
 9139        });
 9140
 9141        let tags = mem::take(&mut runnable.tags);
 9142        let mut tags: Vec<_> = tags
 9143            .into_iter()
 9144            .flat_map(|tag| {
 9145                let tag = tag.0.clone();
 9146                inventory
 9147                    .as_ref()
 9148                    .into_iter()
 9149                    .flat_map(|inventory| {
 9150                        inventory.read(cx).list_tasks(
 9151                            file.clone(),
 9152                            Some(runnable.language.clone()),
 9153                            worktree_id,
 9154                            cx,
 9155                        )
 9156                    })
 9157                    .filter(move |(_, template)| {
 9158                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9159                    })
 9160            })
 9161            .sorted_by_key(|(kind, _)| kind.to_owned())
 9162            .collect();
 9163        if let Some((leading_tag_source, _)) = tags.first() {
 9164            // Strongest source wins; if we have worktree tag binding, prefer that to
 9165            // global and language bindings;
 9166            // if we have a global binding, prefer that to language binding.
 9167            let first_mismatch = tags
 9168                .iter()
 9169                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9170            if let Some(index) = first_mismatch {
 9171                tags.truncate(index);
 9172            }
 9173        }
 9174
 9175        tags
 9176    }
 9177
 9178    pub fn move_to_enclosing_bracket(
 9179        &mut self,
 9180        _: &MoveToEnclosingBracket,
 9181        cx: &mut ViewContext<Self>,
 9182    ) {
 9183        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9184            s.move_offsets_with(|snapshot, selection| {
 9185                let Some(enclosing_bracket_ranges) =
 9186                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9187                else {
 9188                    return;
 9189                };
 9190
 9191                let mut best_length = usize::MAX;
 9192                let mut best_inside = false;
 9193                let mut best_in_bracket_range = false;
 9194                let mut best_destination = None;
 9195                for (open, close) in enclosing_bracket_ranges {
 9196                    let close = close.to_inclusive();
 9197                    let length = close.end() - open.start;
 9198                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9199                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9200                        || close.contains(&selection.head());
 9201
 9202                    // If best is next to a bracket and current isn't, skip
 9203                    if !in_bracket_range && best_in_bracket_range {
 9204                        continue;
 9205                    }
 9206
 9207                    // Prefer smaller lengths unless best is inside and current isn't
 9208                    if length > best_length && (best_inside || !inside) {
 9209                        continue;
 9210                    }
 9211
 9212                    best_length = length;
 9213                    best_inside = inside;
 9214                    best_in_bracket_range = in_bracket_range;
 9215                    best_destination = Some(
 9216                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9217                            if inside {
 9218                                open.end
 9219                            } else {
 9220                                open.start
 9221                            }
 9222                        } else if inside {
 9223                            *close.start()
 9224                        } else {
 9225                            *close.end()
 9226                        },
 9227                    );
 9228                }
 9229
 9230                if let Some(destination) = best_destination {
 9231                    selection.collapse_to(destination, SelectionGoal::None);
 9232                }
 9233            })
 9234        });
 9235    }
 9236
 9237    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9238        self.end_selection(cx);
 9239        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9240        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9241            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9242            self.select_next_state = entry.select_next_state;
 9243            self.select_prev_state = entry.select_prev_state;
 9244            self.add_selections_state = entry.add_selections_state;
 9245            self.request_autoscroll(Autoscroll::newest(), cx);
 9246        }
 9247        self.selection_history.mode = SelectionHistoryMode::Normal;
 9248    }
 9249
 9250    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9251        self.end_selection(cx);
 9252        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9253        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9254            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9255            self.select_next_state = entry.select_next_state;
 9256            self.select_prev_state = entry.select_prev_state;
 9257            self.add_selections_state = entry.add_selections_state;
 9258            self.request_autoscroll(Autoscroll::newest(), cx);
 9259        }
 9260        self.selection_history.mode = SelectionHistoryMode::Normal;
 9261    }
 9262
 9263    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9264        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9265    }
 9266
 9267    pub fn expand_excerpts_down(
 9268        &mut self,
 9269        action: &ExpandExcerptsDown,
 9270        cx: &mut ViewContext<Self>,
 9271    ) {
 9272        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9273    }
 9274
 9275    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9276        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9277    }
 9278
 9279    pub fn expand_excerpts_for_direction(
 9280        &mut self,
 9281        lines: u32,
 9282        direction: ExpandExcerptDirection,
 9283        cx: &mut ViewContext<Self>,
 9284    ) {
 9285        let selections = self.selections.disjoint_anchors();
 9286
 9287        let lines = if lines == 0 {
 9288            EditorSettings::get_global(cx).expand_excerpt_lines
 9289        } else {
 9290            lines
 9291        };
 9292
 9293        self.buffer.update(cx, |buffer, cx| {
 9294            buffer.expand_excerpts(
 9295                selections
 9296                    .iter()
 9297                    .map(|selection| selection.head().excerpt_id)
 9298                    .dedup(),
 9299                lines,
 9300                direction,
 9301                cx,
 9302            )
 9303        })
 9304    }
 9305
 9306    pub fn expand_excerpt(
 9307        &mut self,
 9308        excerpt: ExcerptId,
 9309        direction: ExpandExcerptDirection,
 9310        cx: &mut ViewContext<Self>,
 9311    ) {
 9312        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9313        self.buffer.update(cx, |buffer, cx| {
 9314            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9315        })
 9316    }
 9317
 9318    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9319        self.go_to_diagnostic_impl(Direction::Next, cx)
 9320    }
 9321
 9322    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9323        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9324    }
 9325
 9326    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9327        let buffer = self.buffer.read(cx).snapshot(cx);
 9328        let selection = self.selections.newest::<usize>(cx);
 9329
 9330        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9331        if direction == Direction::Next {
 9332            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9333                let (group_id, jump_to) = popover.activation_info();
 9334                if self.activate_diagnostics(group_id, cx) {
 9335                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9336                        let mut new_selection = s.newest_anchor().clone();
 9337                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9338                        s.select_anchors(vec![new_selection.clone()]);
 9339                    });
 9340                }
 9341                return;
 9342            }
 9343        }
 9344
 9345        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9346            active_diagnostics
 9347                .primary_range
 9348                .to_offset(&buffer)
 9349                .to_inclusive()
 9350        });
 9351        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9352            if active_primary_range.contains(&selection.head()) {
 9353                *active_primary_range.start()
 9354            } else {
 9355                selection.head()
 9356            }
 9357        } else {
 9358            selection.head()
 9359        };
 9360        let snapshot = self.snapshot(cx);
 9361        loop {
 9362            let diagnostics = if direction == Direction::Prev {
 9363                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9364            } else {
 9365                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9366            }
 9367            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9368            let group = diagnostics
 9369                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9370                // be sorted in a stable way
 9371                // skip until we are at current active diagnostic, if it exists
 9372                .skip_while(|entry| {
 9373                    (match direction {
 9374                        Direction::Prev => entry.range.start >= search_start,
 9375                        Direction::Next => entry.range.start <= search_start,
 9376                    }) && self
 9377                        .active_diagnostics
 9378                        .as_ref()
 9379                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9380                })
 9381                .find_map(|entry| {
 9382                    if entry.diagnostic.is_primary
 9383                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9384                        && !entry.range.is_empty()
 9385                        // if we match with the active diagnostic, skip it
 9386                        && Some(entry.diagnostic.group_id)
 9387                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9388                    {
 9389                        Some((entry.range, entry.diagnostic.group_id))
 9390                    } else {
 9391                        None
 9392                    }
 9393                });
 9394
 9395            if let Some((primary_range, group_id)) = group {
 9396                if self.activate_diagnostics(group_id, cx) {
 9397                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9398                        s.select(vec![Selection {
 9399                            id: selection.id,
 9400                            start: primary_range.start,
 9401                            end: primary_range.start,
 9402                            reversed: false,
 9403                            goal: SelectionGoal::None,
 9404                        }]);
 9405                    });
 9406                }
 9407                break;
 9408            } else {
 9409                // Cycle around to the start of the buffer, potentially moving back to the start of
 9410                // the currently active diagnostic.
 9411                active_primary_range.take();
 9412                if direction == Direction::Prev {
 9413                    if search_start == buffer.len() {
 9414                        break;
 9415                    } else {
 9416                        search_start = buffer.len();
 9417                    }
 9418                } else if search_start == 0 {
 9419                    break;
 9420                } else {
 9421                    search_start = 0;
 9422                }
 9423            }
 9424        }
 9425    }
 9426
 9427    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9428        let snapshot = self
 9429            .display_map
 9430            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9431        let selection = self.selections.newest::<Point>(cx);
 9432        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9433    }
 9434
 9435    fn go_to_hunk_after_position(
 9436        &mut self,
 9437        snapshot: &DisplaySnapshot,
 9438        position: Point,
 9439        cx: &mut ViewContext<'_, Editor>,
 9440    ) -> Option<MultiBufferDiffHunk> {
 9441        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9442            snapshot,
 9443            position,
 9444            false,
 9445            snapshot
 9446                .buffer_snapshot
 9447                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9448            cx,
 9449        ) {
 9450            return Some(hunk);
 9451        }
 9452
 9453        let wrapped_point = Point::zero();
 9454        self.go_to_next_hunk_in_direction(
 9455            snapshot,
 9456            wrapped_point,
 9457            true,
 9458            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9459                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9460            ),
 9461            cx,
 9462        )
 9463    }
 9464
 9465    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9466        let snapshot = self
 9467            .display_map
 9468            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9469        let selection = self.selections.newest::<Point>(cx);
 9470
 9471        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9472    }
 9473
 9474    fn go_to_hunk_before_position(
 9475        &mut self,
 9476        snapshot: &DisplaySnapshot,
 9477        position: Point,
 9478        cx: &mut ViewContext<'_, Editor>,
 9479    ) -> Option<MultiBufferDiffHunk> {
 9480        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9481            snapshot,
 9482            position,
 9483            false,
 9484            snapshot
 9485                .buffer_snapshot
 9486                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9487            cx,
 9488        ) {
 9489            return Some(hunk);
 9490        }
 9491
 9492        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9493        self.go_to_next_hunk_in_direction(
 9494            snapshot,
 9495            wrapped_point,
 9496            true,
 9497            snapshot
 9498                .buffer_snapshot
 9499                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9500            cx,
 9501        )
 9502    }
 9503
 9504    fn go_to_next_hunk_in_direction(
 9505        &mut self,
 9506        snapshot: &DisplaySnapshot,
 9507        initial_point: Point,
 9508        is_wrapped: bool,
 9509        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9510        cx: &mut ViewContext<Editor>,
 9511    ) -> Option<MultiBufferDiffHunk> {
 9512        let display_point = initial_point.to_display_point(snapshot);
 9513        let mut hunks = hunks
 9514            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9515            .filter(|(display_hunk, _)| {
 9516                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9517            })
 9518            .dedup();
 9519
 9520        if let Some((display_hunk, hunk)) = hunks.next() {
 9521            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9522                let row = display_hunk.start_display_row();
 9523                let point = DisplayPoint::new(row, 0);
 9524                s.select_display_ranges([point..point]);
 9525            });
 9526
 9527            Some(hunk)
 9528        } else {
 9529            None
 9530        }
 9531    }
 9532
 9533    pub fn go_to_definition(
 9534        &mut self,
 9535        _: &GoToDefinition,
 9536        cx: &mut ViewContext<Self>,
 9537    ) -> Task<Result<Navigated>> {
 9538        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9539        cx.spawn(|editor, mut cx| async move {
 9540            if definition.await? == Navigated::Yes {
 9541                return Ok(Navigated::Yes);
 9542            }
 9543            match editor.update(&mut cx, |editor, cx| {
 9544                editor.find_all_references(&FindAllReferences, cx)
 9545            })? {
 9546                Some(references) => references.await,
 9547                None => Ok(Navigated::No),
 9548            }
 9549        })
 9550    }
 9551
 9552    pub fn go_to_declaration(
 9553        &mut self,
 9554        _: &GoToDeclaration,
 9555        cx: &mut ViewContext<Self>,
 9556    ) -> Task<Result<Navigated>> {
 9557        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9558    }
 9559
 9560    pub fn go_to_declaration_split(
 9561        &mut self,
 9562        _: &GoToDeclaration,
 9563        cx: &mut ViewContext<Self>,
 9564    ) -> Task<Result<Navigated>> {
 9565        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9566    }
 9567
 9568    pub fn go_to_implementation(
 9569        &mut self,
 9570        _: &GoToImplementation,
 9571        cx: &mut ViewContext<Self>,
 9572    ) -> Task<Result<Navigated>> {
 9573        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9574    }
 9575
 9576    pub fn go_to_implementation_split(
 9577        &mut self,
 9578        _: &GoToImplementationSplit,
 9579        cx: &mut ViewContext<Self>,
 9580    ) -> Task<Result<Navigated>> {
 9581        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9582    }
 9583
 9584    pub fn go_to_type_definition(
 9585        &mut self,
 9586        _: &GoToTypeDefinition,
 9587        cx: &mut ViewContext<Self>,
 9588    ) -> Task<Result<Navigated>> {
 9589        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9590    }
 9591
 9592    pub fn go_to_definition_split(
 9593        &mut self,
 9594        _: &GoToDefinitionSplit,
 9595        cx: &mut ViewContext<Self>,
 9596    ) -> Task<Result<Navigated>> {
 9597        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9598    }
 9599
 9600    pub fn go_to_type_definition_split(
 9601        &mut self,
 9602        _: &GoToTypeDefinitionSplit,
 9603        cx: &mut ViewContext<Self>,
 9604    ) -> Task<Result<Navigated>> {
 9605        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9606    }
 9607
 9608    fn go_to_definition_of_kind(
 9609        &mut self,
 9610        kind: GotoDefinitionKind,
 9611        split: bool,
 9612        cx: &mut ViewContext<Self>,
 9613    ) -> Task<Result<Navigated>> {
 9614        let Some(provider) = self.semantics_provider.clone() else {
 9615            return Task::ready(Ok(Navigated::No));
 9616        };
 9617        let buffer = self.buffer.read(cx);
 9618        let head = self.selections.newest::<usize>(cx).head();
 9619        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9620            text_anchor
 9621        } else {
 9622            return Task::ready(Ok(Navigated::No));
 9623        };
 9624
 9625        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9626            return Task::ready(Ok(Navigated::No));
 9627        };
 9628
 9629        cx.spawn(|editor, mut cx| async move {
 9630            let definitions = definitions.await?;
 9631            let navigated = editor
 9632                .update(&mut cx, |editor, cx| {
 9633                    editor.navigate_to_hover_links(
 9634                        Some(kind),
 9635                        definitions
 9636                            .into_iter()
 9637                            .filter(|location| {
 9638                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9639                            })
 9640                            .map(HoverLink::Text)
 9641                            .collect::<Vec<_>>(),
 9642                        split,
 9643                        cx,
 9644                    )
 9645                })?
 9646                .await?;
 9647            anyhow::Ok(navigated)
 9648        })
 9649    }
 9650
 9651    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9652        let position = self.selections.newest_anchor().head();
 9653        let Some((buffer, buffer_position)) =
 9654            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9655        else {
 9656            return;
 9657        };
 9658
 9659        cx.spawn(|editor, mut cx| async move {
 9660            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9661                editor.update(&mut cx, |_, cx| {
 9662                    cx.open_url(&url);
 9663                })
 9664            } else {
 9665                Ok(())
 9666            }
 9667        })
 9668        .detach();
 9669    }
 9670
 9671    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9672        let Some(workspace) = self.workspace() else {
 9673            return;
 9674        };
 9675
 9676        let position = self.selections.newest_anchor().head();
 9677
 9678        let Some((buffer, buffer_position)) =
 9679            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9680        else {
 9681            return;
 9682        };
 9683
 9684        let project = self.project.clone();
 9685
 9686        cx.spawn(|_, mut cx| async move {
 9687            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9688
 9689            if let Some((_, path)) = result {
 9690                workspace
 9691                    .update(&mut cx, |workspace, cx| {
 9692                        workspace.open_resolved_path(path, cx)
 9693                    })?
 9694                    .await?;
 9695            }
 9696            anyhow::Ok(())
 9697        })
 9698        .detach();
 9699    }
 9700
 9701    pub(crate) fn navigate_to_hover_links(
 9702        &mut self,
 9703        kind: Option<GotoDefinitionKind>,
 9704        mut definitions: Vec<HoverLink>,
 9705        split: bool,
 9706        cx: &mut ViewContext<Editor>,
 9707    ) -> Task<Result<Navigated>> {
 9708        // If there is one definition, just open it directly
 9709        if definitions.len() == 1 {
 9710            let definition = definitions.pop().unwrap();
 9711
 9712            enum TargetTaskResult {
 9713                Location(Option<Location>),
 9714                AlreadyNavigated,
 9715            }
 9716
 9717            let target_task = match definition {
 9718                HoverLink::Text(link) => {
 9719                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9720                }
 9721                HoverLink::InlayHint(lsp_location, server_id) => {
 9722                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9723                    cx.background_executor().spawn(async move {
 9724                        let location = computation.await?;
 9725                        Ok(TargetTaskResult::Location(location))
 9726                    })
 9727                }
 9728                HoverLink::Url(url) => {
 9729                    cx.open_url(&url);
 9730                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9731                }
 9732                HoverLink::File(path) => {
 9733                    if let Some(workspace) = self.workspace() {
 9734                        cx.spawn(|_, mut cx| async move {
 9735                            workspace
 9736                                .update(&mut cx, |workspace, cx| {
 9737                                    workspace.open_resolved_path(path, cx)
 9738                                })?
 9739                                .await
 9740                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9741                        })
 9742                    } else {
 9743                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9744                    }
 9745                }
 9746            };
 9747            cx.spawn(|editor, mut cx| async move {
 9748                let target = match target_task.await.context("target resolution task")? {
 9749                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9750                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9751                    TargetTaskResult::Location(Some(target)) => target,
 9752                };
 9753
 9754                editor.update(&mut cx, |editor, cx| {
 9755                    let Some(workspace) = editor.workspace() else {
 9756                        return Navigated::No;
 9757                    };
 9758                    let pane = workspace.read(cx).active_pane().clone();
 9759
 9760                    let range = target.range.to_offset(target.buffer.read(cx));
 9761                    let range = editor.range_for_match(&range);
 9762
 9763                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9764                        let buffer = target.buffer.read(cx);
 9765                        let range = check_multiline_range(buffer, range);
 9766                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9767                            s.select_ranges([range]);
 9768                        });
 9769                    } else {
 9770                        cx.window_context().defer(move |cx| {
 9771                            let target_editor: View<Self> =
 9772                                workspace.update(cx, |workspace, cx| {
 9773                                    let pane = if split {
 9774                                        workspace.adjacent_pane(cx)
 9775                                    } else {
 9776                                        workspace.active_pane().clone()
 9777                                    };
 9778
 9779                                    workspace.open_project_item(
 9780                                        pane,
 9781                                        target.buffer.clone(),
 9782                                        true,
 9783                                        true,
 9784                                        cx,
 9785                                    )
 9786                                });
 9787                            target_editor.update(cx, |target_editor, cx| {
 9788                                // When selecting a definition in a different buffer, disable the nav history
 9789                                // to avoid creating a history entry at the previous cursor location.
 9790                                pane.update(cx, |pane, _| pane.disable_history());
 9791                                let buffer = target.buffer.read(cx);
 9792                                let range = check_multiline_range(buffer, range);
 9793                                target_editor.change_selections(
 9794                                    Some(Autoscroll::focused()),
 9795                                    cx,
 9796                                    |s| {
 9797                                        s.select_ranges([range]);
 9798                                    },
 9799                                );
 9800                                pane.update(cx, |pane, _| pane.enable_history());
 9801                            });
 9802                        });
 9803                    }
 9804                    Navigated::Yes
 9805                })
 9806            })
 9807        } else if !definitions.is_empty() {
 9808            cx.spawn(|editor, mut cx| async move {
 9809                let (title, location_tasks, workspace) = editor
 9810                    .update(&mut cx, |editor, cx| {
 9811                        let tab_kind = match kind {
 9812                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9813                            _ => "Definitions",
 9814                        };
 9815                        let title = definitions
 9816                            .iter()
 9817                            .find_map(|definition| match definition {
 9818                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9819                                    let buffer = origin.buffer.read(cx);
 9820                                    format!(
 9821                                        "{} for {}",
 9822                                        tab_kind,
 9823                                        buffer
 9824                                            .text_for_range(origin.range.clone())
 9825                                            .collect::<String>()
 9826                                    )
 9827                                }),
 9828                                HoverLink::InlayHint(_, _) => None,
 9829                                HoverLink::Url(_) => None,
 9830                                HoverLink::File(_) => None,
 9831                            })
 9832                            .unwrap_or(tab_kind.to_string());
 9833                        let location_tasks = definitions
 9834                            .into_iter()
 9835                            .map(|definition| match definition {
 9836                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9837                                HoverLink::InlayHint(lsp_location, server_id) => {
 9838                                    editor.compute_target_location(lsp_location, server_id, cx)
 9839                                }
 9840                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9841                                HoverLink::File(_) => Task::ready(Ok(None)),
 9842                            })
 9843                            .collect::<Vec<_>>();
 9844                        (title, location_tasks, editor.workspace().clone())
 9845                    })
 9846                    .context("location tasks preparation")?;
 9847
 9848                let locations = future::join_all(location_tasks)
 9849                    .await
 9850                    .into_iter()
 9851                    .filter_map(|location| location.transpose())
 9852                    .collect::<Result<_>>()
 9853                    .context("location tasks")?;
 9854
 9855                let Some(workspace) = workspace else {
 9856                    return Ok(Navigated::No);
 9857                };
 9858                let opened = workspace
 9859                    .update(&mut cx, |workspace, cx| {
 9860                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9861                    })
 9862                    .ok();
 9863
 9864                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9865            })
 9866        } else {
 9867            Task::ready(Ok(Navigated::No))
 9868        }
 9869    }
 9870
 9871    fn compute_target_location(
 9872        &self,
 9873        lsp_location: lsp::Location,
 9874        server_id: LanguageServerId,
 9875        cx: &mut ViewContext<Self>,
 9876    ) -> Task<anyhow::Result<Option<Location>>> {
 9877        let Some(project) = self.project.clone() else {
 9878            return Task::Ready(Some(Ok(None)));
 9879        };
 9880
 9881        cx.spawn(move |editor, mut cx| async move {
 9882            let location_task = editor.update(&mut cx, |_, cx| {
 9883                project.update(cx, |project, cx| {
 9884                    let language_server_name = project
 9885                        .language_server_statuses(cx)
 9886                        .find(|(id, _)| server_id == *id)
 9887                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9888                    language_server_name.map(|language_server_name| {
 9889                        project.open_local_buffer_via_lsp(
 9890                            lsp_location.uri.clone(),
 9891                            server_id,
 9892                            language_server_name,
 9893                            cx,
 9894                        )
 9895                    })
 9896                })
 9897            })?;
 9898            let location = match location_task {
 9899                Some(task) => Some({
 9900                    let target_buffer_handle = task.await.context("open local buffer")?;
 9901                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9902                        let target_start = target_buffer
 9903                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9904                        let target_end = target_buffer
 9905                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9906                        target_buffer.anchor_after(target_start)
 9907                            ..target_buffer.anchor_before(target_end)
 9908                    })?;
 9909                    Location {
 9910                        buffer: target_buffer_handle,
 9911                        range,
 9912                    }
 9913                }),
 9914                None => None,
 9915            };
 9916            Ok(location)
 9917        })
 9918    }
 9919
 9920    pub fn find_all_references(
 9921        &mut self,
 9922        _: &FindAllReferences,
 9923        cx: &mut ViewContext<Self>,
 9924    ) -> Option<Task<Result<Navigated>>> {
 9925        let multi_buffer = self.buffer.read(cx);
 9926        let selection = self.selections.newest::<usize>(cx);
 9927        let head = selection.head();
 9928
 9929        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9930        let head_anchor = multi_buffer_snapshot.anchor_at(
 9931            head,
 9932            if head < selection.tail() {
 9933                Bias::Right
 9934            } else {
 9935                Bias::Left
 9936            },
 9937        );
 9938
 9939        match self
 9940            .find_all_references_task_sources
 9941            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9942        {
 9943            Ok(_) => {
 9944                log::info!(
 9945                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9946                );
 9947                return None;
 9948            }
 9949            Err(i) => {
 9950                self.find_all_references_task_sources.insert(i, head_anchor);
 9951            }
 9952        }
 9953
 9954        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9955        let workspace = self.workspace()?;
 9956        let project = workspace.read(cx).project().clone();
 9957        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9958        Some(cx.spawn(|editor, mut cx| async move {
 9959            let _cleanup = defer({
 9960                let mut cx = cx.clone();
 9961                move || {
 9962                    let _ = editor.update(&mut cx, |editor, _| {
 9963                        if let Ok(i) =
 9964                            editor
 9965                                .find_all_references_task_sources
 9966                                .binary_search_by(|anchor| {
 9967                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9968                                })
 9969                        {
 9970                            editor.find_all_references_task_sources.remove(i);
 9971                        }
 9972                    });
 9973                }
 9974            });
 9975
 9976            let locations = references.await?;
 9977            if locations.is_empty() {
 9978                return anyhow::Ok(Navigated::No);
 9979            }
 9980
 9981            workspace.update(&mut cx, |workspace, cx| {
 9982                let title = locations
 9983                    .first()
 9984                    .as_ref()
 9985                    .map(|location| {
 9986                        let buffer = location.buffer.read(cx);
 9987                        format!(
 9988                            "References to `{}`",
 9989                            buffer
 9990                                .text_for_range(location.range.clone())
 9991                                .collect::<String>()
 9992                        )
 9993                    })
 9994                    .unwrap();
 9995                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9996                Navigated::Yes
 9997            })
 9998        }))
 9999    }
10000
10001    /// Opens a multibuffer with the given project locations in it
10002    pub fn open_locations_in_multibuffer(
10003        workspace: &mut Workspace,
10004        mut locations: Vec<Location>,
10005        title: String,
10006        split: bool,
10007        cx: &mut ViewContext<Workspace>,
10008    ) {
10009        // If there are multiple definitions, open them in a multibuffer
10010        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10011        let mut locations = locations.into_iter().peekable();
10012        let mut ranges_to_highlight = Vec::new();
10013        let capability = workspace.project().read(cx).capability();
10014
10015        let excerpt_buffer = cx.new_model(|cx| {
10016            let mut multibuffer = MultiBuffer::new(capability);
10017            while let Some(location) = locations.next() {
10018                let buffer = location.buffer.read(cx);
10019                let mut ranges_for_buffer = Vec::new();
10020                let range = location.range.to_offset(buffer);
10021                ranges_for_buffer.push(range.clone());
10022
10023                while let Some(next_location) = locations.peek() {
10024                    if next_location.buffer == location.buffer {
10025                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10026                        locations.next();
10027                    } else {
10028                        break;
10029                    }
10030                }
10031
10032                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10033                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10034                    location.buffer.clone(),
10035                    ranges_for_buffer,
10036                    DEFAULT_MULTIBUFFER_CONTEXT,
10037                    cx,
10038                ))
10039            }
10040
10041            multibuffer.with_title(title)
10042        });
10043
10044        let editor = cx.new_view(|cx| {
10045            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10046        });
10047        editor.update(cx, |editor, cx| {
10048            if let Some(first_range) = ranges_to_highlight.first() {
10049                editor.change_selections(None, cx, |selections| {
10050                    selections.clear_disjoint();
10051                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10052                });
10053            }
10054            editor.highlight_background::<Self>(
10055                &ranges_to_highlight,
10056                |theme| theme.editor_highlighted_line_background,
10057                cx,
10058            );
10059        });
10060
10061        let item = Box::new(editor);
10062        let item_id = item.item_id();
10063
10064        if split {
10065            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10066        } else {
10067            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10068                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10069                    pane.close_current_preview_item(cx)
10070                } else {
10071                    None
10072                }
10073            });
10074            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10075        }
10076        workspace.active_pane().update(cx, |pane, cx| {
10077            pane.set_preview_item_id(Some(item_id), cx);
10078        });
10079    }
10080
10081    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10082        use language::ToOffset as _;
10083
10084        let provider = self.semantics_provider.clone()?;
10085        let selection = self.selections.newest_anchor().clone();
10086        let (cursor_buffer, cursor_buffer_position) = self
10087            .buffer
10088            .read(cx)
10089            .text_anchor_for_position(selection.head(), cx)?;
10090        let (tail_buffer, cursor_buffer_position_end) = self
10091            .buffer
10092            .read(cx)
10093            .text_anchor_for_position(selection.tail(), cx)?;
10094        if tail_buffer != cursor_buffer {
10095            return None;
10096        }
10097
10098        let snapshot = cursor_buffer.read(cx).snapshot();
10099        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10100        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10101        let prepare_rename = provider
10102            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10103            .unwrap_or_else(|| Task::ready(Ok(None)));
10104        drop(snapshot);
10105
10106        Some(cx.spawn(|this, mut cx| async move {
10107            let rename_range = if let Some(range) = prepare_rename.await? {
10108                Some(range)
10109            } else {
10110                this.update(&mut cx, |this, cx| {
10111                    let buffer = this.buffer.read(cx).snapshot(cx);
10112                    let mut buffer_highlights = this
10113                        .document_highlights_for_position(selection.head(), &buffer)
10114                        .filter(|highlight| {
10115                            highlight.start.excerpt_id == selection.head().excerpt_id
10116                                && highlight.end.excerpt_id == selection.head().excerpt_id
10117                        });
10118                    buffer_highlights
10119                        .next()
10120                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10121                })?
10122            };
10123            if let Some(rename_range) = rename_range {
10124                this.update(&mut cx, |this, cx| {
10125                    let snapshot = cursor_buffer.read(cx).snapshot();
10126                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10127                    let cursor_offset_in_rename_range =
10128                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10129                    let cursor_offset_in_rename_range_end =
10130                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10131
10132                    this.take_rename(false, cx);
10133                    let buffer = this.buffer.read(cx).read(cx);
10134                    let cursor_offset = selection.head().to_offset(&buffer);
10135                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10136                    let rename_end = rename_start + rename_buffer_range.len();
10137                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10138                    let mut old_highlight_id = None;
10139                    let old_name: Arc<str> = buffer
10140                        .chunks(rename_start..rename_end, true)
10141                        .map(|chunk| {
10142                            if old_highlight_id.is_none() {
10143                                old_highlight_id = chunk.syntax_highlight_id;
10144                            }
10145                            chunk.text
10146                        })
10147                        .collect::<String>()
10148                        .into();
10149
10150                    drop(buffer);
10151
10152                    // Position the selection in the rename editor so that it matches the current selection.
10153                    this.show_local_selections = false;
10154                    let rename_editor = cx.new_view(|cx| {
10155                        let mut editor = Editor::single_line(cx);
10156                        editor.buffer.update(cx, |buffer, cx| {
10157                            buffer.edit([(0..0, old_name.clone())], None, cx)
10158                        });
10159                        let rename_selection_range = match cursor_offset_in_rename_range
10160                            .cmp(&cursor_offset_in_rename_range_end)
10161                        {
10162                            Ordering::Equal => {
10163                                editor.select_all(&SelectAll, cx);
10164                                return editor;
10165                            }
10166                            Ordering::Less => {
10167                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10168                            }
10169                            Ordering::Greater => {
10170                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10171                            }
10172                        };
10173                        if rename_selection_range.end > old_name.len() {
10174                            editor.select_all(&SelectAll, cx);
10175                        } else {
10176                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10177                                s.select_ranges([rename_selection_range]);
10178                            });
10179                        }
10180                        editor
10181                    });
10182                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10183                        if e == &EditorEvent::Focused {
10184                            cx.emit(EditorEvent::FocusedIn)
10185                        }
10186                    })
10187                    .detach();
10188
10189                    let write_highlights =
10190                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10191                    let read_highlights =
10192                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10193                    let ranges = write_highlights
10194                        .iter()
10195                        .flat_map(|(_, ranges)| ranges.iter())
10196                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10197                        .cloned()
10198                        .collect();
10199
10200                    this.highlight_text::<Rename>(
10201                        ranges,
10202                        HighlightStyle {
10203                            fade_out: Some(0.6),
10204                            ..Default::default()
10205                        },
10206                        cx,
10207                    );
10208                    let rename_focus_handle = rename_editor.focus_handle(cx);
10209                    cx.focus(&rename_focus_handle);
10210                    let block_id = this.insert_blocks(
10211                        [BlockProperties {
10212                            style: BlockStyle::Flex,
10213                            position: range.start,
10214                            height: 1,
10215                            render: Box::new({
10216                                let rename_editor = rename_editor.clone();
10217                                move |cx: &mut BlockContext| {
10218                                    let mut text_style = cx.editor_style.text.clone();
10219                                    if let Some(highlight_style) = old_highlight_id
10220                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10221                                    {
10222                                        text_style = text_style.highlight(highlight_style);
10223                                    }
10224                                    div()
10225                                        .pl(cx.anchor_x)
10226                                        .child(EditorElement::new(
10227                                            &rename_editor,
10228                                            EditorStyle {
10229                                                background: cx.theme().system().transparent,
10230                                                local_player: cx.editor_style.local_player,
10231                                                text: text_style,
10232                                                scrollbar_width: cx.editor_style.scrollbar_width,
10233                                                syntax: cx.editor_style.syntax.clone(),
10234                                                status: cx.editor_style.status.clone(),
10235                                                inlay_hints_style: HighlightStyle {
10236                                                    font_weight: Some(FontWeight::BOLD),
10237                                                    ..make_inlay_hints_style(cx)
10238                                                },
10239                                                suggestions_style: HighlightStyle {
10240                                                    color: Some(cx.theme().status().predictive),
10241                                                    ..HighlightStyle::default()
10242                                                },
10243                                                ..EditorStyle::default()
10244                                            },
10245                                        ))
10246                                        .into_any_element()
10247                                }
10248                            }),
10249                            disposition: BlockDisposition::Below,
10250                            priority: 0,
10251                        }],
10252                        Some(Autoscroll::fit()),
10253                        cx,
10254                    )[0];
10255                    this.pending_rename = Some(RenameState {
10256                        range,
10257                        old_name,
10258                        editor: rename_editor,
10259                        block_id,
10260                    });
10261                })?;
10262            }
10263
10264            Ok(())
10265        }))
10266    }
10267
10268    pub fn confirm_rename(
10269        &mut self,
10270        _: &ConfirmRename,
10271        cx: &mut ViewContext<Self>,
10272    ) -> Option<Task<Result<()>>> {
10273        let rename = self.take_rename(false, cx)?;
10274        let workspace = self.workspace()?.downgrade();
10275        let (buffer, start) = self
10276            .buffer
10277            .read(cx)
10278            .text_anchor_for_position(rename.range.start, cx)?;
10279        let (end_buffer, _) = self
10280            .buffer
10281            .read(cx)
10282            .text_anchor_for_position(rename.range.end, cx)?;
10283        if buffer != end_buffer {
10284            return None;
10285        }
10286
10287        let old_name = rename.old_name;
10288        let new_name = rename.editor.read(cx).text(cx);
10289
10290        let rename = self.semantics_provider.as_ref()?.perform_rename(
10291            &buffer,
10292            start,
10293            new_name.clone(),
10294            cx,
10295        )?;
10296
10297        Some(cx.spawn(|editor, mut cx| async move {
10298            let project_transaction = rename.await?;
10299            Self::open_project_transaction(
10300                &editor,
10301                workspace,
10302                project_transaction,
10303                format!("Rename: {}{}", old_name, new_name),
10304                cx.clone(),
10305            )
10306            .await?;
10307
10308            editor.update(&mut cx, |editor, cx| {
10309                editor.refresh_document_highlights(cx);
10310            })?;
10311            Ok(())
10312        }))
10313    }
10314
10315    fn take_rename(
10316        &mut self,
10317        moving_cursor: bool,
10318        cx: &mut ViewContext<Self>,
10319    ) -> Option<RenameState> {
10320        let rename = self.pending_rename.take()?;
10321        if rename.editor.focus_handle(cx).is_focused(cx) {
10322            cx.focus(&self.focus_handle);
10323        }
10324
10325        self.remove_blocks(
10326            [rename.block_id].into_iter().collect(),
10327            Some(Autoscroll::fit()),
10328            cx,
10329        );
10330        self.clear_highlights::<Rename>(cx);
10331        self.show_local_selections = true;
10332
10333        if moving_cursor {
10334            let rename_editor = rename.editor.read(cx);
10335            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10336
10337            // Update the selection to match the position of the selection inside
10338            // the rename editor.
10339            let snapshot = self.buffer.read(cx).read(cx);
10340            let rename_range = rename.range.to_offset(&snapshot);
10341            let cursor_in_editor = snapshot
10342                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10343                .min(rename_range.end);
10344            drop(snapshot);
10345
10346            self.change_selections(None, cx, |s| {
10347                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10348            });
10349        } else {
10350            self.refresh_document_highlights(cx);
10351        }
10352
10353        Some(rename)
10354    }
10355
10356    pub fn pending_rename(&self) -> Option<&RenameState> {
10357        self.pending_rename.as_ref()
10358    }
10359
10360    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10361        let project = match &self.project {
10362            Some(project) => project.clone(),
10363            None => return None,
10364        };
10365
10366        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10367    }
10368
10369    fn format_selections(
10370        &mut self,
10371        _: &FormatSelections,
10372        cx: &mut ViewContext<Self>,
10373    ) -> Option<Task<Result<()>>> {
10374        let project = match &self.project {
10375            Some(project) => project.clone(),
10376            None => return None,
10377        };
10378
10379        let selections = self
10380            .selections
10381            .all_adjusted(cx)
10382            .into_iter()
10383            .filter(|s| !s.is_empty())
10384            .collect_vec();
10385
10386        Some(self.perform_format(
10387            project,
10388            FormatTrigger::Manual,
10389            FormatTarget::Ranges(selections),
10390            cx,
10391        ))
10392    }
10393
10394    fn perform_format(
10395        &mut self,
10396        project: Model<Project>,
10397        trigger: FormatTrigger,
10398        target: FormatTarget,
10399        cx: &mut ViewContext<Self>,
10400    ) -> Task<Result<()>> {
10401        let buffer = self.buffer().clone();
10402        let mut buffers = buffer.read(cx).all_buffers();
10403        if trigger == FormatTrigger::Save {
10404            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10405        }
10406
10407        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10408        let format = project.update(cx, |project, cx| {
10409            project.format(buffers, true, trigger, target, cx)
10410        });
10411
10412        cx.spawn(|_, mut cx| async move {
10413            let transaction = futures::select_biased! {
10414                () = timeout => {
10415                    log::warn!("timed out waiting for formatting");
10416                    None
10417                }
10418                transaction = format.log_err().fuse() => transaction,
10419            };
10420
10421            buffer
10422                .update(&mut cx, |buffer, cx| {
10423                    if let Some(transaction) = transaction {
10424                        if !buffer.is_singleton() {
10425                            buffer.push_transaction(&transaction.0, cx);
10426                        }
10427                    }
10428
10429                    cx.notify();
10430                })
10431                .ok();
10432
10433            Ok(())
10434        })
10435    }
10436
10437    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10438        if let Some(project) = self.project.clone() {
10439            self.buffer.update(cx, |multi_buffer, cx| {
10440                project.update(cx, |project, cx| {
10441                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10442                });
10443            })
10444        }
10445    }
10446
10447    fn cancel_language_server_work(
10448        &mut self,
10449        _: &CancelLanguageServerWork,
10450        cx: &mut ViewContext<Self>,
10451    ) {
10452        if let Some(project) = self.project.clone() {
10453            self.buffer.update(cx, |multi_buffer, cx| {
10454                project.update(cx, |project, cx| {
10455                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10456                });
10457            })
10458        }
10459    }
10460
10461    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10462        cx.show_character_palette();
10463    }
10464
10465    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10466        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10467            let buffer = self.buffer.read(cx).snapshot(cx);
10468            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10469            let is_valid = buffer
10470                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10471                .any(|entry| {
10472                    entry.diagnostic.is_primary
10473                        && !entry.range.is_empty()
10474                        && entry.range.start == primary_range_start
10475                        && entry.diagnostic.message == active_diagnostics.primary_message
10476                });
10477
10478            if is_valid != active_diagnostics.is_valid {
10479                active_diagnostics.is_valid = is_valid;
10480                let mut new_styles = HashMap::default();
10481                for (block_id, diagnostic) in &active_diagnostics.blocks {
10482                    new_styles.insert(
10483                        *block_id,
10484                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10485                    );
10486                }
10487                self.display_map.update(cx, |display_map, _cx| {
10488                    display_map.replace_blocks(new_styles)
10489                });
10490            }
10491        }
10492    }
10493
10494    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10495        self.dismiss_diagnostics(cx);
10496        let snapshot = self.snapshot(cx);
10497        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10498            let buffer = self.buffer.read(cx).snapshot(cx);
10499
10500            let mut primary_range = None;
10501            let mut primary_message = None;
10502            let mut group_end = Point::zero();
10503            let diagnostic_group = buffer
10504                .diagnostic_group::<MultiBufferPoint>(group_id)
10505                .filter_map(|entry| {
10506                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10507                        && (entry.range.start.row == entry.range.end.row
10508                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10509                    {
10510                        return None;
10511                    }
10512                    if entry.range.end > group_end {
10513                        group_end = entry.range.end;
10514                    }
10515                    if entry.diagnostic.is_primary {
10516                        primary_range = Some(entry.range.clone());
10517                        primary_message = Some(entry.diagnostic.message.clone());
10518                    }
10519                    Some(entry)
10520                })
10521                .collect::<Vec<_>>();
10522            let primary_range = primary_range?;
10523            let primary_message = primary_message?;
10524            let primary_range =
10525                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10526
10527            let blocks = display_map
10528                .insert_blocks(
10529                    diagnostic_group.iter().map(|entry| {
10530                        let diagnostic = entry.diagnostic.clone();
10531                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10532                        BlockProperties {
10533                            style: BlockStyle::Fixed,
10534                            position: buffer.anchor_after(entry.range.start),
10535                            height: message_height,
10536                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10537                            disposition: BlockDisposition::Below,
10538                            priority: 0,
10539                        }
10540                    }),
10541                    cx,
10542                )
10543                .into_iter()
10544                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10545                .collect();
10546
10547            Some(ActiveDiagnosticGroup {
10548                primary_range,
10549                primary_message,
10550                group_id,
10551                blocks,
10552                is_valid: true,
10553            })
10554        });
10555        self.active_diagnostics.is_some()
10556    }
10557
10558    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10559        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10560            self.display_map.update(cx, |display_map, cx| {
10561                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10562            });
10563            cx.notify();
10564        }
10565    }
10566
10567    pub fn set_selections_from_remote(
10568        &mut self,
10569        selections: Vec<Selection<Anchor>>,
10570        pending_selection: Option<Selection<Anchor>>,
10571        cx: &mut ViewContext<Self>,
10572    ) {
10573        let old_cursor_position = self.selections.newest_anchor().head();
10574        self.selections.change_with(cx, |s| {
10575            s.select_anchors(selections);
10576            if let Some(pending_selection) = pending_selection {
10577                s.set_pending(pending_selection, SelectMode::Character);
10578            } else {
10579                s.clear_pending();
10580            }
10581        });
10582        self.selections_did_change(false, &old_cursor_position, true, cx);
10583    }
10584
10585    fn push_to_selection_history(&mut self) {
10586        self.selection_history.push(SelectionHistoryEntry {
10587            selections: self.selections.disjoint_anchors(),
10588            select_next_state: self.select_next_state.clone(),
10589            select_prev_state: self.select_prev_state.clone(),
10590            add_selections_state: self.add_selections_state.clone(),
10591        });
10592    }
10593
10594    pub fn transact(
10595        &mut self,
10596        cx: &mut ViewContext<Self>,
10597        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10598    ) -> Option<TransactionId> {
10599        self.start_transaction_at(Instant::now(), cx);
10600        update(self, cx);
10601        self.end_transaction_at(Instant::now(), cx)
10602    }
10603
10604    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10605        self.end_selection(cx);
10606        if let Some(tx_id) = self
10607            .buffer
10608            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10609        {
10610            self.selection_history
10611                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10612            cx.emit(EditorEvent::TransactionBegun {
10613                transaction_id: tx_id,
10614            })
10615        }
10616    }
10617
10618    fn end_transaction_at(
10619        &mut self,
10620        now: Instant,
10621        cx: &mut ViewContext<Self>,
10622    ) -> Option<TransactionId> {
10623        if let Some(transaction_id) = self
10624            .buffer
10625            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10626        {
10627            if let Some((_, end_selections)) =
10628                self.selection_history.transaction_mut(transaction_id)
10629            {
10630                *end_selections = Some(self.selections.disjoint_anchors());
10631            } else {
10632                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10633            }
10634
10635            cx.emit(EditorEvent::Edited { transaction_id });
10636            Some(transaction_id)
10637        } else {
10638            None
10639        }
10640    }
10641
10642    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10643        let selection = self.selections.newest::<Point>(cx);
10644
10645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10646        let range = if selection.is_empty() {
10647            let point = selection.head().to_display_point(&display_map);
10648            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10649            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10650                .to_point(&display_map);
10651            start..end
10652        } else {
10653            selection.range()
10654        };
10655        if display_map.folds_in_range(range).next().is_some() {
10656            self.unfold_lines(&Default::default(), cx)
10657        } else {
10658            self.fold(&Default::default(), cx)
10659        }
10660    }
10661
10662    pub fn toggle_fold_recursive(
10663        &mut self,
10664        _: &actions::ToggleFoldRecursive,
10665        cx: &mut ViewContext<Self>,
10666    ) {
10667        let selection = self.selections.newest::<Point>(cx);
10668
10669        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10670        let range = if selection.is_empty() {
10671            let point = selection.head().to_display_point(&display_map);
10672            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10673            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10674                .to_point(&display_map);
10675            start..end
10676        } else {
10677            selection.range()
10678        };
10679        if display_map.folds_in_range(range).next().is_some() {
10680            self.unfold_recursive(&Default::default(), cx)
10681        } else {
10682            self.fold_recursive(&Default::default(), cx)
10683        }
10684    }
10685
10686    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10687        let mut fold_ranges = Vec::new();
10688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10689        let selections = self.selections.all_adjusted(cx);
10690
10691        for selection in selections {
10692            let range = selection.range().sorted();
10693            let buffer_start_row = range.start.row;
10694
10695            if range.start.row != range.end.row {
10696                let mut found = false;
10697                let mut row = range.start.row;
10698                while row <= range.end.row {
10699                    if let Some((foldable_range, fold_text)) =
10700                        { display_map.foldable_range(MultiBufferRow(row)) }
10701                    {
10702                        found = true;
10703                        row = foldable_range.end.row + 1;
10704                        fold_ranges.push((foldable_range, fold_text));
10705                    } else {
10706                        row += 1
10707                    }
10708                }
10709                if found {
10710                    continue;
10711                }
10712            }
10713
10714            for row in (0..=range.start.row).rev() {
10715                if let Some((foldable_range, fold_text)) =
10716                    display_map.foldable_range(MultiBufferRow(row))
10717                {
10718                    if foldable_range.end.row >= buffer_start_row {
10719                        fold_ranges.push((foldable_range, fold_text));
10720                        if row <= range.start.row {
10721                            break;
10722                        }
10723                    }
10724                }
10725            }
10726        }
10727
10728        self.fold_ranges(fold_ranges, true, cx);
10729    }
10730
10731    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10732        let mut fold_ranges = Vec::new();
10733        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10734
10735        for row in 0..display_map.max_buffer_row().0 {
10736            if let Some((foldable_range, fold_text)) =
10737                display_map.foldable_range(MultiBufferRow(row))
10738            {
10739                fold_ranges.push((foldable_range, fold_text));
10740            }
10741        }
10742
10743        self.fold_ranges(fold_ranges, true, cx);
10744    }
10745
10746    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10747        let mut fold_ranges = Vec::new();
10748        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10749        let selections = self.selections.all_adjusted(cx);
10750
10751        for selection in selections {
10752            let range = selection.range().sorted();
10753            let buffer_start_row = range.start.row;
10754
10755            if range.start.row != range.end.row {
10756                let mut found = false;
10757                for row in range.start.row..=range.end.row {
10758                    if let Some((foldable_range, fold_text)) =
10759                        { display_map.foldable_range(MultiBufferRow(row)) }
10760                    {
10761                        found = true;
10762                        fold_ranges.push((foldable_range, fold_text));
10763                    }
10764                }
10765                if found {
10766                    continue;
10767                }
10768            }
10769
10770            for row in (0..=range.start.row).rev() {
10771                if let Some((foldable_range, fold_text)) =
10772                    display_map.foldable_range(MultiBufferRow(row))
10773                {
10774                    if foldable_range.end.row >= buffer_start_row {
10775                        fold_ranges.push((foldable_range, fold_text));
10776                    } else {
10777                        break;
10778                    }
10779                }
10780            }
10781        }
10782
10783        self.fold_ranges(fold_ranges, true, cx);
10784    }
10785
10786    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10787        let buffer_row = fold_at.buffer_row;
10788        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10789
10790        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10791            let autoscroll = self
10792                .selections
10793                .all::<Point>(cx)
10794                .iter()
10795                .any(|selection| fold_range.overlaps(&selection.range()));
10796
10797            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10798        }
10799    }
10800
10801    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10802        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10803        let buffer = &display_map.buffer_snapshot;
10804        let selections = self.selections.all::<Point>(cx);
10805        let ranges = selections
10806            .iter()
10807            .map(|s| {
10808                let range = s.display_range(&display_map).sorted();
10809                let mut start = range.start.to_point(&display_map);
10810                let mut end = range.end.to_point(&display_map);
10811                start.column = 0;
10812                end.column = buffer.line_len(MultiBufferRow(end.row));
10813                start..end
10814            })
10815            .collect::<Vec<_>>();
10816
10817        self.unfold_ranges(ranges, true, true, cx);
10818    }
10819
10820    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10821        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10822        let selections = self.selections.all::<Point>(cx);
10823        let ranges = selections
10824            .iter()
10825            .map(|s| {
10826                let mut range = s.display_range(&display_map).sorted();
10827                *range.start.column_mut() = 0;
10828                *range.end.column_mut() = display_map.line_len(range.end.row());
10829                let start = range.start.to_point(&display_map);
10830                let end = range.end.to_point(&display_map);
10831                start..end
10832            })
10833            .collect::<Vec<_>>();
10834
10835        self.unfold_ranges(ranges, true, true, cx);
10836    }
10837
10838    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10839        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10840
10841        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10842            ..Point::new(
10843                unfold_at.buffer_row.0,
10844                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10845            );
10846
10847        let autoscroll = self
10848            .selections
10849            .all::<Point>(cx)
10850            .iter()
10851            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10852
10853        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10854    }
10855
10856    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10857        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10858        self.unfold_ranges(
10859            [Point::zero()..display_map.max_point().to_point(&display_map)],
10860            true,
10861            true,
10862            cx,
10863        );
10864    }
10865
10866    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10867        let selections = self.selections.all::<Point>(cx);
10868        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10869        let line_mode = self.selections.line_mode;
10870        let ranges = selections.into_iter().map(|s| {
10871            if line_mode {
10872                let start = Point::new(s.start.row, 0);
10873                let end = Point::new(
10874                    s.end.row,
10875                    display_map
10876                        .buffer_snapshot
10877                        .line_len(MultiBufferRow(s.end.row)),
10878                );
10879                (start..end, display_map.fold_placeholder.clone())
10880            } else {
10881                (s.start..s.end, display_map.fold_placeholder.clone())
10882            }
10883        });
10884        self.fold_ranges(ranges, true, cx);
10885    }
10886
10887    pub fn fold_ranges<T: ToOffset + Clone>(
10888        &mut self,
10889        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10890        auto_scroll: bool,
10891        cx: &mut ViewContext<Self>,
10892    ) {
10893        let mut fold_ranges = Vec::new();
10894        let mut buffers_affected = HashMap::default();
10895        let multi_buffer = self.buffer().read(cx);
10896        for (fold_range, fold_text) in ranges {
10897            if let Some((_, buffer, _)) =
10898                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10899            {
10900                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10901            };
10902            fold_ranges.push((fold_range, fold_text));
10903        }
10904
10905        let mut ranges = fold_ranges.into_iter().peekable();
10906        if ranges.peek().is_some() {
10907            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10908
10909            if auto_scroll {
10910                self.request_autoscroll(Autoscroll::fit(), cx);
10911            }
10912
10913            for buffer in buffers_affected.into_values() {
10914                self.sync_expanded_diff_hunks(buffer, cx);
10915            }
10916
10917            cx.notify();
10918
10919            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10920                // Clear diagnostics block when folding a range that contains it.
10921                let snapshot = self.snapshot(cx);
10922                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10923                    drop(snapshot);
10924                    self.active_diagnostics = Some(active_diagnostics);
10925                    self.dismiss_diagnostics(cx);
10926                } else {
10927                    self.active_diagnostics = Some(active_diagnostics);
10928                }
10929            }
10930
10931            self.scrollbar_marker_state.dirty = true;
10932        }
10933    }
10934
10935    pub fn unfold_ranges<T: ToOffset + Clone>(
10936        &mut self,
10937        ranges: impl IntoIterator<Item = Range<T>>,
10938        inclusive: bool,
10939        auto_scroll: bool,
10940        cx: &mut ViewContext<Self>,
10941    ) {
10942        let mut unfold_ranges = Vec::new();
10943        let mut buffers_affected = HashMap::default();
10944        let multi_buffer = self.buffer().read(cx);
10945        for range in ranges {
10946            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10947                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10948            };
10949            unfold_ranges.push(range);
10950        }
10951
10952        let mut ranges = unfold_ranges.into_iter().peekable();
10953        if ranges.peek().is_some() {
10954            self.display_map
10955                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10956            if auto_scroll {
10957                self.request_autoscroll(Autoscroll::fit(), cx);
10958            }
10959
10960            for buffer in buffers_affected.into_values() {
10961                self.sync_expanded_diff_hunks(buffer, cx);
10962            }
10963
10964            cx.notify();
10965            self.scrollbar_marker_state.dirty = true;
10966            self.active_indent_guides_state.dirty = true;
10967        }
10968    }
10969
10970    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10971        self.display_map.read(cx).fold_placeholder.clone()
10972    }
10973
10974    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10975        if hovered != self.gutter_hovered {
10976            self.gutter_hovered = hovered;
10977            cx.notify();
10978        }
10979    }
10980
10981    pub fn insert_blocks(
10982        &mut self,
10983        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10984        autoscroll: Option<Autoscroll>,
10985        cx: &mut ViewContext<Self>,
10986    ) -> Vec<CustomBlockId> {
10987        let blocks = self
10988            .display_map
10989            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10990        if let Some(autoscroll) = autoscroll {
10991            self.request_autoscroll(autoscroll, cx);
10992        }
10993        cx.notify();
10994        blocks
10995    }
10996
10997    pub fn resize_blocks(
10998        &mut self,
10999        heights: HashMap<CustomBlockId, u32>,
11000        autoscroll: Option<Autoscroll>,
11001        cx: &mut ViewContext<Self>,
11002    ) {
11003        self.display_map
11004            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11005        if let Some(autoscroll) = autoscroll {
11006            self.request_autoscroll(autoscroll, cx);
11007        }
11008        cx.notify();
11009    }
11010
11011    pub fn replace_blocks(
11012        &mut self,
11013        renderers: HashMap<CustomBlockId, RenderBlock>,
11014        autoscroll: Option<Autoscroll>,
11015        cx: &mut ViewContext<Self>,
11016    ) {
11017        self.display_map
11018            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11019        if let Some(autoscroll) = autoscroll {
11020            self.request_autoscroll(autoscroll, cx);
11021        }
11022        cx.notify();
11023    }
11024
11025    pub fn remove_blocks(
11026        &mut self,
11027        block_ids: HashSet<CustomBlockId>,
11028        autoscroll: Option<Autoscroll>,
11029        cx: &mut ViewContext<Self>,
11030    ) {
11031        self.display_map.update(cx, |display_map, cx| {
11032            display_map.remove_blocks(block_ids, cx)
11033        });
11034        if let Some(autoscroll) = autoscroll {
11035            self.request_autoscroll(autoscroll, cx);
11036        }
11037        cx.notify();
11038    }
11039
11040    pub fn row_for_block(
11041        &self,
11042        block_id: CustomBlockId,
11043        cx: &mut ViewContext<Self>,
11044    ) -> Option<DisplayRow> {
11045        self.display_map
11046            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11047    }
11048
11049    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11050        self.focused_block = Some(focused_block);
11051    }
11052
11053    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11054        self.focused_block.take()
11055    }
11056
11057    pub fn insert_creases(
11058        &mut self,
11059        creases: impl IntoIterator<Item = Crease>,
11060        cx: &mut ViewContext<Self>,
11061    ) -> Vec<CreaseId> {
11062        self.display_map
11063            .update(cx, |map, cx| map.insert_creases(creases, cx))
11064    }
11065
11066    pub fn remove_creases(
11067        &mut self,
11068        ids: impl IntoIterator<Item = CreaseId>,
11069        cx: &mut ViewContext<Self>,
11070    ) {
11071        self.display_map
11072            .update(cx, |map, cx| map.remove_creases(ids, cx));
11073    }
11074
11075    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11076        self.display_map
11077            .update(cx, |map, cx| map.snapshot(cx))
11078            .longest_row()
11079    }
11080
11081    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11082        self.display_map
11083            .update(cx, |map, cx| map.snapshot(cx))
11084            .max_point()
11085    }
11086
11087    pub fn text(&self, cx: &AppContext) -> String {
11088        self.buffer.read(cx).read(cx).text()
11089    }
11090
11091    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11092        let text = self.text(cx);
11093        let text = text.trim();
11094
11095        if text.is_empty() {
11096            return None;
11097        }
11098
11099        Some(text.to_string())
11100    }
11101
11102    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11103        self.transact(cx, |this, cx| {
11104            this.buffer
11105                .read(cx)
11106                .as_singleton()
11107                .expect("you can only call set_text on editors for singleton buffers")
11108                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11109        });
11110    }
11111
11112    pub fn display_text(&self, cx: &mut AppContext) -> String {
11113        self.display_map
11114            .update(cx, |map, cx| map.snapshot(cx))
11115            .text()
11116    }
11117
11118    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11119        let mut wrap_guides = smallvec::smallvec![];
11120
11121        if self.show_wrap_guides == Some(false) {
11122            return wrap_guides;
11123        }
11124
11125        let settings = self.buffer.read(cx).settings_at(0, cx);
11126        if settings.show_wrap_guides {
11127            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11128                wrap_guides.push((soft_wrap as usize, true));
11129            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11130                wrap_guides.push((soft_wrap as usize, true));
11131            }
11132            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11133        }
11134
11135        wrap_guides
11136    }
11137
11138    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11139        let settings = self.buffer.read(cx).settings_at(0, cx);
11140        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11141        match mode {
11142            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11143                SoftWrap::None
11144            }
11145            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11146            language_settings::SoftWrap::PreferredLineLength => {
11147                SoftWrap::Column(settings.preferred_line_length)
11148            }
11149            language_settings::SoftWrap::Bounded => {
11150                SoftWrap::Bounded(settings.preferred_line_length)
11151            }
11152        }
11153    }
11154
11155    pub fn set_soft_wrap_mode(
11156        &mut self,
11157        mode: language_settings::SoftWrap,
11158        cx: &mut ViewContext<Self>,
11159    ) {
11160        self.soft_wrap_mode_override = Some(mode);
11161        cx.notify();
11162    }
11163
11164    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11165        self.text_style_refinement = Some(style);
11166    }
11167
11168    /// called by the Element so we know what style we were most recently rendered with.
11169    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11170        let rem_size = cx.rem_size();
11171        self.display_map.update(cx, |map, cx| {
11172            map.set_font(
11173                style.text.font(),
11174                style.text.font_size.to_pixels(rem_size),
11175                cx,
11176            )
11177        });
11178        self.style = Some(style);
11179    }
11180
11181    pub fn style(&self) -> Option<&EditorStyle> {
11182        self.style.as_ref()
11183    }
11184
11185    // Called by the element. This method is not designed to be called outside of the editor
11186    // element's layout code because it does not notify when rewrapping is computed synchronously.
11187    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11188        self.display_map
11189            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11190    }
11191
11192    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11193        if self.soft_wrap_mode_override.is_some() {
11194            self.soft_wrap_mode_override.take();
11195        } else {
11196            let soft_wrap = match self.soft_wrap_mode(cx) {
11197                SoftWrap::GitDiff => return,
11198                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11199                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11200                    language_settings::SoftWrap::None
11201                }
11202            };
11203            self.soft_wrap_mode_override = Some(soft_wrap);
11204        }
11205        cx.notify();
11206    }
11207
11208    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11209        let Some(workspace) = self.workspace() else {
11210            return;
11211        };
11212        let fs = workspace.read(cx).app_state().fs.clone();
11213        let current_show = TabBarSettings::get_global(cx).show;
11214        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11215            setting.show = Some(!current_show);
11216        });
11217    }
11218
11219    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11220        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11221            self.buffer
11222                .read(cx)
11223                .settings_at(0, cx)
11224                .indent_guides
11225                .enabled
11226        });
11227        self.show_indent_guides = Some(!currently_enabled);
11228        cx.notify();
11229    }
11230
11231    fn should_show_indent_guides(&self) -> Option<bool> {
11232        self.show_indent_guides
11233    }
11234
11235    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11236        let mut editor_settings = EditorSettings::get_global(cx).clone();
11237        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11238        EditorSettings::override_global(editor_settings, cx);
11239    }
11240
11241    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11242        self.use_relative_line_numbers
11243            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11244    }
11245
11246    pub fn toggle_relative_line_numbers(
11247        &mut self,
11248        _: &ToggleRelativeLineNumbers,
11249        cx: &mut ViewContext<Self>,
11250    ) {
11251        let is_relative = self.should_use_relative_line_numbers(cx);
11252        self.set_relative_line_number(Some(!is_relative), cx)
11253    }
11254
11255    pub fn set_relative_line_number(
11256        &mut self,
11257        is_relative: Option<bool>,
11258        cx: &mut ViewContext<Self>,
11259    ) {
11260        self.use_relative_line_numbers = is_relative;
11261        cx.notify();
11262    }
11263
11264    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11265        self.show_gutter = show_gutter;
11266        cx.notify();
11267    }
11268
11269    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11270        self.show_line_numbers = Some(show_line_numbers);
11271        cx.notify();
11272    }
11273
11274    pub fn set_show_git_diff_gutter(
11275        &mut self,
11276        show_git_diff_gutter: bool,
11277        cx: &mut ViewContext<Self>,
11278    ) {
11279        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11280        cx.notify();
11281    }
11282
11283    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11284        self.show_code_actions = Some(show_code_actions);
11285        cx.notify();
11286    }
11287
11288    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11289        self.show_runnables = Some(show_runnables);
11290        cx.notify();
11291    }
11292
11293    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11294        if self.display_map.read(cx).masked != masked {
11295            self.display_map.update(cx, |map, _| map.masked = masked);
11296        }
11297        cx.notify()
11298    }
11299
11300    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11301        self.show_wrap_guides = Some(show_wrap_guides);
11302        cx.notify();
11303    }
11304
11305    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11306        self.show_indent_guides = Some(show_indent_guides);
11307        cx.notify();
11308    }
11309
11310    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11311        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11312            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11313                if let Some(dir) = file.abs_path(cx).parent() {
11314                    return Some(dir.to_owned());
11315                }
11316            }
11317
11318            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11319                return Some(project_path.path.to_path_buf());
11320            }
11321        }
11322
11323        None
11324    }
11325
11326    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11327        self.active_excerpt(cx)?
11328            .1
11329            .read(cx)
11330            .file()
11331            .and_then(|f| f.as_local())
11332    }
11333
11334    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11335        if let Some(target) = self.target_file(cx) {
11336            cx.reveal_path(&target.abs_path(cx));
11337        }
11338    }
11339
11340    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11341        if let Some(file) = self.target_file(cx) {
11342            if let Some(path) = file.abs_path(cx).to_str() {
11343                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11344            }
11345        }
11346    }
11347
11348    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11349        if let Some(file) = self.target_file(cx) {
11350            if let Some(path) = file.path().to_str() {
11351                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11352            }
11353        }
11354    }
11355
11356    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11357        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11358
11359        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11360            self.start_git_blame(true, cx);
11361        }
11362
11363        cx.notify();
11364    }
11365
11366    pub fn toggle_git_blame_inline(
11367        &mut self,
11368        _: &ToggleGitBlameInline,
11369        cx: &mut ViewContext<Self>,
11370    ) {
11371        self.toggle_git_blame_inline_internal(true, cx);
11372        cx.notify();
11373    }
11374
11375    pub fn git_blame_inline_enabled(&self) -> bool {
11376        self.git_blame_inline_enabled
11377    }
11378
11379    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11380        self.show_selection_menu = self
11381            .show_selection_menu
11382            .map(|show_selections_menu| !show_selections_menu)
11383            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11384
11385        cx.notify();
11386    }
11387
11388    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11389        self.show_selection_menu
11390            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11391    }
11392
11393    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11394        if let Some(project) = self.project.as_ref() {
11395            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11396                return;
11397            };
11398
11399            if buffer.read(cx).file().is_none() {
11400                return;
11401            }
11402
11403            let focused = self.focus_handle(cx).contains_focused(cx);
11404
11405            let project = project.clone();
11406            let blame =
11407                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11408            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11409            self.blame = Some(blame);
11410        }
11411    }
11412
11413    fn toggle_git_blame_inline_internal(
11414        &mut self,
11415        user_triggered: bool,
11416        cx: &mut ViewContext<Self>,
11417    ) {
11418        if self.git_blame_inline_enabled {
11419            self.git_blame_inline_enabled = false;
11420            self.show_git_blame_inline = false;
11421            self.show_git_blame_inline_delay_task.take();
11422        } else {
11423            self.git_blame_inline_enabled = true;
11424            self.start_git_blame_inline(user_triggered, cx);
11425        }
11426
11427        cx.notify();
11428    }
11429
11430    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11431        self.start_git_blame(user_triggered, cx);
11432
11433        if ProjectSettings::get_global(cx)
11434            .git
11435            .inline_blame_delay()
11436            .is_some()
11437        {
11438            self.start_inline_blame_timer(cx);
11439        } else {
11440            self.show_git_blame_inline = true
11441        }
11442    }
11443
11444    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11445        self.blame.as_ref()
11446    }
11447
11448    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11449        self.show_git_blame_gutter && self.has_blame_entries(cx)
11450    }
11451
11452    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11453        self.show_git_blame_inline
11454            && self.focus_handle.is_focused(cx)
11455            && !self.newest_selection_head_on_empty_line(cx)
11456            && self.has_blame_entries(cx)
11457    }
11458
11459    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11460        self.blame()
11461            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11462    }
11463
11464    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11465        let cursor_anchor = self.selections.newest_anchor().head();
11466
11467        let snapshot = self.buffer.read(cx).snapshot(cx);
11468        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11469
11470        snapshot.line_len(buffer_row) == 0
11471    }
11472
11473    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11474        let buffer_and_selection = maybe!({
11475            let selection = self.selections.newest::<Point>(cx);
11476            let selection_range = selection.range();
11477
11478            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11479                (buffer, selection_range.start.row..selection_range.end.row)
11480            } else {
11481                let buffer_ranges = self
11482                    .buffer()
11483                    .read(cx)
11484                    .range_to_buffer_ranges(selection_range, cx);
11485
11486                let (buffer, range, _) = if selection.reversed {
11487                    buffer_ranges.first()
11488                } else {
11489                    buffer_ranges.last()
11490                }?;
11491
11492                let snapshot = buffer.read(cx).snapshot();
11493                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11494                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11495                (buffer.clone(), selection)
11496            };
11497
11498            Some((buffer, selection))
11499        });
11500
11501        let Some((buffer, selection)) = buffer_and_selection else {
11502            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11503        };
11504
11505        let Some(project) = self.project.as_ref() else {
11506            return Task::ready(Err(anyhow!("editor does not have project")));
11507        };
11508
11509        project.update(cx, |project, cx| {
11510            project.get_permalink_to_line(&buffer, selection, cx)
11511        })
11512    }
11513
11514    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11515        let permalink_task = self.get_permalink_to_line(cx);
11516        let workspace = self.workspace();
11517
11518        cx.spawn(|_, mut cx| async move {
11519            match permalink_task.await {
11520                Ok(permalink) => {
11521                    cx.update(|cx| {
11522                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11523                    })
11524                    .ok();
11525                }
11526                Err(err) => {
11527                    let message = format!("Failed to copy permalink: {err}");
11528
11529                    Err::<(), anyhow::Error>(err).log_err();
11530
11531                    if let Some(workspace) = workspace {
11532                        workspace
11533                            .update(&mut cx, |workspace, cx| {
11534                                struct CopyPermalinkToLine;
11535
11536                                workspace.show_toast(
11537                                    Toast::new(
11538                                        NotificationId::unique::<CopyPermalinkToLine>(),
11539                                        message,
11540                                    ),
11541                                    cx,
11542                                )
11543                            })
11544                            .ok();
11545                    }
11546                }
11547            }
11548        })
11549        .detach();
11550    }
11551
11552    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11553        if let Some(file) = self.target_file(cx) {
11554            if let Some(path) = file.path().to_str() {
11555                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11556                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11557            }
11558        }
11559    }
11560
11561    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11562        let permalink_task = self.get_permalink_to_line(cx);
11563        let workspace = self.workspace();
11564
11565        cx.spawn(|_, mut cx| async move {
11566            match permalink_task.await {
11567                Ok(permalink) => {
11568                    cx.update(|cx| {
11569                        cx.open_url(permalink.as_ref());
11570                    })
11571                    .ok();
11572                }
11573                Err(err) => {
11574                    let message = format!("Failed to open permalink: {err}");
11575
11576                    Err::<(), anyhow::Error>(err).log_err();
11577
11578                    if let Some(workspace) = workspace {
11579                        workspace
11580                            .update(&mut cx, |workspace, cx| {
11581                                struct OpenPermalinkToLine;
11582
11583                                workspace.show_toast(
11584                                    Toast::new(
11585                                        NotificationId::unique::<OpenPermalinkToLine>(),
11586                                        message,
11587                                    ),
11588                                    cx,
11589                                )
11590                            })
11591                            .ok();
11592                    }
11593                }
11594            }
11595        })
11596        .detach();
11597    }
11598
11599    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11600    /// last highlight added will be used.
11601    ///
11602    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11603    pub fn highlight_rows<T: 'static>(
11604        &mut self,
11605        range: Range<Anchor>,
11606        color: Hsla,
11607        should_autoscroll: bool,
11608        cx: &mut ViewContext<Self>,
11609    ) {
11610        let snapshot = self.buffer().read(cx).snapshot(cx);
11611        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11612        let ix = row_highlights.binary_search_by(|highlight| {
11613            Ordering::Equal
11614                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11615                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11616        });
11617
11618        if let Err(mut ix) = ix {
11619            let index = post_inc(&mut self.highlight_order);
11620
11621            // If this range intersects with the preceding highlight, then merge it with
11622            // the preceding highlight. Otherwise insert a new highlight.
11623            let mut merged = false;
11624            if ix > 0 {
11625                let prev_highlight = &mut row_highlights[ix - 1];
11626                if prev_highlight
11627                    .range
11628                    .end
11629                    .cmp(&range.start, &snapshot)
11630                    .is_ge()
11631                {
11632                    ix -= 1;
11633                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11634                        prev_highlight.range.end = range.end;
11635                    }
11636                    merged = true;
11637                    prev_highlight.index = index;
11638                    prev_highlight.color = color;
11639                    prev_highlight.should_autoscroll = should_autoscroll;
11640                }
11641            }
11642
11643            if !merged {
11644                row_highlights.insert(
11645                    ix,
11646                    RowHighlight {
11647                        range: range.clone(),
11648                        index,
11649                        color,
11650                        should_autoscroll,
11651                    },
11652                );
11653            }
11654
11655            // If any of the following highlights intersect with this one, merge them.
11656            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11657                let highlight = &row_highlights[ix];
11658                if next_highlight
11659                    .range
11660                    .start
11661                    .cmp(&highlight.range.end, &snapshot)
11662                    .is_le()
11663                {
11664                    if next_highlight
11665                        .range
11666                        .end
11667                        .cmp(&highlight.range.end, &snapshot)
11668                        .is_gt()
11669                    {
11670                        row_highlights[ix].range.end = next_highlight.range.end;
11671                    }
11672                    row_highlights.remove(ix + 1);
11673                } else {
11674                    break;
11675                }
11676            }
11677        }
11678    }
11679
11680    /// Remove any highlighted row ranges of the given type that intersect the
11681    /// given ranges.
11682    pub fn remove_highlighted_rows<T: 'static>(
11683        &mut self,
11684        ranges_to_remove: Vec<Range<Anchor>>,
11685        cx: &mut ViewContext<Self>,
11686    ) {
11687        let snapshot = self.buffer().read(cx).snapshot(cx);
11688        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11689        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11690        row_highlights.retain(|highlight| {
11691            while let Some(range_to_remove) = ranges_to_remove.peek() {
11692                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11693                    Ordering::Less | Ordering::Equal => {
11694                        ranges_to_remove.next();
11695                    }
11696                    Ordering::Greater => {
11697                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11698                            Ordering::Less | Ordering::Equal => {
11699                                return false;
11700                            }
11701                            Ordering::Greater => break,
11702                        }
11703                    }
11704                }
11705            }
11706
11707            true
11708        })
11709    }
11710
11711    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11712    pub fn clear_row_highlights<T: 'static>(&mut self) {
11713        self.highlighted_rows.remove(&TypeId::of::<T>());
11714    }
11715
11716    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11717    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11718        self.highlighted_rows
11719            .get(&TypeId::of::<T>())
11720            .map_or(&[] as &[_], |vec| vec.as_slice())
11721            .iter()
11722            .map(|highlight| (highlight.range.clone(), highlight.color))
11723    }
11724
11725    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11726    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11727    /// Allows to ignore certain kinds of highlights.
11728    pub fn highlighted_display_rows(
11729        &mut self,
11730        cx: &mut WindowContext,
11731    ) -> BTreeMap<DisplayRow, Hsla> {
11732        let snapshot = self.snapshot(cx);
11733        let mut used_highlight_orders = HashMap::default();
11734        self.highlighted_rows
11735            .iter()
11736            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11737            .fold(
11738                BTreeMap::<DisplayRow, Hsla>::new(),
11739                |mut unique_rows, highlight| {
11740                    let start = highlight.range.start.to_display_point(&snapshot);
11741                    let end = highlight.range.end.to_display_point(&snapshot);
11742                    let start_row = start.row().0;
11743                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11744                        && end.column() == 0
11745                    {
11746                        end.row().0.saturating_sub(1)
11747                    } else {
11748                        end.row().0
11749                    };
11750                    for row in start_row..=end_row {
11751                        let used_index =
11752                            used_highlight_orders.entry(row).or_insert(highlight.index);
11753                        if highlight.index >= *used_index {
11754                            *used_index = highlight.index;
11755                            unique_rows.insert(DisplayRow(row), highlight.color);
11756                        }
11757                    }
11758                    unique_rows
11759                },
11760            )
11761    }
11762
11763    pub fn highlighted_display_row_for_autoscroll(
11764        &self,
11765        snapshot: &DisplaySnapshot,
11766    ) -> Option<DisplayRow> {
11767        self.highlighted_rows
11768            .values()
11769            .flat_map(|highlighted_rows| highlighted_rows.iter())
11770            .filter_map(|highlight| {
11771                if highlight.should_autoscroll {
11772                    Some(highlight.range.start.to_display_point(snapshot).row())
11773                } else {
11774                    None
11775                }
11776            })
11777            .min()
11778    }
11779
11780    pub fn set_search_within_ranges(
11781        &mut self,
11782        ranges: &[Range<Anchor>],
11783        cx: &mut ViewContext<Self>,
11784    ) {
11785        self.highlight_background::<SearchWithinRange>(
11786            ranges,
11787            |colors| colors.editor_document_highlight_read_background,
11788            cx,
11789        )
11790    }
11791
11792    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11793        self.breadcrumb_header = Some(new_header);
11794    }
11795
11796    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11797        self.clear_background_highlights::<SearchWithinRange>(cx);
11798    }
11799
11800    pub fn highlight_background<T: 'static>(
11801        &mut self,
11802        ranges: &[Range<Anchor>],
11803        color_fetcher: fn(&ThemeColors) -> Hsla,
11804        cx: &mut ViewContext<Self>,
11805    ) {
11806        self.background_highlights
11807            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11808        self.scrollbar_marker_state.dirty = true;
11809        cx.notify();
11810    }
11811
11812    pub fn clear_background_highlights<T: 'static>(
11813        &mut self,
11814        cx: &mut ViewContext<Self>,
11815    ) -> Option<BackgroundHighlight> {
11816        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11817        if !text_highlights.1.is_empty() {
11818            self.scrollbar_marker_state.dirty = true;
11819            cx.notify();
11820        }
11821        Some(text_highlights)
11822    }
11823
11824    pub fn highlight_gutter<T: 'static>(
11825        &mut self,
11826        ranges: &[Range<Anchor>],
11827        color_fetcher: fn(&AppContext) -> Hsla,
11828        cx: &mut ViewContext<Self>,
11829    ) {
11830        self.gutter_highlights
11831            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11832        cx.notify();
11833    }
11834
11835    pub fn clear_gutter_highlights<T: 'static>(
11836        &mut self,
11837        cx: &mut ViewContext<Self>,
11838    ) -> Option<GutterHighlight> {
11839        cx.notify();
11840        self.gutter_highlights.remove(&TypeId::of::<T>())
11841    }
11842
11843    #[cfg(feature = "test-support")]
11844    pub fn all_text_background_highlights(
11845        &mut self,
11846        cx: &mut ViewContext<Self>,
11847    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11848        let snapshot = self.snapshot(cx);
11849        let buffer = &snapshot.buffer_snapshot;
11850        let start = buffer.anchor_before(0);
11851        let end = buffer.anchor_after(buffer.len());
11852        let theme = cx.theme().colors();
11853        self.background_highlights_in_range(start..end, &snapshot, theme)
11854    }
11855
11856    #[cfg(feature = "test-support")]
11857    pub fn search_background_highlights(
11858        &mut self,
11859        cx: &mut ViewContext<Self>,
11860    ) -> Vec<Range<Point>> {
11861        let snapshot = self.buffer().read(cx).snapshot(cx);
11862
11863        let highlights = self
11864            .background_highlights
11865            .get(&TypeId::of::<items::BufferSearchHighlights>());
11866
11867        if let Some((_color, ranges)) = highlights {
11868            ranges
11869                .iter()
11870                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11871                .collect_vec()
11872        } else {
11873            vec![]
11874        }
11875    }
11876
11877    fn document_highlights_for_position<'a>(
11878        &'a self,
11879        position: Anchor,
11880        buffer: &'a MultiBufferSnapshot,
11881    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11882        let read_highlights = self
11883            .background_highlights
11884            .get(&TypeId::of::<DocumentHighlightRead>())
11885            .map(|h| &h.1);
11886        let write_highlights = self
11887            .background_highlights
11888            .get(&TypeId::of::<DocumentHighlightWrite>())
11889            .map(|h| &h.1);
11890        let left_position = position.bias_left(buffer);
11891        let right_position = position.bias_right(buffer);
11892        read_highlights
11893            .into_iter()
11894            .chain(write_highlights)
11895            .flat_map(move |ranges| {
11896                let start_ix = match ranges.binary_search_by(|probe| {
11897                    let cmp = probe.end.cmp(&left_position, buffer);
11898                    if cmp.is_ge() {
11899                        Ordering::Greater
11900                    } else {
11901                        Ordering::Less
11902                    }
11903                }) {
11904                    Ok(i) | Err(i) => i,
11905                };
11906
11907                ranges[start_ix..]
11908                    .iter()
11909                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11910            })
11911    }
11912
11913    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11914        self.background_highlights
11915            .get(&TypeId::of::<T>())
11916            .map_or(false, |(_, highlights)| !highlights.is_empty())
11917    }
11918
11919    pub fn background_highlights_in_range(
11920        &self,
11921        search_range: Range<Anchor>,
11922        display_snapshot: &DisplaySnapshot,
11923        theme: &ThemeColors,
11924    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11925        let mut results = Vec::new();
11926        for (color_fetcher, ranges) in self.background_highlights.values() {
11927            let color = color_fetcher(theme);
11928            let start_ix = match ranges.binary_search_by(|probe| {
11929                let cmp = probe
11930                    .end
11931                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11932                if cmp.is_gt() {
11933                    Ordering::Greater
11934                } else {
11935                    Ordering::Less
11936                }
11937            }) {
11938                Ok(i) | Err(i) => i,
11939            };
11940            for range in &ranges[start_ix..] {
11941                if range
11942                    .start
11943                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11944                    .is_ge()
11945                {
11946                    break;
11947                }
11948
11949                let start = range.start.to_display_point(display_snapshot);
11950                let end = range.end.to_display_point(display_snapshot);
11951                results.push((start..end, color))
11952            }
11953        }
11954        results
11955    }
11956
11957    pub fn background_highlight_row_ranges<T: 'static>(
11958        &self,
11959        search_range: Range<Anchor>,
11960        display_snapshot: &DisplaySnapshot,
11961        count: usize,
11962    ) -> Vec<RangeInclusive<DisplayPoint>> {
11963        let mut results = Vec::new();
11964        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11965            return vec![];
11966        };
11967
11968        let start_ix = match ranges.binary_search_by(|probe| {
11969            let cmp = probe
11970                .end
11971                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11972            if cmp.is_gt() {
11973                Ordering::Greater
11974            } else {
11975                Ordering::Less
11976            }
11977        }) {
11978            Ok(i) | Err(i) => i,
11979        };
11980        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11981            if let (Some(start_display), Some(end_display)) = (start, end) {
11982                results.push(
11983                    start_display.to_display_point(display_snapshot)
11984                        ..=end_display.to_display_point(display_snapshot),
11985                );
11986            }
11987        };
11988        let mut start_row: Option<Point> = None;
11989        let mut end_row: Option<Point> = None;
11990        if ranges.len() > count {
11991            return Vec::new();
11992        }
11993        for range in &ranges[start_ix..] {
11994            if range
11995                .start
11996                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11997                .is_ge()
11998            {
11999                break;
12000            }
12001            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12002            if let Some(current_row) = &end_row {
12003                if end.row == current_row.row {
12004                    continue;
12005                }
12006            }
12007            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12008            if start_row.is_none() {
12009                assert_eq!(end_row, None);
12010                start_row = Some(start);
12011                end_row = Some(end);
12012                continue;
12013            }
12014            if let Some(current_end) = end_row.as_mut() {
12015                if start.row > current_end.row + 1 {
12016                    push_region(start_row, end_row);
12017                    start_row = Some(start);
12018                    end_row = Some(end);
12019                } else {
12020                    // Merge two hunks.
12021                    *current_end = end;
12022                }
12023            } else {
12024                unreachable!();
12025            }
12026        }
12027        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12028        push_region(start_row, end_row);
12029        results
12030    }
12031
12032    pub fn gutter_highlights_in_range(
12033        &self,
12034        search_range: Range<Anchor>,
12035        display_snapshot: &DisplaySnapshot,
12036        cx: &AppContext,
12037    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12038        let mut results = Vec::new();
12039        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12040            let color = color_fetcher(cx);
12041            let start_ix = match ranges.binary_search_by(|probe| {
12042                let cmp = probe
12043                    .end
12044                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12045                if cmp.is_gt() {
12046                    Ordering::Greater
12047                } else {
12048                    Ordering::Less
12049                }
12050            }) {
12051                Ok(i) | Err(i) => i,
12052            };
12053            for range in &ranges[start_ix..] {
12054                if range
12055                    .start
12056                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12057                    .is_ge()
12058                {
12059                    break;
12060                }
12061
12062                let start = range.start.to_display_point(display_snapshot);
12063                let end = range.end.to_display_point(display_snapshot);
12064                results.push((start..end, color))
12065            }
12066        }
12067        results
12068    }
12069
12070    /// Get the text ranges corresponding to the redaction query
12071    pub fn redacted_ranges(
12072        &self,
12073        search_range: Range<Anchor>,
12074        display_snapshot: &DisplaySnapshot,
12075        cx: &WindowContext,
12076    ) -> Vec<Range<DisplayPoint>> {
12077        display_snapshot
12078            .buffer_snapshot
12079            .redacted_ranges(search_range, |file| {
12080                if let Some(file) = file {
12081                    file.is_private()
12082                        && EditorSettings::get(
12083                            Some(SettingsLocation {
12084                                worktree_id: file.worktree_id(cx),
12085                                path: file.path().as_ref(),
12086                            }),
12087                            cx,
12088                        )
12089                        .redact_private_values
12090                } else {
12091                    false
12092                }
12093            })
12094            .map(|range| {
12095                range.start.to_display_point(display_snapshot)
12096                    ..range.end.to_display_point(display_snapshot)
12097            })
12098            .collect()
12099    }
12100
12101    pub fn highlight_text<T: 'static>(
12102        &mut self,
12103        ranges: Vec<Range<Anchor>>,
12104        style: HighlightStyle,
12105        cx: &mut ViewContext<Self>,
12106    ) {
12107        self.display_map.update(cx, |map, _| {
12108            map.highlight_text(TypeId::of::<T>(), ranges, style)
12109        });
12110        cx.notify();
12111    }
12112
12113    pub(crate) fn highlight_inlays<T: 'static>(
12114        &mut self,
12115        highlights: Vec<InlayHighlight>,
12116        style: HighlightStyle,
12117        cx: &mut ViewContext<Self>,
12118    ) {
12119        self.display_map.update(cx, |map, _| {
12120            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12121        });
12122        cx.notify();
12123    }
12124
12125    pub fn text_highlights<'a, T: 'static>(
12126        &'a self,
12127        cx: &'a AppContext,
12128    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12129        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12130    }
12131
12132    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12133        let cleared = self
12134            .display_map
12135            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12136        if cleared {
12137            cx.notify();
12138        }
12139    }
12140
12141    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12142        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12143            && self.focus_handle.is_focused(cx)
12144    }
12145
12146    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12147        self.show_cursor_when_unfocused = is_enabled;
12148        cx.notify();
12149    }
12150
12151    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12152        cx.notify();
12153    }
12154
12155    fn on_buffer_event(
12156        &mut self,
12157        multibuffer: Model<MultiBuffer>,
12158        event: &multi_buffer::Event,
12159        cx: &mut ViewContext<Self>,
12160    ) {
12161        match event {
12162            multi_buffer::Event::Edited {
12163                singleton_buffer_edited,
12164            } => {
12165                self.scrollbar_marker_state.dirty = true;
12166                self.active_indent_guides_state.dirty = true;
12167                self.refresh_active_diagnostics(cx);
12168                self.refresh_code_actions(cx);
12169                if self.has_active_inline_completion(cx) {
12170                    self.update_visible_inline_completion(cx);
12171                }
12172                cx.emit(EditorEvent::BufferEdited);
12173                cx.emit(SearchEvent::MatchesInvalidated);
12174                if *singleton_buffer_edited {
12175                    if let Some(project) = &self.project {
12176                        let project = project.read(cx);
12177                        #[allow(clippy::mutable_key_type)]
12178                        let languages_affected = multibuffer
12179                            .read(cx)
12180                            .all_buffers()
12181                            .into_iter()
12182                            .filter_map(|buffer| {
12183                                let buffer = buffer.read(cx);
12184                                let language = buffer.language()?;
12185                                if project.is_local()
12186                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12187                                {
12188                                    None
12189                                } else {
12190                                    Some(language)
12191                                }
12192                            })
12193                            .cloned()
12194                            .collect::<HashSet<_>>();
12195                        if !languages_affected.is_empty() {
12196                            self.refresh_inlay_hints(
12197                                InlayHintRefreshReason::BufferEdited(languages_affected),
12198                                cx,
12199                            );
12200                        }
12201                    }
12202                }
12203
12204                let Some(project) = &self.project else { return };
12205                let (telemetry, is_via_ssh) = {
12206                    let project = project.read(cx);
12207                    let telemetry = project.client().telemetry().clone();
12208                    let is_via_ssh = project.is_via_ssh();
12209                    (telemetry, is_via_ssh)
12210                };
12211                refresh_linked_ranges(self, cx);
12212                telemetry.log_edit_event("editor", is_via_ssh);
12213            }
12214            multi_buffer::Event::ExcerptsAdded {
12215                buffer,
12216                predecessor,
12217                excerpts,
12218            } => {
12219                self.tasks_update_task = Some(self.refresh_runnables(cx));
12220                cx.emit(EditorEvent::ExcerptsAdded {
12221                    buffer: buffer.clone(),
12222                    predecessor: *predecessor,
12223                    excerpts: excerpts.clone(),
12224                });
12225                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12226            }
12227            multi_buffer::Event::ExcerptsRemoved { ids } => {
12228                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12229                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12230            }
12231            multi_buffer::Event::ExcerptsEdited { ids } => {
12232                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12233            }
12234            multi_buffer::Event::ExcerptsExpanded { ids } => {
12235                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12236            }
12237            multi_buffer::Event::Reparsed(buffer_id) => {
12238                self.tasks_update_task = Some(self.refresh_runnables(cx));
12239
12240                cx.emit(EditorEvent::Reparsed(*buffer_id));
12241            }
12242            multi_buffer::Event::LanguageChanged(buffer_id) => {
12243                linked_editing_ranges::refresh_linked_ranges(self, cx);
12244                cx.emit(EditorEvent::Reparsed(*buffer_id));
12245                cx.notify();
12246            }
12247            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12248            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12249            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12250                cx.emit(EditorEvent::TitleChanged)
12251            }
12252            multi_buffer::Event::DiffBaseChanged => {
12253                self.scrollbar_marker_state.dirty = true;
12254                cx.emit(EditorEvent::DiffBaseChanged);
12255                cx.notify();
12256            }
12257            multi_buffer::Event::DiffUpdated { buffer } => {
12258                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12259                cx.notify();
12260            }
12261            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12262            multi_buffer::Event::DiagnosticsUpdated => {
12263                self.refresh_active_diagnostics(cx);
12264                self.scrollbar_marker_state.dirty = true;
12265                cx.notify();
12266            }
12267            _ => {}
12268        };
12269    }
12270
12271    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12272        cx.notify();
12273    }
12274
12275    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12276        self.tasks_update_task = Some(self.refresh_runnables(cx));
12277        self.refresh_inline_completion(true, false, cx);
12278        self.refresh_inlay_hints(
12279            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12280                self.selections.newest_anchor().head(),
12281                &self.buffer.read(cx).snapshot(cx),
12282                cx,
12283            )),
12284            cx,
12285        );
12286
12287        let old_cursor_shape = self.cursor_shape;
12288
12289        {
12290            let editor_settings = EditorSettings::get_global(cx);
12291            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12292            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12293            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12294        }
12295
12296        if old_cursor_shape != self.cursor_shape {
12297            cx.emit(EditorEvent::CursorShapeChanged);
12298        }
12299
12300        let project_settings = ProjectSettings::get_global(cx);
12301        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12302
12303        if self.mode == EditorMode::Full {
12304            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12305            if self.git_blame_inline_enabled != inline_blame_enabled {
12306                self.toggle_git_blame_inline_internal(false, cx);
12307            }
12308        }
12309
12310        cx.notify();
12311    }
12312
12313    pub fn set_searchable(&mut self, searchable: bool) {
12314        self.searchable = searchable;
12315    }
12316
12317    pub fn searchable(&self) -> bool {
12318        self.searchable
12319    }
12320
12321    fn open_proposed_changes_editor(
12322        &mut self,
12323        _: &OpenProposedChangesEditor,
12324        cx: &mut ViewContext<Self>,
12325    ) {
12326        let Some(workspace) = self.workspace() else {
12327            cx.propagate();
12328            return;
12329        };
12330
12331        let buffer = self.buffer.read(cx);
12332        let mut new_selections_by_buffer = HashMap::default();
12333        for selection in self.selections.all::<usize>(cx) {
12334            for (buffer, range, _) in
12335                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12336            {
12337                let mut range = range.to_point(buffer.read(cx));
12338                range.start.column = 0;
12339                range.end.column = buffer.read(cx).line_len(range.end.row);
12340                new_selections_by_buffer
12341                    .entry(buffer)
12342                    .or_insert(Vec::new())
12343                    .push(range)
12344            }
12345        }
12346
12347        let proposed_changes_buffers = new_selections_by_buffer
12348            .into_iter()
12349            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12350            .collect::<Vec<_>>();
12351        let proposed_changes_editor = cx.new_view(|cx| {
12352            ProposedChangesEditor::new(
12353                "Proposed changes",
12354                proposed_changes_buffers,
12355                self.project.clone(),
12356                cx,
12357            )
12358        });
12359
12360        cx.window_context().defer(move |cx| {
12361            workspace.update(cx, |workspace, cx| {
12362                workspace.active_pane().update(cx, |pane, cx| {
12363                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12364                });
12365            });
12366        });
12367    }
12368
12369    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12370        self.open_excerpts_common(true, cx)
12371    }
12372
12373    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12374        self.open_excerpts_common(false, cx)
12375    }
12376
12377    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12378        let buffer = self.buffer.read(cx);
12379        if buffer.is_singleton() {
12380            cx.propagate();
12381            return;
12382        }
12383
12384        let Some(workspace) = self.workspace() else {
12385            cx.propagate();
12386            return;
12387        };
12388
12389        let mut new_selections_by_buffer = HashMap::default();
12390        for selection in self.selections.all::<usize>(cx) {
12391            for (mut buffer_handle, mut range, _) in
12392                buffer.range_to_buffer_ranges(selection.range(), cx)
12393            {
12394                // When editing branch buffers, jump to the corresponding location
12395                // in their base buffer.
12396                let buffer = buffer_handle.read(cx);
12397                if let Some(base_buffer) = buffer.diff_base_buffer() {
12398                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12399                    buffer_handle = base_buffer;
12400                }
12401
12402                if selection.reversed {
12403                    mem::swap(&mut range.start, &mut range.end);
12404                }
12405                new_selections_by_buffer
12406                    .entry(buffer_handle)
12407                    .or_insert(Vec::new())
12408                    .push(range)
12409            }
12410        }
12411
12412        // We defer the pane interaction because we ourselves are a workspace item
12413        // and activating a new item causes the pane to call a method on us reentrantly,
12414        // which panics if we're on the stack.
12415        cx.window_context().defer(move |cx| {
12416            workspace.update(cx, |workspace, cx| {
12417                let pane = if split {
12418                    workspace.adjacent_pane(cx)
12419                } else {
12420                    workspace.active_pane().clone()
12421                };
12422
12423                for (buffer, ranges) in new_selections_by_buffer {
12424                    let editor =
12425                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12426                    editor.update(cx, |editor, cx| {
12427                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12428                            s.select_ranges(ranges);
12429                        });
12430                    });
12431                }
12432            })
12433        });
12434    }
12435
12436    fn jump(
12437        &mut self,
12438        path: ProjectPath,
12439        position: Point,
12440        anchor: language::Anchor,
12441        offset_from_top: u32,
12442        cx: &mut ViewContext<Self>,
12443    ) {
12444        let workspace = self.workspace();
12445        cx.spawn(|_, mut cx| async move {
12446            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12447            let editor = workspace.update(&mut cx, |workspace, cx| {
12448                // Reset the preview item id before opening the new item
12449                workspace.active_pane().update(cx, |pane, cx| {
12450                    pane.set_preview_item_id(None, cx);
12451                });
12452                workspace.open_path_preview(path, None, true, true, cx)
12453            })?;
12454            let editor = editor
12455                .await?
12456                .downcast::<Editor>()
12457                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12458                .downgrade();
12459            editor.update(&mut cx, |editor, cx| {
12460                let buffer = editor
12461                    .buffer()
12462                    .read(cx)
12463                    .as_singleton()
12464                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12465                let buffer = buffer.read(cx);
12466                let cursor = if buffer.can_resolve(&anchor) {
12467                    language::ToPoint::to_point(&anchor, buffer)
12468                } else {
12469                    buffer.clip_point(position, Bias::Left)
12470                };
12471
12472                let nav_history = editor.nav_history.take();
12473                editor.change_selections(
12474                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12475                    cx,
12476                    |s| {
12477                        s.select_ranges([cursor..cursor]);
12478                    },
12479                );
12480                editor.nav_history = nav_history;
12481
12482                anyhow::Ok(())
12483            })??;
12484
12485            anyhow::Ok(())
12486        })
12487        .detach_and_log_err(cx);
12488    }
12489
12490    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12491        let snapshot = self.buffer.read(cx).read(cx);
12492        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12493        Some(
12494            ranges
12495                .iter()
12496                .map(move |range| {
12497                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12498                })
12499                .collect(),
12500        )
12501    }
12502
12503    fn selection_replacement_ranges(
12504        &self,
12505        range: Range<OffsetUtf16>,
12506        cx: &AppContext,
12507    ) -> Vec<Range<OffsetUtf16>> {
12508        let selections = self.selections.all::<OffsetUtf16>(cx);
12509        let newest_selection = selections
12510            .iter()
12511            .max_by_key(|selection| selection.id)
12512            .unwrap();
12513        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12514        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12515        let snapshot = self.buffer.read(cx).read(cx);
12516        selections
12517            .into_iter()
12518            .map(|mut selection| {
12519                selection.start.0 =
12520                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12521                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12522                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12523                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12524            })
12525            .collect()
12526    }
12527
12528    fn report_editor_event(
12529        &self,
12530        operation: &'static str,
12531        file_extension: Option<String>,
12532        cx: &AppContext,
12533    ) {
12534        if cfg!(any(test, feature = "test-support")) {
12535            return;
12536        }
12537
12538        let Some(project) = &self.project else { return };
12539
12540        // If None, we are in a file without an extension
12541        let file = self
12542            .buffer
12543            .read(cx)
12544            .as_singleton()
12545            .and_then(|b| b.read(cx).file());
12546        let file_extension = file_extension.or(file
12547            .as_ref()
12548            .and_then(|file| Path::new(file.file_name(cx)).extension())
12549            .and_then(|e| e.to_str())
12550            .map(|a| a.to_string()));
12551
12552        let vim_mode = cx
12553            .global::<SettingsStore>()
12554            .raw_user_settings()
12555            .get("vim_mode")
12556            == Some(&serde_json::Value::Bool(true));
12557
12558        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12559            == language::language_settings::InlineCompletionProvider::Copilot;
12560        let copilot_enabled_for_language = self
12561            .buffer
12562            .read(cx)
12563            .settings_at(0, cx)
12564            .show_inline_completions;
12565
12566        let project = project.read(cx);
12567        let telemetry = project.client().telemetry().clone();
12568        telemetry.report_editor_event(
12569            file_extension,
12570            vim_mode,
12571            operation,
12572            copilot_enabled,
12573            copilot_enabled_for_language,
12574            project.is_via_ssh(),
12575        )
12576    }
12577
12578    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12579    /// with each line being an array of {text, highlight} objects.
12580    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12581        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12582            return;
12583        };
12584
12585        #[derive(Serialize)]
12586        struct Chunk<'a> {
12587            text: String,
12588            highlight: Option<&'a str>,
12589        }
12590
12591        let snapshot = buffer.read(cx).snapshot();
12592        let range = self
12593            .selected_text_range(false, cx)
12594            .and_then(|selection| {
12595                if selection.range.is_empty() {
12596                    None
12597                } else {
12598                    Some(selection.range)
12599                }
12600            })
12601            .unwrap_or_else(|| 0..snapshot.len());
12602
12603        let chunks = snapshot.chunks(range, true);
12604        let mut lines = Vec::new();
12605        let mut line: VecDeque<Chunk> = VecDeque::new();
12606
12607        let Some(style) = self.style.as_ref() else {
12608            return;
12609        };
12610
12611        for chunk in chunks {
12612            let highlight = chunk
12613                .syntax_highlight_id
12614                .and_then(|id| id.name(&style.syntax));
12615            let mut chunk_lines = chunk.text.split('\n').peekable();
12616            while let Some(text) = chunk_lines.next() {
12617                let mut merged_with_last_token = false;
12618                if let Some(last_token) = line.back_mut() {
12619                    if last_token.highlight == highlight {
12620                        last_token.text.push_str(text);
12621                        merged_with_last_token = true;
12622                    }
12623                }
12624
12625                if !merged_with_last_token {
12626                    line.push_back(Chunk {
12627                        text: text.into(),
12628                        highlight,
12629                    });
12630                }
12631
12632                if chunk_lines.peek().is_some() {
12633                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12634                        line.pop_front();
12635                    }
12636                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12637                        line.pop_back();
12638                    }
12639
12640                    lines.push(mem::take(&mut line));
12641                }
12642            }
12643        }
12644
12645        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12646            return;
12647        };
12648        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12649    }
12650
12651    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12652        &self.inlay_hint_cache
12653    }
12654
12655    pub fn replay_insert_event(
12656        &mut self,
12657        text: &str,
12658        relative_utf16_range: Option<Range<isize>>,
12659        cx: &mut ViewContext<Self>,
12660    ) {
12661        if !self.input_enabled {
12662            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12663            return;
12664        }
12665        if let Some(relative_utf16_range) = relative_utf16_range {
12666            let selections = self.selections.all::<OffsetUtf16>(cx);
12667            self.change_selections(None, cx, |s| {
12668                let new_ranges = selections.into_iter().map(|range| {
12669                    let start = OffsetUtf16(
12670                        range
12671                            .head()
12672                            .0
12673                            .saturating_add_signed(relative_utf16_range.start),
12674                    );
12675                    let end = OffsetUtf16(
12676                        range
12677                            .head()
12678                            .0
12679                            .saturating_add_signed(relative_utf16_range.end),
12680                    );
12681                    start..end
12682                });
12683                s.select_ranges(new_ranges);
12684            });
12685        }
12686
12687        self.handle_input(text, cx);
12688    }
12689
12690    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12691        let Some(provider) = self.semantics_provider.as_ref() else {
12692            return false;
12693        };
12694
12695        let mut supports = false;
12696        self.buffer().read(cx).for_each_buffer(|buffer| {
12697            supports |= provider.supports_inlay_hints(buffer, cx);
12698        });
12699        supports
12700    }
12701
12702    pub fn focus(&self, cx: &mut WindowContext) {
12703        cx.focus(&self.focus_handle)
12704    }
12705
12706    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12707        self.focus_handle.is_focused(cx)
12708    }
12709
12710    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12711        cx.emit(EditorEvent::Focused);
12712
12713        if let Some(descendant) = self
12714            .last_focused_descendant
12715            .take()
12716            .and_then(|descendant| descendant.upgrade())
12717        {
12718            cx.focus(&descendant);
12719        } else {
12720            if let Some(blame) = self.blame.as_ref() {
12721                blame.update(cx, GitBlame::focus)
12722            }
12723
12724            self.blink_manager.update(cx, BlinkManager::enable);
12725            self.show_cursor_names(cx);
12726            self.buffer.update(cx, |buffer, cx| {
12727                buffer.finalize_last_transaction(cx);
12728                if self.leader_peer_id.is_none() {
12729                    buffer.set_active_selections(
12730                        &self.selections.disjoint_anchors(),
12731                        self.selections.line_mode,
12732                        self.cursor_shape,
12733                        cx,
12734                    );
12735                }
12736            });
12737        }
12738    }
12739
12740    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12741        cx.emit(EditorEvent::FocusedIn)
12742    }
12743
12744    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12745        if event.blurred != self.focus_handle {
12746            self.last_focused_descendant = Some(event.blurred);
12747        }
12748    }
12749
12750    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12751        self.blink_manager.update(cx, BlinkManager::disable);
12752        self.buffer
12753            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12754
12755        if let Some(blame) = self.blame.as_ref() {
12756            blame.update(cx, GitBlame::blur)
12757        }
12758        if !self.hover_state.focused(cx) {
12759            hide_hover(self, cx);
12760        }
12761
12762        self.hide_context_menu(cx);
12763        cx.emit(EditorEvent::Blurred);
12764        cx.notify();
12765    }
12766
12767    pub fn register_action<A: Action>(
12768        &mut self,
12769        listener: impl Fn(&A, &mut WindowContext) + 'static,
12770    ) -> Subscription {
12771        let id = self.next_editor_action_id.post_inc();
12772        let listener = Arc::new(listener);
12773        self.editor_actions.borrow_mut().insert(
12774            id,
12775            Box::new(move |cx| {
12776                let cx = cx.window_context();
12777                let listener = listener.clone();
12778                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12779                    let action = action.downcast_ref().unwrap();
12780                    if phase == DispatchPhase::Bubble {
12781                        listener(action, cx)
12782                    }
12783                })
12784            }),
12785        );
12786
12787        let editor_actions = self.editor_actions.clone();
12788        Subscription::new(move || {
12789            editor_actions.borrow_mut().remove(&id);
12790        })
12791    }
12792
12793    pub fn file_header_size(&self) -> u32 {
12794        FILE_HEADER_HEIGHT
12795    }
12796
12797    pub fn revert(
12798        &mut self,
12799        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12800        cx: &mut ViewContext<Self>,
12801    ) {
12802        self.buffer().update(cx, |multi_buffer, cx| {
12803            for (buffer_id, changes) in revert_changes {
12804                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12805                    buffer.update(cx, |buffer, cx| {
12806                        buffer.edit(
12807                            changes.into_iter().map(|(range, text)| {
12808                                (range, text.to_string().map(Arc::<str>::from))
12809                            }),
12810                            None,
12811                            cx,
12812                        );
12813                    });
12814                }
12815            }
12816        });
12817        self.change_selections(None, cx, |selections| selections.refresh());
12818    }
12819
12820    pub fn to_pixel_point(
12821        &mut self,
12822        source: multi_buffer::Anchor,
12823        editor_snapshot: &EditorSnapshot,
12824        cx: &mut ViewContext<Self>,
12825    ) -> Option<gpui::Point<Pixels>> {
12826        let source_point = source.to_display_point(editor_snapshot);
12827        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12828    }
12829
12830    pub fn display_to_pixel_point(
12831        &mut self,
12832        source: DisplayPoint,
12833        editor_snapshot: &EditorSnapshot,
12834        cx: &mut ViewContext<Self>,
12835    ) -> Option<gpui::Point<Pixels>> {
12836        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12837        let text_layout_details = self.text_layout_details(cx);
12838        let scroll_top = text_layout_details
12839            .scroll_anchor
12840            .scroll_position(editor_snapshot)
12841            .y;
12842
12843        if source.row().as_f32() < scroll_top.floor() {
12844            return None;
12845        }
12846        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12847        let source_y = line_height * (source.row().as_f32() - scroll_top);
12848        Some(gpui::Point::new(source_x, source_y))
12849    }
12850
12851    pub fn has_active_completions_menu(&self) -> bool {
12852        self.context_menu.read().as_ref().map_or(false, |menu| {
12853            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12854        })
12855    }
12856
12857    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12858        self.addons
12859            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12860    }
12861
12862    pub fn unregister_addon<T: Addon>(&mut self) {
12863        self.addons.remove(&std::any::TypeId::of::<T>());
12864    }
12865
12866    pub fn addon<T: Addon>(&self) -> Option<&T> {
12867        let type_id = std::any::TypeId::of::<T>();
12868        self.addons
12869            .get(&type_id)
12870            .and_then(|item| item.to_any().downcast_ref::<T>())
12871    }
12872}
12873
12874fn hunks_for_selections(
12875    multi_buffer_snapshot: &MultiBufferSnapshot,
12876    selections: &[Selection<Anchor>],
12877) -> Vec<MultiBufferDiffHunk> {
12878    let buffer_rows_for_selections = selections.iter().map(|selection| {
12879        let head = selection.head();
12880        let tail = selection.tail();
12881        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12882        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12883        if start > end {
12884            end..start
12885        } else {
12886            start..end
12887        }
12888    });
12889
12890    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12891}
12892
12893pub fn hunks_for_rows(
12894    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12895    multi_buffer_snapshot: &MultiBufferSnapshot,
12896) -> Vec<MultiBufferDiffHunk> {
12897    let mut hunks = Vec::new();
12898    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12899        HashMap::default();
12900    for selected_multi_buffer_rows in rows {
12901        let query_rows =
12902            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12903        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12904            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12905            // when the caret is just above or just below the deleted hunk.
12906            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12907            let related_to_selection = if allow_adjacent {
12908                hunk.row_range.overlaps(&query_rows)
12909                    || hunk.row_range.start == query_rows.end
12910                    || hunk.row_range.end == query_rows.start
12911            } else {
12912                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12913                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12914                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12915                    || selected_multi_buffer_rows.end == hunk.row_range.start
12916            };
12917            if related_to_selection {
12918                if !processed_buffer_rows
12919                    .entry(hunk.buffer_id)
12920                    .or_default()
12921                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12922                {
12923                    continue;
12924                }
12925                hunks.push(hunk);
12926            }
12927        }
12928    }
12929
12930    hunks
12931}
12932
12933pub trait CollaborationHub {
12934    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12935    fn user_participant_indices<'a>(
12936        &self,
12937        cx: &'a AppContext,
12938    ) -> &'a HashMap<u64, ParticipantIndex>;
12939    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12940}
12941
12942impl CollaborationHub for Model<Project> {
12943    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12944        self.read(cx).collaborators()
12945    }
12946
12947    fn user_participant_indices<'a>(
12948        &self,
12949        cx: &'a AppContext,
12950    ) -> &'a HashMap<u64, ParticipantIndex> {
12951        self.read(cx).user_store().read(cx).participant_indices()
12952    }
12953
12954    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12955        let this = self.read(cx);
12956        let user_ids = this.collaborators().values().map(|c| c.user_id);
12957        this.user_store().read_with(cx, |user_store, cx| {
12958            user_store.participant_names(user_ids, cx)
12959        })
12960    }
12961}
12962
12963pub trait SemanticsProvider {
12964    fn hover(
12965        &self,
12966        buffer: &Model<Buffer>,
12967        position: text::Anchor,
12968        cx: &mut AppContext,
12969    ) -> Option<Task<Vec<project::Hover>>>;
12970
12971    fn inlay_hints(
12972        &self,
12973        buffer_handle: Model<Buffer>,
12974        range: Range<text::Anchor>,
12975        cx: &mut AppContext,
12976    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12977
12978    fn resolve_inlay_hint(
12979        &self,
12980        hint: InlayHint,
12981        buffer_handle: Model<Buffer>,
12982        server_id: LanguageServerId,
12983        cx: &mut AppContext,
12984    ) -> Option<Task<anyhow::Result<InlayHint>>>;
12985
12986    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
12987
12988    fn document_highlights(
12989        &self,
12990        buffer: &Model<Buffer>,
12991        position: text::Anchor,
12992        cx: &mut AppContext,
12993    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
12994
12995    fn definitions(
12996        &self,
12997        buffer: &Model<Buffer>,
12998        position: text::Anchor,
12999        kind: GotoDefinitionKind,
13000        cx: &mut AppContext,
13001    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13002
13003    fn range_for_rename(
13004        &self,
13005        buffer: &Model<Buffer>,
13006        position: text::Anchor,
13007        cx: &mut AppContext,
13008    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13009
13010    fn perform_rename(
13011        &self,
13012        buffer: &Model<Buffer>,
13013        position: text::Anchor,
13014        new_name: String,
13015        cx: &mut AppContext,
13016    ) -> Option<Task<Result<ProjectTransaction>>>;
13017}
13018
13019pub trait CompletionProvider {
13020    fn completions(
13021        &self,
13022        buffer: &Model<Buffer>,
13023        buffer_position: text::Anchor,
13024        trigger: CompletionContext,
13025        cx: &mut ViewContext<Editor>,
13026    ) -> Task<Result<Vec<Completion>>>;
13027
13028    fn resolve_completions(
13029        &self,
13030        buffer: Model<Buffer>,
13031        completion_indices: Vec<usize>,
13032        completions: Arc<RwLock<Box<[Completion]>>>,
13033        cx: &mut ViewContext<Editor>,
13034    ) -> Task<Result<bool>>;
13035
13036    fn apply_additional_edits_for_completion(
13037        &self,
13038        buffer: Model<Buffer>,
13039        completion: Completion,
13040        push_to_history: bool,
13041        cx: &mut ViewContext<Editor>,
13042    ) -> Task<Result<Option<language::Transaction>>>;
13043
13044    fn is_completion_trigger(
13045        &self,
13046        buffer: &Model<Buffer>,
13047        position: language::Anchor,
13048        text: &str,
13049        trigger_in_words: bool,
13050        cx: &mut ViewContext<Editor>,
13051    ) -> bool;
13052
13053    fn sort_completions(&self) -> bool {
13054        true
13055    }
13056}
13057
13058pub trait CodeActionProvider {
13059    fn code_actions(
13060        &self,
13061        buffer: &Model<Buffer>,
13062        range: Range<text::Anchor>,
13063        cx: &mut WindowContext,
13064    ) -> Task<Result<Vec<CodeAction>>>;
13065
13066    fn apply_code_action(
13067        &self,
13068        buffer_handle: Model<Buffer>,
13069        action: CodeAction,
13070        excerpt_id: ExcerptId,
13071        push_to_history: bool,
13072        cx: &mut WindowContext,
13073    ) -> Task<Result<ProjectTransaction>>;
13074}
13075
13076impl CodeActionProvider for Model<Project> {
13077    fn code_actions(
13078        &self,
13079        buffer: &Model<Buffer>,
13080        range: Range<text::Anchor>,
13081        cx: &mut WindowContext,
13082    ) -> Task<Result<Vec<CodeAction>>> {
13083        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13084    }
13085
13086    fn apply_code_action(
13087        &self,
13088        buffer_handle: Model<Buffer>,
13089        action: CodeAction,
13090        _excerpt_id: ExcerptId,
13091        push_to_history: bool,
13092        cx: &mut WindowContext,
13093    ) -> Task<Result<ProjectTransaction>> {
13094        self.update(cx, |project, cx| {
13095            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13096        })
13097    }
13098}
13099
13100fn snippet_completions(
13101    project: &Project,
13102    buffer: &Model<Buffer>,
13103    buffer_position: text::Anchor,
13104    cx: &mut AppContext,
13105) -> Vec<Completion> {
13106    let language = buffer.read(cx).language_at(buffer_position);
13107    let language_name = language.as_ref().map(|language| language.lsp_id());
13108    let snippet_store = project.snippets().read(cx);
13109    let snippets = snippet_store.snippets_for(language_name, cx);
13110
13111    if snippets.is_empty() {
13112        return vec![];
13113    }
13114    let snapshot = buffer.read(cx).text_snapshot();
13115    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13116
13117    let scope = language.map(|language| language.default_scope());
13118    let classifier = CharClassifier::new(scope).for_completion(true);
13119    let mut last_word = chars
13120        .take_while(|c| classifier.is_word(*c))
13121        .collect::<String>();
13122    last_word = last_word.chars().rev().collect();
13123    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13124    let to_lsp = |point: &text::Anchor| {
13125        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13126        point_to_lsp(end)
13127    };
13128    let lsp_end = to_lsp(&buffer_position);
13129    snippets
13130        .into_iter()
13131        .filter_map(|snippet| {
13132            let matching_prefix = snippet
13133                .prefix
13134                .iter()
13135                .find(|prefix| prefix.starts_with(&last_word))?;
13136            let start = as_offset - last_word.len();
13137            let start = snapshot.anchor_before(start);
13138            let range = start..buffer_position;
13139            let lsp_start = to_lsp(&start);
13140            let lsp_range = lsp::Range {
13141                start: lsp_start,
13142                end: lsp_end,
13143            };
13144            Some(Completion {
13145                old_range: range,
13146                new_text: snippet.body.clone(),
13147                label: CodeLabel {
13148                    text: matching_prefix.clone(),
13149                    runs: vec![],
13150                    filter_range: 0..matching_prefix.len(),
13151                },
13152                server_id: LanguageServerId(usize::MAX),
13153                documentation: snippet.description.clone().map(Documentation::SingleLine),
13154                lsp_completion: lsp::CompletionItem {
13155                    label: snippet.prefix.first().unwrap().clone(),
13156                    kind: Some(CompletionItemKind::SNIPPET),
13157                    label_details: snippet.description.as_ref().map(|description| {
13158                        lsp::CompletionItemLabelDetails {
13159                            detail: Some(description.clone()),
13160                            description: None,
13161                        }
13162                    }),
13163                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13164                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13165                        lsp::InsertReplaceEdit {
13166                            new_text: snippet.body.clone(),
13167                            insert: lsp_range,
13168                            replace: lsp_range,
13169                        },
13170                    )),
13171                    filter_text: Some(snippet.body.clone()),
13172                    sort_text: Some(char::MAX.to_string()),
13173                    ..Default::default()
13174                },
13175                confirm: None,
13176            })
13177        })
13178        .collect()
13179}
13180
13181impl CompletionProvider for Model<Project> {
13182    fn completions(
13183        &self,
13184        buffer: &Model<Buffer>,
13185        buffer_position: text::Anchor,
13186        options: CompletionContext,
13187        cx: &mut ViewContext<Editor>,
13188    ) -> Task<Result<Vec<Completion>>> {
13189        self.update(cx, |project, cx| {
13190            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13191            let project_completions = project.completions(buffer, buffer_position, options, cx);
13192            cx.background_executor().spawn(async move {
13193                let mut completions = project_completions.await?;
13194                //let snippets = snippets.into_iter().;
13195                completions.extend(snippets);
13196                Ok(completions)
13197            })
13198        })
13199    }
13200
13201    fn resolve_completions(
13202        &self,
13203        buffer: Model<Buffer>,
13204        completion_indices: Vec<usize>,
13205        completions: Arc<RwLock<Box<[Completion]>>>,
13206        cx: &mut ViewContext<Editor>,
13207    ) -> Task<Result<bool>> {
13208        self.update(cx, |project, cx| {
13209            project.resolve_completions(buffer, completion_indices, completions, cx)
13210        })
13211    }
13212
13213    fn apply_additional_edits_for_completion(
13214        &self,
13215        buffer: Model<Buffer>,
13216        completion: Completion,
13217        push_to_history: bool,
13218        cx: &mut ViewContext<Editor>,
13219    ) -> Task<Result<Option<language::Transaction>>> {
13220        self.update(cx, |project, cx| {
13221            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13222        })
13223    }
13224
13225    fn is_completion_trigger(
13226        &self,
13227        buffer: &Model<Buffer>,
13228        position: language::Anchor,
13229        text: &str,
13230        trigger_in_words: bool,
13231        cx: &mut ViewContext<Editor>,
13232    ) -> bool {
13233        if !EditorSettings::get_global(cx).show_completions_on_input {
13234            return false;
13235        }
13236
13237        let mut chars = text.chars();
13238        let char = if let Some(char) = chars.next() {
13239            char
13240        } else {
13241            return false;
13242        };
13243        if chars.next().is_some() {
13244            return false;
13245        }
13246
13247        let buffer = buffer.read(cx);
13248        let classifier = buffer
13249            .snapshot()
13250            .char_classifier_at(position)
13251            .for_completion(true);
13252        if trigger_in_words && classifier.is_word(char) {
13253            return true;
13254        }
13255
13256        buffer
13257            .completion_triggers()
13258            .iter()
13259            .any(|string| string == text)
13260    }
13261}
13262
13263impl SemanticsProvider for Model<Project> {
13264    fn hover(
13265        &self,
13266        buffer: &Model<Buffer>,
13267        position: text::Anchor,
13268        cx: &mut AppContext,
13269    ) -> Option<Task<Vec<project::Hover>>> {
13270        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13271    }
13272
13273    fn document_highlights(
13274        &self,
13275        buffer: &Model<Buffer>,
13276        position: text::Anchor,
13277        cx: &mut AppContext,
13278    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13279        Some(self.update(cx, |project, cx| {
13280            project.document_highlights(buffer, position, cx)
13281        }))
13282    }
13283
13284    fn definitions(
13285        &self,
13286        buffer: &Model<Buffer>,
13287        position: text::Anchor,
13288        kind: GotoDefinitionKind,
13289        cx: &mut AppContext,
13290    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13291        Some(self.update(cx, |project, cx| match kind {
13292            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13293            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13294            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13295            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13296        }))
13297    }
13298
13299    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13300        // TODO: make this work for remote projects
13301        self.read(cx)
13302            .language_servers_for_buffer(buffer.read(cx), cx)
13303            .any(
13304                |(_, server)| match server.capabilities().inlay_hint_provider {
13305                    Some(lsp::OneOf::Left(enabled)) => enabled,
13306                    Some(lsp::OneOf::Right(_)) => true,
13307                    None => false,
13308                },
13309            )
13310    }
13311
13312    fn inlay_hints(
13313        &self,
13314        buffer_handle: Model<Buffer>,
13315        range: Range<text::Anchor>,
13316        cx: &mut AppContext,
13317    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13318        Some(self.update(cx, |project, cx| {
13319            project.inlay_hints(buffer_handle, range, cx)
13320        }))
13321    }
13322
13323    fn resolve_inlay_hint(
13324        &self,
13325        hint: InlayHint,
13326        buffer_handle: Model<Buffer>,
13327        server_id: LanguageServerId,
13328        cx: &mut AppContext,
13329    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13330        Some(self.update(cx, |project, cx| {
13331            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13332        }))
13333    }
13334
13335    fn range_for_rename(
13336        &self,
13337        buffer: &Model<Buffer>,
13338        position: text::Anchor,
13339        cx: &mut AppContext,
13340    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13341        Some(self.update(cx, |project, cx| {
13342            project.prepare_rename(buffer.clone(), position, cx)
13343        }))
13344    }
13345
13346    fn perform_rename(
13347        &self,
13348        buffer: &Model<Buffer>,
13349        position: text::Anchor,
13350        new_name: String,
13351        cx: &mut AppContext,
13352    ) -> Option<Task<Result<ProjectTransaction>>> {
13353        Some(self.update(cx, |project, cx| {
13354            project.perform_rename(buffer.clone(), position, new_name, cx)
13355        }))
13356    }
13357}
13358
13359fn inlay_hint_settings(
13360    location: Anchor,
13361    snapshot: &MultiBufferSnapshot,
13362    cx: &mut ViewContext<'_, Editor>,
13363) -> InlayHintSettings {
13364    let file = snapshot.file_at(location);
13365    let language = snapshot.language_at(location).map(|l| l.name());
13366    language_settings(language, file, cx).inlay_hints
13367}
13368
13369fn consume_contiguous_rows(
13370    contiguous_row_selections: &mut Vec<Selection<Point>>,
13371    selection: &Selection<Point>,
13372    display_map: &DisplaySnapshot,
13373    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13374) -> (MultiBufferRow, MultiBufferRow) {
13375    contiguous_row_selections.push(selection.clone());
13376    let start_row = MultiBufferRow(selection.start.row);
13377    let mut end_row = ending_row(selection, display_map);
13378
13379    while let Some(next_selection) = selections.peek() {
13380        if next_selection.start.row <= end_row.0 {
13381            end_row = ending_row(next_selection, display_map);
13382            contiguous_row_selections.push(selections.next().unwrap().clone());
13383        } else {
13384            break;
13385        }
13386    }
13387    (start_row, end_row)
13388}
13389
13390fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13391    if next_selection.end.column > 0 || next_selection.is_empty() {
13392        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13393    } else {
13394        MultiBufferRow(next_selection.end.row)
13395    }
13396}
13397
13398impl EditorSnapshot {
13399    pub fn remote_selections_in_range<'a>(
13400        &'a self,
13401        range: &'a Range<Anchor>,
13402        collaboration_hub: &dyn CollaborationHub,
13403        cx: &'a AppContext,
13404    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13405        let participant_names = collaboration_hub.user_names(cx);
13406        let participant_indices = collaboration_hub.user_participant_indices(cx);
13407        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13408        let collaborators_by_replica_id = collaborators_by_peer_id
13409            .iter()
13410            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13411            .collect::<HashMap<_, _>>();
13412        self.buffer_snapshot
13413            .selections_in_range(range, false)
13414            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13415                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13416                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13417                let user_name = participant_names.get(&collaborator.user_id).cloned();
13418                Some(RemoteSelection {
13419                    replica_id,
13420                    selection,
13421                    cursor_shape,
13422                    line_mode,
13423                    participant_index,
13424                    peer_id: collaborator.peer_id,
13425                    user_name,
13426                })
13427            })
13428    }
13429
13430    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13431        self.display_snapshot.buffer_snapshot.language_at(position)
13432    }
13433
13434    pub fn is_focused(&self) -> bool {
13435        self.is_focused
13436    }
13437
13438    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13439        self.placeholder_text.as_ref()
13440    }
13441
13442    pub fn scroll_position(&self) -> gpui::Point<f32> {
13443        self.scroll_anchor.scroll_position(&self.display_snapshot)
13444    }
13445
13446    fn gutter_dimensions(
13447        &self,
13448        font_id: FontId,
13449        font_size: Pixels,
13450        em_width: Pixels,
13451        em_advance: Pixels,
13452        max_line_number_width: Pixels,
13453        cx: &AppContext,
13454    ) -> GutterDimensions {
13455        if !self.show_gutter {
13456            return GutterDimensions::default();
13457        }
13458        let descent = cx.text_system().descent(font_id, font_size);
13459
13460        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13461            matches!(
13462                ProjectSettings::get_global(cx).git.git_gutter,
13463                Some(GitGutterSetting::TrackedFiles)
13464            )
13465        });
13466        let gutter_settings = EditorSettings::get_global(cx).gutter;
13467        let show_line_numbers = self
13468            .show_line_numbers
13469            .unwrap_or(gutter_settings.line_numbers);
13470        let line_gutter_width = if show_line_numbers {
13471            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13472            let min_width_for_number_on_gutter = em_advance * 4.0;
13473            max_line_number_width.max(min_width_for_number_on_gutter)
13474        } else {
13475            0.0.into()
13476        };
13477
13478        let show_code_actions = self
13479            .show_code_actions
13480            .unwrap_or(gutter_settings.code_actions);
13481
13482        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13483
13484        let git_blame_entries_width =
13485            self.git_blame_gutter_max_author_length
13486                .map(|max_author_length| {
13487                    // Length of the author name, but also space for the commit hash,
13488                    // the spacing and the timestamp.
13489                    let max_char_count = max_author_length
13490                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13491                        + 7 // length of commit sha
13492                        + 14 // length of max relative timestamp ("60 minutes ago")
13493                        + 4; // gaps and margins
13494
13495                    em_advance * max_char_count
13496                });
13497
13498        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13499        left_padding += if show_code_actions || show_runnables {
13500            em_width * 3.0
13501        } else if show_git_gutter && show_line_numbers {
13502            em_width * 2.0
13503        } else if show_git_gutter || show_line_numbers {
13504            em_width
13505        } else {
13506            px(0.)
13507        };
13508
13509        let right_padding = if gutter_settings.folds && show_line_numbers {
13510            em_width * 4.0
13511        } else if gutter_settings.folds {
13512            em_width * 3.0
13513        } else if show_line_numbers {
13514            em_width
13515        } else {
13516            px(0.)
13517        };
13518
13519        GutterDimensions {
13520            left_padding,
13521            right_padding,
13522            width: line_gutter_width + left_padding + right_padding,
13523            margin: -descent,
13524            git_blame_entries_width,
13525        }
13526    }
13527
13528    pub fn render_fold_toggle(
13529        &self,
13530        buffer_row: MultiBufferRow,
13531        row_contains_cursor: bool,
13532        editor: View<Editor>,
13533        cx: &mut WindowContext,
13534    ) -> Option<AnyElement> {
13535        let folded = self.is_line_folded(buffer_row);
13536
13537        if let Some(crease) = self
13538            .crease_snapshot
13539            .query_row(buffer_row, &self.buffer_snapshot)
13540        {
13541            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13542                if folded {
13543                    editor.update(cx, |editor, cx| {
13544                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13545                    });
13546                } else {
13547                    editor.update(cx, |editor, cx| {
13548                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13549                    });
13550                }
13551            });
13552
13553            Some((crease.render_toggle)(
13554                buffer_row,
13555                folded,
13556                toggle_callback,
13557                cx,
13558            ))
13559        } else if folded
13560            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13561        {
13562            Some(
13563                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13564                    .selected(folded)
13565                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13566                        if folded {
13567                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13568                        } else {
13569                            this.fold_at(&FoldAt { buffer_row }, cx);
13570                        }
13571                    }))
13572                    .into_any_element(),
13573            )
13574        } else {
13575            None
13576        }
13577    }
13578
13579    pub fn render_crease_trailer(
13580        &self,
13581        buffer_row: MultiBufferRow,
13582        cx: &mut WindowContext,
13583    ) -> Option<AnyElement> {
13584        let folded = self.is_line_folded(buffer_row);
13585        let crease = self
13586            .crease_snapshot
13587            .query_row(buffer_row, &self.buffer_snapshot)?;
13588        Some((crease.render_trailer)(buffer_row, folded, cx))
13589    }
13590}
13591
13592impl Deref for EditorSnapshot {
13593    type Target = DisplaySnapshot;
13594
13595    fn deref(&self) -> &Self::Target {
13596        &self.display_snapshot
13597    }
13598}
13599
13600#[derive(Clone, Debug, PartialEq, Eq)]
13601pub enum EditorEvent {
13602    InputIgnored {
13603        text: Arc<str>,
13604    },
13605    InputHandled {
13606        utf16_range_to_replace: Option<Range<isize>>,
13607        text: Arc<str>,
13608    },
13609    ExcerptsAdded {
13610        buffer: Model<Buffer>,
13611        predecessor: ExcerptId,
13612        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13613    },
13614    ExcerptsRemoved {
13615        ids: Vec<ExcerptId>,
13616    },
13617    ExcerptsEdited {
13618        ids: Vec<ExcerptId>,
13619    },
13620    ExcerptsExpanded {
13621        ids: Vec<ExcerptId>,
13622    },
13623    BufferEdited,
13624    Edited {
13625        transaction_id: clock::Lamport,
13626    },
13627    Reparsed(BufferId),
13628    Focused,
13629    FocusedIn,
13630    Blurred,
13631    DirtyChanged,
13632    Saved,
13633    TitleChanged,
13634    DiffBaseChanged,
13635    SelectionsChanged {
13636        local: bool,
13637    },
13638    ScrollPositionChanged {
13639        local: bool,
13640        autoscroll: bool,
13641    },
13642    Closed,
13643    TransactionUndone {
13644        transaction_id: clock::Lamport,
13645    },
13646    TransactionBegun {
13647        transaction_id: clock::Lamport,
13648    },
13649    Reloaded,
13650    CursorShapeChanged,
13651}
13652
13653impl EventEmitter<EditorEvent> for Editor {}
13654
13655impl FocusableView for Editor {
13656    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13657        self.focus_handle.clone()
13658    }
13659}
13660
13661impl Render for Editor {
13662    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13663        let settings = ThemeSettings::get_global(cx);
13664
13665        let mut text_style = match self.mode {
13666            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13667                color: cx.theme().colors().editor_foreground,
13668                font_family: settings.ui_font.family.clone(),
13669                font_features: settings.ui_font.features.clone(),
13670                font_fallbacks: settings.ui_font.fallbacks.clone(),
13671                font_size: rems(0.875).into(),
13672                font_weight: settings.ui_font.weight,
13673                line_height: relative(settings.buffer_line_height.value()),
13674                ..Default::default()
13675            },
13676            EditorMode::Full => TextStyle {
13677                color: cx.theme().colors().editor_foreground,
13678                font_family: settings.buffer_font.family.clone(),
13679                font_features: settings.buffer_font.features.clone(),
13680                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13681                font_size: settings.buffer_font_size(cx).into(),
13682                font_weight: settings.buffer_font.weight,
13683                line_height: relative(settings.buffer_line_height.value()),
13684                ..Default::default()
13685            },
13686        };
13687        if let Some(text_style_refinement) = &self.text_style_refinement {
13688            text_style.refine(text_style_refinement)
13689        }
13690
13691        let background = match self.mode {
13692            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13693            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13694            EditorMode::Full => cx.theme().colors().editor_background,
13695        };
13696
13697        EditorElement::new(
13698            cx.view(),
13699            EditorStyle {
13700                background,
13701                local_player: cx.theme().players().local(),
13702                text: text_style,
13703                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13704                syntax: cx.theme().syntax().clone(),
13705                status: cx.theme().status().clone(),
13706                inlay_hints_style: make_inlay_hints_style(cx),
13707                suggestions_style: HighlightStyle {
13708                    color: Some(cx.theme().status().predictive),
13709                    ..HighlightStyle::default()
13710                },
13711                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13712            },
13713        )
13714    }
13715}
13716
13717impl ViewInputHandler for Editor {
13718    fn text_for_range(
13719        &mut self,
13720        range_utf16: Range<usize>,
13721        cx: &mut ViewContext<Self>,
13722    ) -> Option<String> {
13723        Some(
13724            self.buffer
13725                .read(cx)
13726                .read(cx)
13727                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13728                .collect(),
13729        )
13730    }
13731
13732    fn selected_text_range(
13733        &mut self,
13734        ignore_disabled_input: bool,
13735        cx: &mut ViewContext<Self>,
13736    ) -> Option<UTF16Selection> {
13737        // Prevent the IME menu from appearing when holding down an alphabetic key
13738        // while input is disabled.
13739        if !ignore_disabled_input && !self.input_enabled {
13740            return None;
13741        }
13742
13743        let selection = self.selections.newest::<OffsetUtf16>(cx);
13744        let range = selection.range();
13745
13746        Some(UTF16Selection {
13747            range: range.start.0..range.end.0,
13748            reversed: selection.reversed,
13749        })
13750    }
13751
13752    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13753        let snapshot = self.buffer.read(cx).read(cx);
13754        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13755        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13756    }
13757
13758    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13759        self.clear_highlights::<InputComposition>(cx);
13760        self.ime_transaction.take();
13761    }
13762
13763    fn replace_text_in_range(
13764        &mut self,
13765        range_utf16: Option<Range<usize>>,
13766        text: &str,
13767        cx: &mut ViewContext<Self>,
13768    ) {
13769        if !self.input_enabled {
13770            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13771            return;
13772        }
13773
13774        self.transact(cx, |this, cx| {
13775            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13776                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13777                Some(this.selection_replacement_ranges(range_utf16, cx))
13778            } else {
13779                this.marked_text_ranges(cx)
13780            };
13781
13782            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13783                let newest_selection_id = this.selections.newest_anchor().id;
13784                this.selections
13785                    .all::<OffsetUtf16>(cx)
13786                    .iter()
13787                    .zip(ranges_to_replace.iter())
13788                    .find_map(|(selection, range)| {
13789                        if selection.id == newest_selection_id {
13790                            Some(
13791                                (range.start.0 as isize - selection.head().0 as isize)
13792                                    ..(range.end.0 as isize - selection.head().0 as isize),
13793                            )
13794                        } else {
13795                            None
13796                        }
13797                    })
13798            });
13799
13800            cx.emit(EditorEvent::InputHandled {
13801                utf16_range_to_replace: range_to_replace,
13802                text: text.into(),
13803            });
13804
13805            if let Some(new_selected_ranges) = new_selected_ranges {
13806                this.change_selections(None, cx, |selections| {
13807                    selections.select_ranges(new_selected_ranges)
13808                });
13809                this.backspace(&Default::default(), cx);
13810            }
13811
13812            this.handle_input(text, cx);
13813        });
13814
13815        if let Some(transaction) = self.ime_transaction {
13816            self.buffer.update(cx, |buffer, cx| {
13817                buffer.group_until_transaction(transaction, cx);
13818            });
13819        }
13820
13821        self.unmark_text(cx);
13822    }
13823
13824    fn replace_and_mark_text_in_range(
13825        &mut self,
13826        range_utf16: Option<Range<usize>>,
13827        text: &str,
13828        new_selected_range_utf16: Option<Range<usize>>,
13829        cx: &mut ViewContext<Self>,
13830    ) {
13831        if !self.input_enabled {
13832            return;
13833        }
13834
13835        let transaction = self.transact(cx, |this, cx| {
13836            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13837                let snapshot = this.buffer.read(cx).read(cx);
13838                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13839                    for marked_range in &mut marked_ranges {
13840                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13841                        marked_range.start.0 += relative_range_utf16.start;
13842                        marked_range.start =
13843                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13844                        marked_range.end =
13845                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13846                    }
13847                }
13848                Some(marked_ranges)
13849            } else if let Some(range_utf16) = range_utf16 {
13850                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13851                Some(this.selection_replacement_ranges(range_utf16, cx))
13852            } else {
13853                None
13854            };
13855
13856            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13857                let newest_selection_id = this.selections.newest_anchor().id;
13858                this.selections
13859                    .all::<OffsetUtf16>(cx)
13860                    .iter()
13861                    .zip(ranges_to_replace.iter())
13862                    .find_map(|(selection, range)| {
13863                        if selection.id == newest_selection_id {
13864                            Some(
13865                                (range.start.0 as isize - selection.head().0 as isize)
13866                                    ..(range.end.0 as isize - selection.head().0 as isize),
13867                            )
13868                        } else {
13869                            None
13870                        }
13871                    })
13872            });
13873
13874            cx.emit(EditorEvent::InputHandled {
13875                utf16_range_to_replace: range_to_replace,
13876                text: text.into(),
13877            });
13878
13879            if let Some(ranges) = ranges_to_replace {
13880                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13881            }
13882
13883            let marked_ranges = {
13884                let snapshot = this.buffer.read(cx).read(cx);
13885                this.selections
13886                    .disjoint_anchors()
13887                    .iter()
13888                    .map(|selection| {
13889                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13890                    })
13891                    .collect::<Vec<_>>()
13892            };
13893
13894            if text.is_empty() {
13895                this.unmark_text(cx);
13896            } else {
13897                this.highlight_text::<InputComposition>(
13898                    marked_ranges.clone(),
13899                    HighlightStyle {
13900                        underline: Some(UnderlineStyle {
13901                            thickness: px(1.),
13902                            color: None,
13903                            wavy: false,
13904                        }),
13905                        ..Default::default()
13906                    },
13907                    cx,
13908                );
13909            }
13910
13911            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13912            let use_autoclose = this.use_autoclose;
13913            let use_auto_surround = this.use_auto_surround;
13914            this.set_use_autoclose(false);
13915            this.set_use_auto_surround(false);
13916            this.handle_input(text, cx);
13917            this.set_use_autoclose(use_autoclose);
13918            this.set_use_auto_surround(use_auto_surround);
13919
13920            if let Some(new_selected_range) = new_selected_range_utf16 {
13921                let snapshot = this.buffer.read(cx).read(cx);
13922                let new_selected_ranges = marked_ranges
13923                    .into_iter()
13924                    .map(|marked_range| {
13925                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13926                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13927                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13928                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13929                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13930                    })
13931                    .collect::<Vec<_>>();
13932
13933                drop(snapshot);
13934                this.change_selections(None, cx, |selections| {
13935                    selections.select_ranges(new_selected_ranges)
13936                });
13937            }
13938        });
13939
13940        self.ime_transaction = self.ime_transaction.or(transaction);
13941        if let Some(transaction) = self.ime_transaction {
13942            self.buffer.update(cx, |buffer, cx| {
13943                buffer.group_until_transaction(transaction, cx);
13944            });
13945        }
13946
13947        if self.text_highlights::<InputComposition>(cx).is_none() {
13948            self.ime_transaction.take();
13949        }
13950    }
13951
13952    fn bounds_for_range(
13953        &mut self,
13954        range_utf16: Range<usize>,
13955        element_bounds: gpui::Bounds<Pixels>,
13956        cx: &mut ViewContext<Self>,
13957    ) -> Option<gpui::Bounds<Pixels>> {
13958        let text_layout_details = self.text_layout_details(cx);
13959        let style = &text_layout_details.editor_style;
13960        let font_id = cx.text_system().resolve_font(&style.text.font());
13961        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13962        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13963
13964        let em_width = cx
13965            .text_system()
13966            .typographic_bounds(font_id, font_size, 'm')
13967            .unwrap()
13968            .size
13969            .width;
13970
13971        let snapshot = self.snapshot(cx);
13972        let scroll_position = snapshot.scroll_position();
13973        let scroll_left = scroll_position.x * em_width;
13974
13975        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13976        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13977            + self.gutter_dimensions.width;
13978        let y = line_height * (start.row().as_f32() - scroll_position.y);
13979
13980        Some(Bounds {
13981            origin: element_bounds.origin + point(x, y),
13982            size: size(em_width, line_height),
13983        })
13984    }
13985}
13986
13987trait SelectionExt {
13988    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13989    fn spanned_rows(
13990        &self,
13991        include_end_if_at_line_start: bool,
13992        map: &DisplaySnapshot,
13993    ) -> Range<MultiBufferRow>;
13994}
13995
13996impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13997    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13998        let start = self
13999            .start
14000            .to_point(&map.buffer_snapshot)
14001            .to_display_point(map);
14002        let end = self
14003            .end
14004            .to_point(&map.buffer_snapshot)
14005            .to_display_point(map);
14006        if self.reversed {
14007            end..start
14008        } else {
14009            start..end
14010        }
14011    }
14012
14013    fn spanned_rows(
14014        &self,
14015        include_end_if_at_line_start: bool,
14016        map: &DisplaySnapshot,
14017    ) -> Range<MultiBufferRow> {
14018        let start = self.start.to_point(&map.buffer_snapshot);
14019        let mut end = self.end.to_point(&map.buffer_snapshot);
14020        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14021            end.row -= 1;
14022        }
14023
14024        let buffer_start = map.prev_line_boundary(start).0;
14025        let buffer_end = map.next_line_boundary(end).0;
14026        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14027    }
14028}
14029
14030impl<T: InvalidationRegion> InvalidationStack<T> {
14031    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14032    where
14033        S: Clone + ToOffset,
14034    {
14035        while let Some(region) = self.last() {
14036            let all_selections_inside_invalidation_ranges =
14037                if selections.len() == region.ranges().len() {
14038                    selections
14039                        .iter()
14040                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14041                        .all(|(selection, invalidation_range)| {
14042                            let head = selection.head().to_offset(buffer);
14043                            invalidation_range.start <= head && invalidation_range.end >= head
14044                        })
14045                } else {
14046                    false
14047                };
14048
14049            if all_selections_inside_invalidation_ranges {
14050                break;
14051            } else {
14052                self.pop();
14053            }
14054        }
14055    }
14056}
14057
14058impl<T> Default for InvalidationStack<T> {
14059    fn default() -> Self {
14060        Self(Default::default())
14061    }
14062}
14063
14064impl<T> Deref for InvalidationStack<T> {
14065    type Target = Vec<T>;
14066
14067    fn deref(&self) -> &Self::Target {
14068        &self.0
14069    }
14070}
14071
14072impl<T> DerefMut for InvalidationStack<T> {
14073    fn deref_mut(&mut self) -> &mut Self::Target {
14074        &mut self.0
14075    }
14076}
14077
14078impl InvalidationRegion for SnippetState {
14079    fn ranges(&self) -> &[Range<Anchor>] {
14080        &self.ranges[self.active_index]
14081    }
14082}
14083
14084pub fn diagnostic_block_renderer(
14085    diagnostic: Diagnostic,
14086    max_message_rows: Option<u8>,
14087    allow_closing: bool,
14088    _is_valid: bool,
14089) -> RenderBlock {
14090    let (text_without_backticks, code_ranges) =
14091        highlight_diagnostic_message(&diagnostic, max_message_rows);
14092
14093    Box::new(move |cx: &mut BlockContext| {
14094        let group_id: SharedString = cx.block_id.to_string().into();
14095
14096        let mut text_style = cx.text_style().clone();
14097        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14098        let theme_settings = ThemeSettings::get_global(cx);
14099        text_style.font_family = theme_settings.buffer_font.family.clone();
14100        text_style.font_style = theme_settings.buffer_font.style;
14101        text_style.font_features = theme_settings.buffer_font.features.clone();
14102        text_style.font_weight = theme_settings.buffer_font.weight;
14103
14104        let multi_line_diagnostic = diagnostic.message.contains('\n');
14105
14106        let buttons = |diagnostic: &Diagnostic| {
14107            if multi_line_diagnostic {
14108                v_flex()
14109            } else {
14110                h_flex()
14111            }
14112            .when(allow_closing, |div| {
14113                div.children(diagnostic.is_primary.then(|| {
14114                    IconButton::new("close-block", IconName::XCircle)
14115                        .icon_color(Color::Muted)
14116                        .size(ButtonSize::Compact)
14117                        .style(ButtonStyle::Transparent)
14118                        .visible_on_hover(group_id.clone())
14119                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14120                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14121                }))
14122            })
14123            .child(
14124                IconButton::new("copy-block", IconName::Copy)
14125                    .icon_color(Color::Muted)
14126                    .size(ButtonSize::Compact)
14127                    .style(ButtonStyle::Transparent)
14128                    .visible_on_hover(group_id.clone())
14129                    .on_click({
14130                        let message = diagnostic.message.clone();
14131                        move |_click, cx| {
14132                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14133                        }
14134                    })
14135                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14136            )
14137        };
14138
14139        let icon_size = buttons(&diagnostic)
14140            .into_any_element()
14141            .layout_as_root(AvailableSpace::min_size(), cx);
14142
14143        h_flex()
14144            .id(cx.block_id)
14145            .group(group_id.clone())
14146            .relative()
14147            .size_full()
14148            .pl(cx.gutter_dimensions.width)
14149            .w(cx.max_width + cx.gutter_dimensions.width)
14150            .child(
14151                div()
14152                    .flex()
14153                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14154                    .flex_shrink(),
14155            )
14156            .child(buttons(&diagnostic))
14157            .child(div().flex().flex_shrink_0().child(
14158                StyledText::new(text_without_backticks.clone()).with_highlights(
14159                    &text_style,
14160                    code_ranges.iter().map(|range| {
14161                        (
14162                            range.clone(),
14163                            HighlightStyle {
14164                                font_weight: Some(FontWeight::BOLD),
14165                                ..Default::default()
14166                            },
14167                        )
14168                    }),
14169                ),
14170            ))
14171            .into_any_element()
14172    })
14173}
14174
14175pub fn highlight_diagnostic_message(
14176    diagnostic: &Diagnostic,
14177    mut max_message_rows: Option<u8>,
14178) -> (SharedString, Vec<Range<usize>>) {
14179    let mut text_without_backticks = String::new();
14180    let mut code_ranges = Vec::new();
14181
14182    if let Some(source) = &diagnostic.source {
14183        text_without_backticks.push_str(source);
14184        code_ranges.push(0..source.len());
14185        text_without_backticks.push_str(": ");
14186    }
14187
14188    let mut prev_offset = 0;
14189    let mut in_code_block = false;
14190    let has_row_limit = max_message_rows.is_some();
14191    let mut newline_indices = diagnostic
14192        .message
14193        .match_indices('\n')
14194        .filter(|_| has_row_limit)
14195        .map(|(ix, _)| ix)
14196        .fuse()
14197        .peekable();
14198
14199    for (quote_ix, _) in diagnostic
14200        .message
14201        .match_indices('`')
14202        .chain([(diagnostic.message.len(), "")])
14203    {
14204        let mut first_newline_ix = None;
14205        let mut last_newline_ix = None;
14206        while let Some(newline_ix) = newline_indices.peek() {
14207            if *newline_ix < quote_ix {
14208                if first_newline_ix.is_none() {
14209                    first_newline_ix = Some(*newline_ix);
14210                }
14211                last_newline_ix = Some(*newline_ix);
14212
14213                if let Some(rows_left) = &mut max_message_rows {
14214                    if *rows_left == 0 {
14215                        break;
14216                    } else {
14217                        *rows_left -= 1;
14218                    }
14219                }
14220                let _ = newline_indices.next();
14221            } else {
14222                break;
14223            }
14224        }
14225        let prev_len = text_without_backticks.len();
14226        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14227        text_without_backticks.push_str(new_text);
14228        if in_code_block {
14229            code_ranges.push(prev_len..text_without_backticks.len());
14230        }
14231        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14232        in_code_block = !in_code_block;
14233        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14234            text_without_backticks.push_str("...");
14235            break;
14236        }
14237    }
14238
14239    (text_without_backticks.into(), code_ranges)
14240}
14241
14242fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14243    match severity {
14244        DiagnosticSeverity::ERROR => colors.error,
14245        DiagnosticSeverity::WARNING => colors.warning,
14246        DiagnosticSeverity::INFORMATION => colors.info,
14247        DiagnosticSeverity::HINT => colors.info,
14248        _ => colors.ignored,
14249    }
14250}
14251
14252pub fn styled_runs_for_code_label<'a>(
14253    label: &'a CodeLabel,
14254    syntax_theme: &'a theme::SyntaxTheme,
14255) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14256    let fade_out = HighlightStyle {
14257        fade_out: Some(0.35),
14258        ..Default::default()
14259    };
14260
14261    let mut prev_end = label.filter_range.end;
14262    label
14263        .runs
14264        .iter()
14265        .enumerate()
14266        .flat_map(move |(ix, (range, highlight_id))| {
14267            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14268                style
14269            } else {
14270                return Default::default();
14271            };
14272            let mut muted_style = style;
14273            muted_style.highlight(fade_out);
14274
14275            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14276            if range.start >= label.filter_range.end {
14277                if range.start > prev_end {
14278                    runs.push((prev_end..range.start, fade_out));
14279                }
14280                runs.push((range.clone(), muted_style));
14281            } else if range.end <= label.filter_range.end {
14282                runs.push((range.clone(), style));
14283            } else {
14284                runs.push((range.start..label.filter_range.end, style));
14285                runs.push((label.filter_range.end..range.end, muted_style));
14286            }
14287            prev_end = cmp::max(prev_end, range.end);
14288
14289            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14290                runs.push((prev_end..label.text.len(), fade_out));
14291            }
14292
14293            runs
14294        })
14295}
14296
14297pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14298    let mut prev_index = 0;
14299    let mut prev_codepoint: Option<char> = None;
14300    text.char_indices()
14301        .chain([(text.len(), '\0')])
14302        .filter_map(move |(index, codepoint)| {
14303            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14304            let is_boundary = index == text.len()
14305                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14306                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14307            if is_boundary {
14308                let chunk = &text[prev_index..index];
14309                prev_index = index;
14310                Some(chunk)
14311            } else {
14312                None
14313            }
14314        })
14315}
14316
14317pub trait RangeToAnchorExt: Sized {
14318    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14319
14320    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14321        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14322        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14323    }
14324}
14325
14326impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14327    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14328        let start_offset = self.start.to_offset(snapshot);
14329        let end_offset = self.end.to_offset(snapshot);
14330        if start_offset == end_offset {
14331            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14332        } else {
14333            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14334        }
14335    }
14336}
14337
14338pub trait RowExt {
14339    fn as_f32(&self) -> f32;
14340
14341    fn next_row(&self) -> Self;
14342
14343    fn previous_row(&self) -> Self;
14344
14345    fn minus(&self, other: Self) -> u32;
14346}
14347
14348impl RowExt for DisplayRow {
14349    fn as_f32(&self) -> f32 {
14350        self.0 as f32
14351    }
14352
14353    fn next_row(&self) -> Self {
14354        Self(self.0 + 1)
14355    }
14356
14357    fn previous_row(&self) -> Self {
14358        Self(self.0.saturating_sub(1))
14359    }
14360
14361    fn minus(&self, other: Self) -> u32 {
14362        self.0 - other.0
14363    }
14364}
14365
14366impl RowExt for MultiBufferRow {
14367    fn as_f32(&self) -> f32 {
14368        self.0 as f32
14369    }
14370
14371    fn next_row(&self) -> Self {
14372        Self(self.0 + 1)
14373    }
14374
14375    fn previous_row(&self) -> Self {
14376        Self(self.0.saturating_sub(1))
14377    }
14378
14379    fn minus(&self, other: Self) -> u32 {
14380        self.0 - other.0
14381    }
14382}
14383
14384trait RowRangeExt {
14385    type Row;
14386
14387    fn len(&self) -> usize;
14388
14389    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14390}
14391
14392impl RowRangeExt for Range<MultiBufferRow> {
14393    type Row = MultiBufferRow;
14394
14395    fn len(&self) -> usize {
14396        (self.end.0 - self.start.0) as usize
14397    }
14398
14399    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14400        (self.start.0..self.end.0).map(MultiBufferRow)
14401    }
14402}
14403
14404impl RowRangeExt for Range<DisplayRow> {
14405    type Row = DisplayRow;
14406
14407    fn len(&self) -> usize {
14408        (self.end.0 - self.start.0) as usize
14409    }
14410
14411    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14412        (self.start.0..self.end.0).map(DisplayRow)
14413    }
14414}
14415
14416fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14417    if hunk.diff_base_byte_range.is_empty() {
14418        DiffHunkStatus::Added
14419    } else if hunk.row_range.is_empty() {
14420        DiffHunkStatus::Removed
14421    } else {
14422        DiffHunkStatus::Modified
14423    }
14424}
14425
14426/// If select range has more than one line, we
14427/// just point the cursor to range.start.
14428fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14429    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14430        range
14431    } else {
14432        range.start..range.start
14433    }
14434}