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, UTF16Selection,
   80    UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
   81    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, 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 = all_language_settings(None, cx)
  432        .language(None)
  433        .inlay_hints
  434        .show_background;
  435
  436    HighlightStyle {
  437        color: Some(cx.theme().status().hint),
  438        background_color: show_background.then(|| cx.theme().status().hint_background),
  439        ..HighlightStyle::default()
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445#[derive(Clone, Debug)]
  446struct CompletionState {
  447    // render_inlay_ids represents the inlay hints that are inserted
  448    // for rendering the inline completions. They may be discontinuous
  449    // in the event that the completion provider returns some intersection
  450    // with the existing content.
  451    render_inlay_ids: Vec<InlayId>,
  452    // text is the resulting rope that is inserted when the user accepts a completion.
  453    text: Rope,
  454    // position is the position of the cursor when the completion was triggered.
  455    position: multi_buffer::Anchor,
  456    // delete_range is the range of text that this completion state covers.
  457    // if the completion is accepted, this range should be deleted.
  458    delete_range: Option<Range<multi_buffer::Anchor>>,
  459}
  460
  461#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  462struct EditorActionId(usize);
  463
  464impl EditorActionId {
  465    pub fn post_inc(&mut self) -> Self {
  466        let answer = self.0;
  467
  468        *self = Self(answer + 1);
  469
  470        Self(answer)
  471    }
  472}
  473
  474// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  475// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  476
  477type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  478type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  479
  480#[derive(Default)]
  481struct ScrollbarMarkerState {
  482    scrollbar_size: Size<Pixels>,
  483    dirty: bool,
  484    markers: Arc<[PaintQuad]>,
  485    pending_refresh: Option<Task<Result<()>>>,
  486}
  487
  488impl ScrollbarMarkerState {
  489    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  490        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  491    }
  492}
  493
  494#[derive(Clone, Debug)]
  495struct RunnableTasks {
  496    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  497    offset: MultiBufferOffset,
  498    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  499    column: u32,
  500    // Values of all named captures, including those starting with '_'
  501    extra_variables: HashMap<String, String>,
  502    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  503    context_range: Range<BufferOffset>,
  504}
  505
  506#[derive(Clone)]
  507struct ResolvedTasks {
  508    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  509    position: Anchor,
  510}
  511#[derive(Copy, Clone, Debug)]
  512struct MultiBufferOffset(usize);
  513#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  514struct BufferOffset(usize);
  515
  516// Addons allow storing per-editor state in other crates (e.g. Vim)
  517pub trait Addon: 'static {
  518    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  519
  520    fn to_any(&self) -> &dyn std::any::Any;
  521}
  522
  523/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  524///
  525/// See the [module level documentation](self) for more information.
  526pub struct Editor {
  527    focus_handle: FocusHandle,
  528    last_focused_descendant: Option<WeakFocusHandle>,
  529    /// The text buffer being edited
  530    buffer: Model<MultiBuffer>,
  531    /// Map of how text in the buffer should be displayed.
  532    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  533    pub display_map: Model<DisplayMap>,
  534    pub selections: SelectionsCollection,
  535    pub scroll_manager: ScrollManager,
  536    /// When inline assist editors are linked, they all render cursors because
  537    /// typing enters text into each of them, even the ones that aren't focused.
  538    pub(crate) show_cursor_when_unfocused: bool,
  539    columnar_selection_tail: Option<Anchor>,
  540    add_selections_state: Option<AddSelectionsState>,
  541    select_next_state: Option<SelectNextState>,
  542    select_prev_state: Option<SelectNextState>,
  543    selection_history: SelectionHistory,
  544    autoclose_regions: Vec<AutocloseRegion>,
  545    snippet_stack: InvalidationStack<SnippetState>,
  546    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  547    ime_transaction: Option<TransactionId>,
  548    active_diagnostics: Option<ActiveDiagnosticGroup>,
  549    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  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    next_editor_action_id: EditorActionId,
  620    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  621    use_autoclose: bool,
  622    use_auto_surround: bool,
  623    auto_replace_emoji_shortcode: bool,
  624    show_git_blame_gutter: bool,
  625    show_git_blame_inline: bool,
  626    show_git_blame_inline_delay_task: Option<Task<()>>,
  627    git_blame_inline_enabled: bool,
  628    serialize_dirty_buffers: bool,
  629    show_selection_menu: Option<bool>,
  630    blame: Option<Model<GitBlame>>,
  631    blame_subscription: Option<Subscription>,
  632    custom_context_menu: Option<
  633        Box<
  634            dyn 'static
  635                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  636        >,
  637    >,
  638    last_bounds: Option<Bounds<Pixels>>,
  639    expect_bounds_change: Option<Bounds<Pixels>>,
  640    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  641    tasks_update_task: Option<Task<()>>,
  642    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  643    breadcrumb_header: Option<String>,
  644    focused_block: Option<FocusedBlock>,
  645    next_scroll_position: NextScrollCursorCenterTopBottom,
  646    addons: HashMap<TypeId, Box<dyn Addon>>,
  647    _scroll_cursor_center_top_bottom_task: Task<()>,
  648}
  649
  650#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  651enum NextScrollCursorCenterTopBottom {
  652    #[default]
  653    Center,
  654    Top,
  655    Bottom,
  656}
  657
  658impl NextScrollCursorCenterTopBottom {
  659    fn next(&self) -> Self {
  660        match self {
  661            Self::Center => Self::Top,
  662            Self::Top => Self::Bottom,
  663            Self::Bottom => Self::Center,
  664        }
  665    }
  666}
  667
  668#[derive(Clone)]
  669pub struct EditorSnapshot {
  670    pub mode: EditorMode,
  671    show_gutter: bool,
  672    show_line_numbers: Option<bool>,
  673    show_git_diff_gutter: Option<bool>,
  674    show_code_actions: Option<bool>,
  675    show_runnables: Option<bool>,
  676    git_blame_gutter_max_author_length: Option<usize>,
  677    pub display_snapshot: DisplaySnapshot,
  678    pub placeholder_text: Option<Arc<str>>,
  679    is_focused: bool,
  680    scroll_anchor: ScrollAnchor,
  681    ongoing_scroll: OngoingScroll,
  682    current_line_highlight: CurrentLineHighlight,
  683    gutter_hovered: bool,
  684}
  685
  686const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  687
  688#[derive(Default, Debug, Clone, Copy)]
  689pub struct GutterDimensions {
  690    pub left_padding: Pixels,
  691    pub right_padding: Pixels,
  692    pub width: Pixels,
  693    pub margin: Pixels,
  694    pub git_blame_entries_width: Option<Pixels>,
  695}
  696
  697impl GutterDimensions {
  698    /// The full width of the space taken up by the gutter.
  699    pub fn full_width(&self) -> Pixels {
  700        self.margin + self.width
  701    }
  702
  703    /// The width of the space reserved for the fold indicators,
  704    /// use alongside 'justify_end' and `gutter_width` to
  705    /// right align content with the line numbers
  706    pub fn fold_area_width(&self) -> Pixels {
  707        self.margin + self.right_padding
  708    }
  709}
  710
  711#[derive(Debug)]
  712pub struct RemoteSelection {
  713    pub replica_id: ReplicaId,
  714    pub selection: Selection<Anchor>,
  715    pub cursor_shape: CursorShape,
  716    pub peer_id: PeerId,
  717    pub line_mode: bool,
  718    pub participant_index: Option<ParticipantIndex>,
  719    pub user_name: Option<SharedString>,
  720}
  721
  722#[derive(Clone, Debug)]
  723struct SelectionHistoryEntry {
  724    selections: Arc<[Selection<Anchor>]>,
  725    select_next_state: Option<SelectNextState>,
  726    select_prev_state: Option<SelectNextState>,
  727    add_selections_state: Option<AddSelectionsState>,
  728}
  729
  730enum SelectionHistoryMode {
  731    Normal,
  732    Undoing,
  733    Redoing,
  734}
  735
  736#[derive(Clone, PartialEq, Eq, Hash)]
  737struct HoveredCursor {
  738    replica_id: u16,
  739    selection_id: usize,
  740}
  741
  742impl Default for SelectionHistoryMode {
  743    fn default() -> Self {
  744        Self::Normal
  745    }
  746}
  747
  748#[derive(Default)]
  749struct SelectionHistory {
  750    #[allow(clippy::type_complexity)]
  751    selections_by_transaction:
  752        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  753    mode: SelectionHistoryMode,
  754    undo_stack: VecDeque<SelectionHistoryEntry>,
  755    redo_stack: VecDeque<SelectionHistoryEntry>,
  756}
  757
  758impl SelectionHistory {
  759    fn insert_transaction(
  760        &mut self,
  761        transaction_id: TransactionId,
  762        selections: Arc<[Selection<Anchor>]>,
  763    ) {
  764        self.selections_by_transaction
  765            .insert(transaction_id, (selections, None));
  766    }
  767
  768    #[allow(clippy::type_complexity)]
  769    fn transaction(
  770        &self,
  771        transaction_id: TransactionId,
  772    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  773        self.selections_by_transaction.get(&transaction_id)
  774    }
  775
  776    #[allow(clippy::type_complexity)]
  777    fn transaction_mut(
  778        &mut self,
  779        transaction_id: TransactionId,
  780    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  781        self.selections_by_transaction.get_mut(&transaction_id)
  782    }
  783
  784    fn push(&mut self, entry: SelectionHistoryEntry) {
  785        if !entry.selections.is_empty() {
  786            match self.mode {
  787                SelectionHistoryMode::Normal => {
  788                    self.push_undo(entry);
  789                    self.redo_stack.clear();
  790                }
  791                SelectionHistoryMode::Undoing => self.push_redo(entry),
  792                SelectionHistoryMode::Redoing => self.push_undo(entry),
  793            }
  794        }
  795    }
  796
  797    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  798        if self
  799            .undo_stack
  800            .back()
  801            .map_or(true, |e| e.selections != entry.selections)
  802        {
  803            self.undo_stack.push_back(entry);
  804            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  805                self.undo_stack.pop_front();
  806            }
  807        }
  808    }
  809
  810    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  811        if self
  812            .redo_stack
  813            .back()
  814            .map_or(true, |e| e.selections != entry.selections)
  815        {
  816            self.redo_stack.push_back(entry);
  817            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  818                self.redo_stack.pop_front();
  819            }
  820        }
  821    }
  822}
  823
  824struct RowHighlight {
  825    index: usize,
  826    range: Range<Anchor>,
  827    color: Hsla,
  828    should_autoscroll: bool,
  829}
  830
  831#[derive(Clone, Debug)]
  832struct AddSelectionsState {
  833    above: bool,
  834    stack: Vec<usize>,
  835}
  836
  837#[derive(Clone)]
  838struct SelectNextState {
  839    query: AhoCorasick,
  840    wordwise: bool,
  841    done: bool,
  842}
  843
  844impl std::fmt::Debug for SelectNextState {
  845    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  846        f.debug_struct(std::any::type_name::<Self>())
  847            .field("wordwise", &self.wordwise)
  848            .field("done", &self.done)
  849            .finish()
  850    }
  851}
  852
  853#[derive(Debug)]
  854struct AutocloseRegion {
  855    selection_id: usize,
  856    range: Range<Anchor>,
  857    pair: BracketPair,
  858}
  859
  860#[derive(Debug)]
  861struct SnippetState {
  862    ranges: Vec<Vec<Range<Anchor>>>,
  863    active_index: usize,
  864}
  865
  866#[doc(hidden)]
  867pub struct RenameState {
  868    pub range: Range<Anchor>,
  869    pub old_name: Arc<str>,
  870    pub editor: View<Editor>,
  871    block_id: CustomBlockId,
  872}
  873
  874struct InvalidationStack<T>(Vec<T>);
  875
  876struct RegisteredInlineCompletionProvider {
  877    provider: Arc<dyn InlineCompletionProviderHandle>,
  878    _subscription: Subscription,
  879}
  880
  881enum ContextMenu {
  882    Completions(CompletionsMenu),
  883    CodeActions(CodeActionsMenu),
  884}
  885
  886impl ContextMenu {
  887    fn select_first(
  888        &mut self,
  889        provider: Option<&dyn CompletionProvider>,
  890        cx: &mut ViewContext<Editor>,
  891    ) -> bool {
  892        if self.visible() {
  893            match self {
  894                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  895                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  896            }
  897            true
  898        } else {
  899            false
  900        }
  901    }
  902
  903    fn select_prev(
  904        &mut self,
  905        provider: Option<&dyn CompletionProvider>,
  906        cx: &mut ViewContext<Editor>,
  907    ) -> bool {
  908        if self.visible() {
  909            match self {
  910                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_next(
  920        &mut self,
  921        provider: Option<&dyn CompletionProvider>,
  922        cx: &mut ViewContext<Editor>,
  923    ) -> bool {
  924        if self.visible() {
  925            match self {
  926                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_last(
  936        &mut self,
  937        provider: Option<&dyn CompletionProvider>,
  938        cx: &mut ViewContext<Editor>,
  939    ) -> bool {
  940        if self.visible() {
  941            match self {
  942                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn visible(&self) -> bool {
  952        match self {
  953            ContextMenu::Completions(menu) => menu.visible(),
  954            ContextMenu::CodeActions(menu) => menu.visible(),
  955        }
  956    }
  957
  958    fn render(
  959        &self,
  960        cursor_position: DisplayPoint,
  961        style: &EditorStyle,
  962        max_height: Pixels,
  963        workspace: Option<WeakView<Workspace>>,
  964        cx: &mut ViewContext<Editor>,
  965    ) -> (ContextMenuOrigin, AnyElement) {
  966        match self {
  967            ContextMenu::Completions(menu) => (
  968                ContextMenuOrigin::EditorPoint(cursor_position),
  969                menu.render(style, max_height, workspace, cx),
  970            ),
  971            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  972        }
  973    }
  974}
  975
  976enum ContextMenuOrigin {
  977    EditorPoint(DisplayPoint),
  978    GutterIndicator(DisplayRow),
  979}
  980
  981#[derive(Clone)]
  982struct CompletionsMenu {
  983    id: CompletionId,
  984    sort_completions: bool,
  985    initial_position: Anchor,
  986    buffer: Model<Buffer>,
  987    completions: Arc<RwLock<Box<[Completion]>>>,
  988    match_candidates: Arc<[StringMatchCandidate]>,
  989    matches: Arc<[StringMatch]>,
  990    selected_item: usize,
  991    scroll_handle: UniformListScrollHandle,
  992    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  993}
  994
  995impl CompletionsMenu {
  996    fn select_first(
  997        &mut self,
  998        provider: Option<&dyn CompletionProvider>,
  999        cx: &mut ViewContext<Editor>,
 1000    ) {
 1001        self.selected_item = 0;
 1002        self.scroll_handle.scroll_to_item(self.selected_item);
 1003        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1004        cx.notify();
 1005    }
 1006
 1007    fn select_prev(
 1008        &mut self,
 1009        provider: Option<&dyn CompletionProvider>,
 1010        cx: &mut ViewContext<Editor>,
 1011    ) {
 1012        if self.selected_item > 0 {
 1013            self.selected_item -= 1;
 1014        } else {
 1015            self.selected_item = self.matches.len() - 1;
 1016        }
 1017        self.scroll_handle.scroll_to_item(self.selected_item);
 1018        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1019        cx.notify();
 1020    }
 1021
 1022    fn select_next(
 1023        &mut self,
 1024        provider: Option<&dyn CompletionProvider>,
 1025        cx: &mut ViewContext<Editor>,
 1026    ) {
 1027        if self.selected_item + 1 < self.matches.len() {
 1028            self.selected_item += 1;
 1029        } else {
 1030            self.selected_item = 0;
 1031        }
 1032        self.scroll_handle.scroll_to_item(self.selected_item);
 1033        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1034        cx.notify();
 1035    }
 1036
 1037    fn select_last(
 1038        &mut self,
 1039        provider: Option<&dyn CompletionProvider>,
 1040        cx: &mut ViewContext<Editor>,
 1041    ) {
 1042        self.selected_item = self.matches.len() - 1;
 1043        self.scroll_handle.scroll_to_item(self.selected_item);
 1044        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1045        cx.notify();
 1046    }
 1047
 1048    fn pre_resolve_completion_documentation(
 1049        buffer: Model<Buffer>,
 1050        completions: Arc<RwLock<Box<[Completion]>>>,
 1051        matches: Arc<[StringMatch]>,
 1052        editor: &Editor,
 1053        cx: &mut ViewContext<Editor>,
 1054    ) -> Task<()> {
 1055        let settings = EditorSettings::get_global(cx);
 1056        if !settings.show_completion_documentation {
 1057            return Task::ready(());
 1058        }
 1059
 1060        let Some(provider) = editor.completion_provider.as_ref() else {
 1061            return Task::ready(());
 1062        };
 1063
 1064        let resolve_task = provider.resolve_completions(
 1065            buffer,
 1066            matches.iter().map(|m| m.candidate_id).collect(),
 1067            completions.clone(),
 1068            cx,
 1069        );
 1070
 1071        cx.spawn(move |this, mut cx| async move {
 1072            if let Some(true) = resolve_task.await.log_err() {
 1073                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1074            }
 1075        })
 1076    }
 1077
 1078    fn attempt_resolve_selected_completion_documentation(
 1079        &mut self,
 1080        provider: Option<&dyn CompletionProvider>,
 1081        cx: &mut ViewContext<Editor>,
 1082    ) {
 1083        let settings = EditorSettings::get_global(cx);
 1084        if !settings.show_completion_documentation {
 1085            return;
 1086        }
 1087
 1088        let completion_index = self.matches[self.selected_item].candidate_id;
 1089        let Some(provider) = provider else {
 1090            return;
 1091        };
 1092
 1093        let resolve_task = provider.resolve_completions(
 1094            self.buffer.clone(),
 1095            vec![completion_index],
 1096            self.completions.clone(),
 1097            cx,
 1098        );
 1099
 1100        let delay_ms =
 1101            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1102        let delay = Duration::from_millis(delay_ms);
 1103
 1104        self.selected_completion_documentation_resolve_debounce
 1105            .lock()
 1106            .fire_new(delay, cx, |_, cx| {
 1107                cx.spawn(move |this, mut cx| async move {
 1108                    if let Some(true) = resolve_task.await.log_err() {
 1109                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1110                    }
 1111                })
 1112            });
 1113    }
 1114
 1115    fn visible(&self) -> bool {
 1116        !self.matches.is_empty()
 1117    }
 1118
 1119    fn render(
 1120        &self,
 1121        style: &EditorStyle,
 1122        max_height: Pixels,
 1123        workspace: Option<WeakView<Workspace>>,
 1124        cx: &mut ViewContext<Editor>,
 1125    ) -> AnyElement {
 1126        let settings = EditorSettings::get_global(cx);
 1127        let show_completion_documentation = settings.show_completion_documentation;
 1128
 1129        let widest_completion_ix = self
 1130            .matches
 1131            .iter()
 1132            .enumerate()
 1133            .max_by_key(|(_, mat)| {
 1134                let completions = self.completions.read();
 1135                let completion = &completions[mat.candidate_id];
 1136                let documentation = &completion.documentation;
 1137
 1138                let mut len = completion.label.text.chars().count();
 1139                if let Some(Documentation::SingleLine(text)) = documentation {
 1140                    if show_completion_documentation {
 1141                        len += text.chars().count();
 1142                    }
 1143                }
 1144
 1145                len
 1146            })
 1147            .map(|(ix, _)| ix);
 1148
 1149        let completions = self.completions.clone();
 1150        let matches = self.matches.clone();
 1151        let selected_item = self.selected_item;
 1152        let style = style.clone();
 1153
 1154        let multiline_docs = if show_completion_documentation {
 1155            let mat = &self.matches[selected_item];
 1156            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1157                Some(Documentation::MultiLinePlainText(text)) => {
 1158                    Some(div().child(SharedString::from(text.clone())))
 1159                }
 1160                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1161                    Some(div().child(render_parsed_markdown(
 1162                        "completions_markdown",
 1163                        parsed,
 1164                        &style,
 1165                        workspace,
 1166                        cx,
 1167                    )))
 1168                }
 1169                _ => None,
 1170            };
 1171            multiline_docs.map(|div| {
 1172                div.id("multiline_docs")
 1173                    .max_h(max_height)
 1174                    .flex_1()
 1175                    .px_1p5()
 1176                    .py_1()
 1177                    .min_w(px(260.))
 1178                    .max_w(px(640.))
 1179                    .w(px(500.))
 1180                    .overflow_y_scroll()
 1181                    .occlude()
 1182            })
 1183        } else {
 1184            None
 1185        };
 1186
 1187        let list = uniform_list(
 1188            cx.view().clone(),
 1189            "completions",
 1190            matches.len(),
 1191            move |_editor, range, cx| {
 1192                let start_ix = range.start;
 1193                let completions_guard = completions.read();
 1194
 1195                matches[range]
 1196                    .iter()
 1197                    .enumerate()
 1198                    .map(|(ix, mat)| {
 1199                        let item_ix = start_ix + ix;
 1200                        let candidate_id = mat.candidate_id;
 1201                        let completion = &completions_guard[candidate_id];
 1202
 1203                        let documentation = if show_completion_documentation {
 1204                            &completion.documentation
 1205                        } else {
 1206                            &None
 1207                        };
 1208
 1209                        let highlights = gpui::combine_highlights(
 1210                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1211                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1212                                |(range, mut highlight)| {
 1213                                    // Ignore font weight for syntax highlighting, as we'll use it
 1214                                    // for fuzzy matches.
 1215                                    highlight.font_weight = None;
 1216
 1217                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1218                                        highlight.strikethrough = Some(StrikethroughStyle {
 1219                                            thickness: 1.0.into(),
 1220                                            ..Default::default()
 1221                                        });
 1222                                        highlight.color = Some(cx.theme().colors().text_muted);
 1223                                    }
 1224
 1225                                    (range, highlight)
 1226                                },
 1227                            ),
 1228                        );
 1229                        let completion_label = StyledText::new(completion.label.text.clone())
 1230                            .with_highlights(&style.text, highlights);
 1231                        let documentation_label =
 1232                            if let Some(Documentation::SingleLine(text)) = documentation {
 1233                                if text.trim().is_empty() {
 1234                                    None
 1235                                } else {
 1236                                    Some(
 1237                                        Label::new(text.clone())
 1238                                            .ml_4()
 1239                                            .size(LabelSize::Small)
 1240                                            .color(Color::Muted),
 1241                                    )
 1242                                }
 1243                            } else {
 1244                                None
 1245                            };
 1246
 1247                        let color_swatch = completion
 1248                            .color()
 1249                            .map(|color| div().size_4().bg(color).rounded_sm());
 1250
 1251                        div().min_w(px(220.)).max_w(px(540.)).child(
 1252                            ListItem::new(mat.candidate_id)
 1253                                .inset(true)
 1254                                .selected(item_ix == selected_item)
 1255                                .on_click(cx.listener(move |editor, _event, cx| {
 1256                                    cx.stop_propagation();
 1257                                    if let Some(task) = editor.confirm_completion(
 1258                                        &ConfirmCompletion {
 1259                                            item_ix: Some(item_ix),
 1260                                        },
 1261                                        cx,
 1262                                    ) {
 1263                                        task.detach_and_log_err(cx)
 1264                                    }
 1265                                }))
 1266                                .start_slot::<Div>(color_swatch)
 1267                                .child(h_flex().overflow_hidden().child(completion_label))
 1268                                .end_slot::<Label>(documentation_label),
 1269                        )
 1270                    })
 1271                    .collect()
 1272            },
 1273        )
 1274        .occlude()
 1275        .max_h(max_height)
 1276        .track_scroll(self.scroll_handle.clone())
 1277        .with_width_from_item(widest_completion_ix)
 1278        .with_sizing_behavior(ListSizingBehavior::Infer);
 1279
 1280        Popover::new()
 1281            .child(list)
 1282            .when_some(multiline_docs, |popover, multiline_docs| {
 1283                popover.aside(multiline_docs)
 1284            })
 1285            .into_any_element()
 1286    }
 1287
 1288    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1289        let mut matches = if let Some(query) = query {
 1290            fuzzy::match_strings(
 1291                &self.match_candidates,
 1292                query,
 1293                query.chars().any(|c| c.is_uppercase()),
 1294                100,
 1295                &Default::default(),
 1296                executor,
 1297            )
 1298            .await
 1299        } else {
 1300            self.match_candidates
 1301                .iter()
 1302                .enumerate()
 1303                .map(|(candidate_id, candidate)| StringMatch {
 1304                    candidate_id,
 1305                    score: Default::default(),
 1306                    positions: Default::default(),
 1307                    string: candidate.string.clone(),
 1308                })
 1309                .collect()
 1310        };
 1311
 1312        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1313        if let Some(query) = query {
 1314            if let Some(query_start) = query.chars().next() {
 1315                matches.retain(|string_match| {
 1316                    split_words(&string_match.string).any(|word| {
 1317                        // Check that the first codepoint of the word as lowercase matches the first
 1318                        // codepoint of the query as lowercase
 1319                        word.chars()
 1320                            .flat_map(|codepoint| codepoint.to_lowercase())
 1321                            .zip(query_start.to_lowercase())
 1322                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1323                    })
 1324                });
 1325            }
 1326        }
 1327
 1328        let completions = self.completions.read();
 1329        if self.sort_completions {
 1330            matches.sort_unstable_by_key(|mat| {
 1331                // We do want to strike a balance here between what the language server tells us
 1332                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1333                // `Creat` and there is a local variable called `CreateComponent`).
 1334                // So what we do is: we bucket all matches into two buckets
 1335                // - Strong matches
 1336                // - Weak matches
 1337                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1338                // and the Weak matches are the rest.
 1339                //
 1340                // For the strong matches, we sort by the language-servers score first and for the weak
 1341                // matches, we prefer our fuzzy finder first.
 1342                //
 1343                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1344                // us into account when it's obviously a bad match.
 1345
 1346                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1347                enum MatchScore<'a> {
 1348                    Strong {
 1349                        sort_text: Option<&'a str>,
 1350                        score: Reverse<OrderedFloat<f64>>,
 1351                        sort_key: (usize, &'a str),
 1352                    },
 1353                    Weak {
 1354                        score: Reverse<OrderedFloat<f64>>,
 1355                        sort_text: Option<&'a str>,
 1356                        sort_key: (usize, &'a str),
 1357                    },
 1358                }
 1359
 1360                let completion = &completions[mat.candidate_id];
 1361                let sort_key = completion.sort_key();
 1362                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1363                let score = Reverse(OrderedFloat(mat.score));
 1364
 1365                if mat.score >= 0.2 {
 1366                    MatchScore::Strong {
 1367                        sort_text,
 1368                        score,
 1369                        sort_key,
 1370                    }
 1371                } else {
 1372                    MatchScore::Weak {
 1373                        score,
 1374                        sort_text,
 1375                        sort_key,
 1376                    }
 1377                }
 1378            });
 1379        }
 1380
 1381        for mat in &mut matches {
 1382            let completion = &completions[mat.candidate_id];
 1383            mat.string.clone_from(&completion.label.text);
 1384            for position in &mut mat.positions {
 1385                *position += completion.label.filter_range.start;
 1386            }
 1387        }
 1388        drop(completions);
 1389
 1390        self.matches = matches.into();
 1391        self.selected_item = 0;
 1392    }
 1393}
 1394
 1395struct AvailableCodeAction {
 1396    excerpt_id: ExcerptId,
 1397    action: CodeAction,
 1398    provider: Arc<dyn CodeActionProvider>,
 1399}
 1400
 1401#[derive(Clone)]
 1402struct CodeActionContents {
 1403    tasks: Option<Arc<ResolvedTasks>>,
 1404    actions: Option<Arc<[AvailableCodeAction]>>,
 1405}
 1406
 1407impl CodeActionContents {
 1408    fn len(&self) -> usize {
 1409        match (&self.tasks, &self.actions) {
 1410            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1411            (Some(tasks), None) => tasks.templates.len(),
 1412            (None, Some(actions)) => actions.len(),
 1413            (None, None) => 0,
 1414        }
 1415    }
 1416
 1417    fn is_empty(&self) -> bool {
 1418        match (&self.tasks, &self.actions) {
 1419            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1420            (Some(tasks), None) => tasks.templates.is_empty(),
 1421            (None, Some(actions)) => actions.is_empty(),
 1422            (None, None) => true,
 1423        }
 1424    }
 1425
 1426    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1427        self.tasks
 1428            .iter()
 1429            .flat_map(|tasks| {
 1430                tasks
 1431                    .templates
 1432                    .iter()
 1433                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1434            })
 1435            .chain(self.actions.iter().flat_map(|actions| {
 1436                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1437                    excerpt_id: available.excerpt_id,
 1438                    action: available.action.clone(),
 1439                    provider: available.provider.clone(),
 1440                })
 1441            }))
 1442    }
 1443    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1444        match (&self.tasks, &self.actions) {
 1445            (Some(tasks), Some(actions)) => {
 1446                if index < tasks.templates.len() {
 1447                    tasks
 1448                        .templates
 1449                        .get(index)
 1450                        .cloned()
 1451                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1452                } else {
 1453                    actions.get(index - tasks.templates.len()).map(|available| {
 1454                        CodeActionsItem::CodeAction {
 1455                            excerpt_id: available.excerpt_id,
 1456                            action: available.action.clone(),
 1457                            provider: available.provider.clone(),
 1458                        }
 1459                    })
 1460                }
 1461            }
 1462            (Some(tasks), None) => tasks
 1463                .templates
 1464                .get(index)
 1465                .cloned()
 1466                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1467            (None, Some(actions)) => {
 1468                actions
 1469                    .get(index)
 1470                    .map(|available| CodeActionsItem::CodeAction {
 1471                        excerpt_id: available.excerpt_id,
 1472                        action: available.action.clone(),
 1473                        provider: available.provider.clone(),
 1474                    })
 1475            }
 1476            (None, None) => None,
 1477        }
 1478    }
 1479}
 1480
 1481#[allow(clippy::large_enum_variant)]
 1482#[derive(Clone)]
 1483enum CodeActionsItem {
 1484    Task(TaskSourceKind, ResolvedTask),
 1485    CodeAction {
 1486        excerpt_id: ExcerptId,
 1487        action: CodeAction,
 1488        provider: Arc<dyn CodeActionProvider>,
 1489    },
 1490}
 1491
 1492impl CodeActionsItem {
 1493    fn as_task(&self) -> Option<&ResolvedTask> {
 1494        let Self::Task(_, task) = self else {
 1495            return None;
 1496        };
 1497        Some(task)
 1498    }
 1499    fn as_code_action(&self) -> Option<&CodeAction> {
 1500        let Self::CodeAction { action, .. } = self else {
 1501            return None;
 1502        };
 1503        Some(action)
 1504    }
 1505    fn label(&self) -> String {
 1506        match self {
 1507            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1508            Self::Task(_, task) => task.resolved_label.clone(),
 1509        }
 1510    }
 1511}
 1512
 1513struct CodeActionsMenu {
 1514    actions: CodeActionContents,
 1515    buffer: Model<Buffer>,
 1516    selected_item: usize,
 1517    scroll_handle: UniformListScrollHandle,
 1518    deployed_from_indicator: Option<DisplayRow>,
 1519}
 1520
 1521impl CodeActionsMenu {
 1522    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1523        self.selected_item = 0;
 1524        self.scroll_handle.scroll_to_item(self.selected_item);
 1525        cx.notify()
 1526    }
 1527
 1528    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1529        if self.selected_item > 0 {
 1530            self.selected_item -= 1;
 1531        } else {
 1532            self.selected_item = self.actions.len() - 1;
 1533        }
 1534        self.scroll_handle.scroll_to_item(self.selected_item);
 1535        cx.notify();
 1536    }
 1537
 1538    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1539        if self.selected_item + 1 < self.actions.len() {
 1540            self.selected_item += 1;
 1541        } else {
 1542            self.selected_item = 0;
 1543        }
 1544        self.scroll_handle.scroll_to_item(self.selected_item);
 1545        cx.notify();
 1546    }
 1547
 1548    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1549        self.selected_item = self.actions.len() - 1;
 1550        self.scroll_handle.scroll_to_item(self.selected_item);
 1551        cx.notify()
 1552    }
 1553
 1554    fn visible(&self) -> bool {
 1555        !self.actions.is_empty()
 1556    }
 1557
 1558    fn render(
 1559        &self,
 1560        cursor_position: DisplayPoint,
 1561        _style: &EditorStyle,
 1562        max_height: Pixels,
 1563        cx: &mut ViewContext<Editor>,
 1564    ) -> (ContextMenuOrigin, AnyElement) {
 1565        let actions = self.actions.clone();
 1566        let selected_item = self.selected_item;
 1567        let element = uniform_list(
 1568            cx.view().clone(),
 1569            "code_actions_menu",
 1570            self.actions.len(),
 1571            move |_this, range, cx| {
 1572                actions
 1573                    .iter()
 1574                    .skip(range.start)
 1575                    .take(range.end - range.start)
 1576                    .enumerate()
 1577                    .map(|(ix, action)| {
 1578                        let item_ix = range.start + ix;
 1579                        let selected = selected_item == item_ix;
 1580                        let colors = cx.theme().colors();
 1581                        div()
 1582                            .px_1()
 1583                            .rounded_md()
 1584                            .text_color(colors.text)
 1585                            .when(selected, |style| {
 1586                                style
 1587                                    .bg(colors.element_active)
 1588                                    .text_color(colors.text_accent)
 1589                            })
 1590                            .hover(|style| {
 1591                                style
 1592                                    .bg(colors.element_hover)
 1593                                    .text_color(colors.text_accent)
 1594                            })
 1595                            .whitespace_nowrap()
 1596                            .when_some(action.as_code_action(), |this, action| {
 1597                                this.on_mouse_down(
 1598                                    MouseButton::Left,
 1599                                    cx.listener(move |editor, _, cx| {
 1600                                        cx.stop_propagation();
 1601                                        if let Some(task) = editor.confirm_code_action(
 1602                                            &ConfirmCodeAction {
 1603                                                item_ix: Some(item_ix),
 1604                                            },
 1605                                            cx,
 1606                                        ) {
 1607                                            task.detach_and_log_err(cx)
 1608                                        }
 1609                                    }),
 1610                                )
 1611                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1612                                .child(SharedString::from(action.lsp_action.title.clone()))
 1613                            })
 1614                            .when_some(action.as_task(), |this, task| {
 1615                                this.on_mouse_down(
 1616                                    MouseButton::Left,
 1617                                    cx.listener(move |editor, _, cx| {
 1618                                        cx.stop_propagation();
 1619                                        if let Some(task) = editor.confirm_code_action(
 1620                                            &ConfirmCodeAction {
 1621                                                item_ix: Some(item_ix),
 1622                                            },
 1623                                            cx,
 1624                                        ) {
 1625                                            task.detach_and_log_err(cx)
 1626                                        }
 1627                                    }),
 1628                                )
 1629                                .child(SharedString::from(task.resolved_label.clone()))
 1630                            })
 1631                    })
 1632                    .collect()
 1633            },
 1634        )
 1635        .elevation_1(cx)
 1636        .p_1()
 1637        .max_h(max_height)
 1638        .occlude()
 1639        .track_scroll(self.scroll_handle.clone())
 1640        .with_width_from_item(
 1641            self.actions
 1642                .iter()
 1643                .enumerate()
 1644                .max_by_key(|(_, action)| match action {
 1645                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1646                    CodeActionsItem::CodeAction { action, .. } => {
 1647                        action.lsp_action.title.chars().count()
 1648                    }
 1649                })
 1650                .map(|(ix, _)| ix),
 1651        )
 1652        .with_sizing_behavior(ListSizingBehavior::Infer)
 1653        .into_any_element();
 1654
 1655        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1656            ContextMenuOrigin::GutterIndicator(row)
 1657        } else {
 1658            ContextMenuOrigin::EditorPoint(cursor_position)
 1659        };
 1660
 1661        (cursor_position, element)
 1662    }
 1663}
 1664
 1665#[derive(Debug)]
 1666struct ActiveDiagnosticGroup {
 1667    primary_range: Range<Anchor>,
 1668    primary_message: String,
 1669    group_id: usize,
 1670    blocks: HashMap<CustomBlockId, Diagnostic>,
 1671    is_valid: bool,
 1672}
 1673
 1674#[derive(Serialize, Deserialize, Clone, Debug)]
 1675pub struct ClipboardSelection {
 1676    pub len: usize,
 1677    pub is_entire_line: bool,
 1678    pub first_line_indent: u32,
 1679}
 1680
 1681#[derive(Debug)]
 1682pub(crate) struct NavigationData {
 1683    cursor_anchor: Anchor,
 1684    cursor_position: Point,
 1685    scroll_anchor: ScrollAnchor,
 1686    scroll_top_row: u32,
 1687}
 1688
 1689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1690pub enum GotoDefinitionKind {
 1691    Symbol,
 1692    Declaration,
 1693    Type,
 1694    Implementation,
 1695}
 1696
 1697#[derive(Debug, Clone)]
 1698enum InlayHintRefreshReason {
 1699    Toggle(bool),
 1700    SettingsChange(InlayHintSettings),
 1701    NewLinesShown,
 1702    BufferEdited(HashSet<Arc<Language>>),
 1703    RefreshRequested,
 1704    ExcerptsRemoved(Vec<ExcerptId>),
 1705}
 1706
 1707impl InlayHintRefreshReason {
 1708    fn description(&self) -> &'static str {
 1709        match self {
 1710            Self::Toggle(_) => "toggle",
 1711            Self::SettingsChange(_) => "settings change",
 1712            Self::NewLinesShown => "new lines shown",
 1713            Self::BufferEdited(_) => "buffer edited",
 1714            Self::RefreshRequested => "refresh requested",
 1715            Self::ExcerptsRemoved(_) => "excerpts removed",
 1716        }
 1717    }
 1718}
 1719
 1720pub(crate) struct FocusedBlock {
 1721    id: BlockId,
 1722    focus_handle: WeakFocusHandle,
 1723}
 1724
 1725impl Editor {
 1726    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1727        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1728        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1729        Self::new(
 1730            EditorMode::SingleLine { auto_width: false },
 1731            buffer,
 1732            None,
 1733            false,
 1734            cx,
 1735        )
 1736    }
 1737
 1738    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1739        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1740        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1741        Self::new(EditorMode::Full, buffer, None, false, cx)
 1742    }
 1743
 1744    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1745        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1746        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1747        Self::new(
 1748            EditorMode::SingleLine { auto_width: true },
 1749            buffer,
 1750            None,
 1751            false,
 1752            cx,
 1753        )
 1754    }
 1755
 1756    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1757        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1758        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1759        Self::new(
 1760            EditorMode::AutoHeight { max_lines },
 1761            buffer,
 1762            None,
 1763            false,
 1764            cx,
 1765        )
 1766    }
 1767
 1768    pub fn for_buffer(
 1769        buffer: Model<Buffer>,
 1770        project: Option<Model<Project>>,
 1771        cx: &mut ViewContext<Self>,
 1772    ) -> Self {
 1773        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1774        Self::new(EditorMode::Full, buffer, project, false, cx)
 1775    }
 1776
 1777    pub fn for_multibuffer(
 1778        buffer: Model<MultiBuffer>,
 1779        project: Option<Model<Project>>,
 1780        show_excerpt_controls: bool,
 1781        cx: &mut ViewContext<Self>,
 1782    ) -> Self {
 1783        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1784    }
 1785
 1786    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1787        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1788        let mut clone = Self::new(
 1789            self.mode,
 1790            self.buffer.clone(),
 1791            self.project.clone(),
 1792            show_excerpt_controls,
 1793            cx,
 1794        );
 1795        self.display_map.update(cx, |display_map, cx| {
 1796            let snapshot = display_map.snapshot(cx);
 1797            clone.display_map.update(cx, |display_map, cx| {
 1798                display_map.set_state(&snapshot, cx);
 1799            });
 1800        });
 1801        clone.selections.clone_state(&self.selections);
 1802        clone.scroll_manager.clone_state(&self.scroll_manager);
 1803        clone.searchable = self.searchable;
 1804        clone
 1805    }
 1806
 1807    pub fn new(
 1808        mode: EditorMode,
 1809        buffer: Model<MultiBuffer>,
 1810        project: Option<Model<Project>>,
 1811        show_excerpt_controls: bool,
 1812        cx: &mut ViewContext<Self>,
 1813    ) -> Self {
 1814        let style = cx.text_style();
 1815        let font_size = style.font_size.to_pixels(cx.rem_size());
 1816        let editor = cx.view().downgrade();
 1817        let fold_placeholder = FoldPlaceholder {
 1818            constrain_width: true,
 1819            render: Arc::new(move |fold_id, fold_range, cx| {
 1820                let editor = editor.clone();
 1821                div()
 1822                    .id(fold_id)
 1823                    .bg(cx.theme().colors().ghost_element_background)
 1824                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1825                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1826                    .rounded_sm()
 1827                    .size_full()
 1828                    .cursor_pointer()
 1829                    .child("")
 1830                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1831                    .on_click(move |_, cx| {
 1832                        editor
 1833                            .update(cx, |editor, cx| {
 1834                                editor.unfold_ranges(
 1835                                    [fold_range.start..fold_range.end],
 1836                                    true,
 1837                                    false,
 1838                                    cx,
 1839                                );
 1840                                cx.stop_propagation();
 1841                            })
 1842                            .ok();
 1843                    })
 1844                    .into_any()
 1845            }),
 1846            merge_adjacent: true,
 1847        };
 1848        let display_map = cx.new_model(|cx| {
 1849            DisplayMap::new(
 1850                buffer.clone(),
 1851                style.font(),
 1852                font_size,
 1853                None,
 1854                show_excerpt_controls,
 1855                FILE_HEADER_HEIGHT,
 1856                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1857                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1858                fold_placeholder,
 1859                cx,
 1860            )
 1861        });
 1862
 1863        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1864
 1865        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1866
 1867        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1868            .then(|| language_settings::SoftWrap::None);
 1869
 1870        let mut project_subscriptions = Vec::new();
 1871        if mode == EditorMode::Full {
 1872            if let Some(project) = project.as_ref() {
 1873                if buffer.read(cx).is_singleton() {
 1874                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1875                        cx.emit(EditorEvent::TitleChanged);
 1876                    }));
 1877                }
 1878                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1879                    if let project::Event::RefreshInlayHints = event {
 1880                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1881                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1882                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1883                            let focus_handle = editor.focus_handle(cx);
 1884                            if focus_handle.is_focused(cx) {
 1885                                let snapshot = buffer.read(cx).snapshot();
 1886                                for (range, snippet) in snippet_edits {
 1887                                    let editor_range =
 1888                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1889                                    editor
 1890                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1891                                        .ok();
 1892                                }
 1893                            }
 1894                        }
 1895                    }
 1896                }));
 1897                if let Some(task_inventory) = project
 1898                    .read(cx)
 1899                    .task_store()
 1900                    .read(cx)
 1901                    .task_inventory()
 1902                    .cloned()
 1903                {
 1904                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1905                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1906                    }));
 1907                }
 1908            }
 1909        }
 1910
 1911        let inlay_hint_settings = inlay_hint_settings(
 1912            selections.newest_anchor().head(),
 1913            &buffer.read(cx).snapshot(cx),
 1914            cx,
 1915        );
 1916        let focus_handle = cx.focus_handle();
 1917        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1918        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1919            .detach();
 1920        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1921            .detach();
 1922        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1923
 1924        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1925            Some(false)
 1926        } else {
 1927            None
 1928        };
 1929
 1930        let mut code_action_providers = Vec::new();
 1931        if let Some(project) = project.clone() {
 1932            code_action_providers.push(Arc::new(project) as Arc<_>);
 1933        }
 1934
 1935        let mut this = Self {
 1936            focus_handle,
 1937            show_cursor_when_unfocused: false,
 1938            last_focused_descendant: None,
 1939            buffer: buffer.clone(),
 1940            display_map: display_map.clone(),
 1941            selections,
 1942            scroll_manager: ScrollManager::new(cx),
 1943            columnar_selection_tail: None,
 1944            add_selections_state: None,
 1945            select_next_state: None,
 1946            select_prev_state: None,
 1947            selection_history: Default::default(),
 1948            autoclose_regions: Default::default(),
 1949            snippet_stack: Default::default(),
 1950            select_larger_syntax_node_stack: Vec::new(),
 1951            ime_transaction: Default::default(),
 1952            active_diagnostics: None,
 1953            soft_wrap_mode_override,
 1954            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1955            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1956            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1957            project,
 1958            blink_manager: blink_manager.clone(),
 1959            show_local_selections: true,
 1960            mode,
 1961            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1962            show_gutter: mode == EditorMode::Full,
 1963            show_line_numbers: None,
 1964            use_relative_line_numbers: None,
 1965            show_git_diff_gutter: None,
 1966            show_code_actions: None,
 1967            show_runnables: None,
 1968            show_wrap_guides: None,
 1969            show_indent_guides,
 1970            placeholder_text: None,
 1971            highlight_order: 0,
 1972            highlighted_rows: HashMap::default(),
 1973            background_highlights: Default::default(),
 1974            gutter_highlights: TreeMap::default(),
 1975            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1976            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1977            nav_history: None,
 1978            context_menu: RwLock::new(None),
 1979            mouse_context_menu: None,
 1980            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1981            completion_tasks: Default::default(),
 1982            signature_help_state: SignatureHelpState::default(),
 1983            auto_signature_help: None,
 1984            find_all_references_task_sources: Vec::new(),
 1985            next_completion_id: 0,
 1986            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1987            next_inlay_id: 0,
 1988            code_action_providers,
 1989            available_code_actions: Default::default(),
 1990            code_actions_task: Default::default(),
 1991            document_highlights_task: Default::default(),
 1992            linked_editing_range_task: Default::default(),
 1993            pending_rename: Default::default(),
 1994            searchable: true,
 1995            cursor_shape: EditorSettings::get_global(cx)
 1996                .cursor_shape
 1997                .unwrap_or_default(),
 1998            current_line_highlight: None,
 1999            autoindent_mode: Some(AutoindentMode::EachLine),
 2000            collapse_matches: false,
 2001            workspace: None,
 2002            input_enabled: true,
 2003            use_modal_editing: mode == EditorMode::Full,
 2004            read_only: false,
 2005            use_autoclose: true,
 2006            use_auto_surround: true,
 2007            auto_replace_emoji_shortcode: false,
 2008            leader_peer_id: None,
 2009            remote_id: None,
 2010            hover_state: Default::default(),
 2011            hovered_link_state: Default::default(),
 2012            inline_completion_provider: None,
 2013            active_inline_completion: None,
 2014            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2015            expanded_hunks: ExpandedHunks::default(),
 2016            gutter_hovered: false,
 2017            pixel_position_of_newest_cursor: None,
 2018            last_bounds: None,
 2019            expect_bounds_change: None,
 2020            gutter_dimensions: GutterDimensions::default(),
 2021            style: None,
 2022            show_cursor_names: false,
 2023            hovered_cursors: Default::default(),
 2024            next_editor_action_id: EditorActionId::default(),
 2025            editor_actions: Rc::default(),
 2026            show_inline_completions_override: None,
 2027            enable_inline_completions: true,
 2028            custom_context_menu: None,
 2029            show_git_blame_gutter: false,
 2030            show_git_blame_inline: false,
 2031            show_selection_menu: None,
 2032            show_git_blame_inline_delay_task: None,
 2033            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2034            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2035                .session
 2036                .restore_unsaved_buffers,
 2037            blame: None,
 2038            blame_subscription: None,
 2039            tasks: Default::default(),
 2040            _subscriptions: vec![
 2041                cx.observe(&buffer, Self::on_buffer_changed),
 2042                cx.subscribe(&buffer, Self::on_buffer_event),
 2043                cx.observe(&display_map, Self::on_display_map_changed),
 2044                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2045                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2046                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2047                cx.observe_window_activation(|editor, cx| {
 2048                    let active = cx.is_window_active();
 2049                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2050                        if active {
 2051                            blink_manager.enable(cx);
 2052                        } else {
 2053                            blink_manager.disable(cx);
 2054                        }
 2055                    });
 2056                }),
 2057            ],
 2058            tasks_update_task: None,
 2059            linked_edit_ranges: Default::default(),
 2060            previous_search_ranges: None,
 2061            breadcrumb_header: None,
 2062            focused_block: None,
 2063            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2064            addons: HashMap::default(),
 2065            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2066        };
 2067        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2068        this._subscriptions.extend(project_subscriptions);
 2069
 2070        this.end_selection(cx);
 2071        this.scroll_manager.show_scrollbar(cx);
 2072
 2073        if mode == EditorMode::Full {
 2074            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2075            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2076
 2077            if this.git_blame_inline_enabled {
 2078                this.git_blame_inline_enabled = true;
 2079                this.start_git_blame_inline(false, cx);
 2080            }
 2081        }
 2082
 2083        this.report_editor_event("open", None, cx);
 2084        this
 2085    }
 2086
 2087    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2088        self.mouse_context_menu
 2089            .as_ref()
 2090            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2091    }
 2092
 2093    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2094        let mut key_context = KeyContext::new_with_defaults();
 2095        key_context.add("Editor");
 2096        let mode = match self.mode {
 2097            EditorMode::SingleLine { .. } => "single_line",
 2098            EditorMode::AutoHeight { .. } => "auto_height",
 2099            EditorMode::Full => "full",
 2100        };
 2101
 2102        if EditorSettings::jupyter_enabled(cx) {
 2103            key_context.add("jupyter");
 2104        }
 2105
 2106        key_context.set("mode", mode);
 2107        if self.pending_rename.is_some() {
 2108            key_context.add("renaming");
 2109        }
 2110        if self.context_menu_visible() {
 2111            match self.context_menu.read().as_ref() {
 2112                Some(ContextMenu::Completions(_)) => {
 2113                    key_context.add("menu");
 2114                    key_context.add("showing_completions")
 2115                }
 2116                Some(ContextMenu::CodeActions(_)) => {
 2117                    key_context.add("menu");
 2118                    key_context.add("showing_code_actions")
 2119                }
 2120                None => {}
 2121            }
 2122        }
 2123
 2124        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2125        if !self.focus_handle(cx).contains_focused(cx)
 2126            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2127        {
 2128            for addon in self.addons.values() {
 2129                addon.extend_key_context(&mut key_context, cx)
 2130            }
 2131        }
 2132
 2133        if let Some(extension) = self
 2134            .buffer
 2135            .read(cx)
 2136            .as_singleton()
 2137            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2138        {
 2139            key_context.set("extension", extension.to_string());
 2140        }
 2141
 2142        if self.has_active_inline_completion(cx) {
 2143            key_context.add("copilot_suggestion");
 2144            key_context.add("inline_completion");
 2145        }
 2146
 2147        key_context
 2148    }
 2149
 2150    pub fn new_file(
 2151        workspace: &mut Workspace,
 2152        _: &workspace::NewFile,
 2153        cx: &mut ViewContext<Workspace>,
 2154    ) {
 2155        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2156            "Failed to create buffer",
 2157            cx,
 2158            |e, _| match e.error_code() {
 2159                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2160                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2161                e.error_tag("required").unwrap_or("the latest version")
 2162            )),
 2163                _ => None,
 2164            },
 2165        );
 2166    }
 2167
 2168    pub fn new_in_workspace(
 2169        workspace: &mut Workspace,
 2170        cx: &mut ViewContext<Workspace>,
 2171    ) -> Task<Result<View<Editor>>> {
 2172        let project = workspace.project().clone();
 2173        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2174
 2175        cx.spawn(|workspace, mut cx| async move {
 2176            let buffer = create.await?;
 2177            workspace.update(&mut cx, |workspace, cx| {
 2178                let editor =
 2179                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2180                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2181                editor
 2182            })
 2183        })
 2184    }
 2185
 2186    fn new_file_vertical(
 2187        workspace: &mut Workspace,
 2188        _: &workspace::NewFileSplitVertical,
 2189        cx: &mut ViewContext<Workspace>,
 2190    ) {
 2191        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2192    }
 2193
 2194    fn new_file_horizontal(
 2195        workspace: &mut Workspace,
 2196        _: &workspace::NewFileSplitHorizontal,
 2197        cx: &mut ViewContext<Workspace>,
 2198    ) {
 2199        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2200    }
 2201
 2202    fn new_file_in_direction(
 2203        workspace: &mut Workspace,
 2204        direction: SplitDirection,
 2205        cx: &mut ViewContext<Workspace>,
 2206    ) {
 2207        let project = workspace.project().clone();
 2208        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2209
 2210        cx.spawn(|workspace, mut cx| async move {
 2211            let buffer = create.await?;
 2212            workspace.update(&mut cx, move |workspace, cx| {
 2213                workspace.split_item(
 2214                    direction,
 2215                    Box::new(
 2216                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2217                    ),
 2218                    cx,
 2219                )
 2220            })?;
 2221            anyhow::Ok(())
 2222        })
 2223        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2224            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2225                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2226                e.error_tag("required").unwrap_or("the latest version")
 2227            )),
 2228            _ => None,
 2229        });
 2230    }
 2231
 2232    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2233        self.leader_peer_id
 2234    }
 2235
 2236    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2237        &self.buffer
 2238    }
 2239
 2240    pub fn workspace(&self) -> Option<View<Workspace>> {
 2241        self.workspace.as_ref()?.0.upgrade()
 2242    }
 2243
 2244    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2245        self.buffer().read(cx).title(cx)
 2246    }
 2247
 2248    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2249        let git_blame_gutter_max_author_length = self
 2250            .render_git_blame_gutter(cx)
 2251            .then(|| {
 2252                if let Some(blame) = self.blame.as_ref() {
 2253                    let max_author_length =
 2254                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2255                    Some(max_author_length)
 2256                } else {
 2257                    None
 2258                }
 2259            })
 2260            .flatten();
 2261
 2262        EditorSnapshot {
 2263            mode: self.mode,
 2264            show_gutter: self.show_gutter,
 2265            show_line_numbers: self.show_line_numbers,
 2266            show_git_diff_gutter: self.show_git_diff_gutter,
 2267            show_code_actions: self.show_code_actions,
 2268            show_runnables: self.show_runnables,
 2269            git_blame_gutter_max_author_length,
 2270            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2271            scroll_anchor: self.scroll_manager.anchor(),
 2272            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2273            placeholder_text: self.placeholder_text.clone(),
 2274            is_focused: self.focus_handle.is_focused(cx),
 2275            current_line_highlight: self
 2276                .current_line_highlight
 2277                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2278            gutter_hovered: self.gutter_hovered,
 2279        }
 2280    }
 2281
 2282    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2283        self.buffer.read(cx).language_at(point, cx)
 2284    }
 2285
 2286    pub fn file_at<T: ToOffset>(
 2287        &self,
 2288        point: T,
 2289        cx: &AppContext,
 2290    ) -> Option<Arc<dyn language::File>> {
 2291        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2292    }
 2293
 2294    pub fn active_excerpt(
 2295        &self,
 2296        cx: &AppContext,
 2297    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2298        self.buffer
 2299            .read(cx)
 2300            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2301    }
 2302
 2303    pub fn mode(&self) -> EditorMode {
 2304        self.mode
 2305    }
 2306
 2307    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2308        self.collaboration_hub.as_deref()
 2309    }
 2310
 2311    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2312        self.collaboration_hub = Some(hub);
 2313    }
 2314
 2315    pub fn set_custom_context_menu(
 2316        &mut self,
 2317        f: impl 'static
 2318            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2319    ) {
 2320        self.custom_context_menu = Some(Box::new(f))
 2321    }
 2322
 2323    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2324        self.completion_provider = provider;
 2325    }
 2326
 2327    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2328        self.semantics_provider.clone()
 2329    }
 2330
 2331    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2332        self.semantics_provider = provider;
 2333    }
 2334
 2335    pub fn set_inline_completion_provider<T>(
 2336        &mut self,
 2337        provider: Option<Model<T>>,
 2338        cx: &mut ViewContext<Self>,
 2339    ) where
 2340        T: InlineCompletionProvider,
 2341    {
 2342        self.inline_completion_provider =
 2343            provider.map(|provider| RegisteredInlineCompletionProvider {
 2344                _subscription: cx.observe(&provider, |this, _, cx| {
 2345                    if this.focus_handle.is_focused(cx) {
 2346                        this.update_visible_inline_completion(cx);
 2347                    }
 2348                }),
 2349                provider: Arc::new(provider),
 2350            });
 2351        self.refresh_inline_completion(false, false, cx);
 2352    }
 2353
 2354    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2355        self.placeholder_text.as_deref()
 2356    }
 2357
 2358    pub fn set_placeholder_text(
 2359        &mut self,
 2360        placeholder_text: impl Into<Arc<str>>,
 2361        cx: &mut ViewContext<Self>,
 2362    ) {
 2363        let placeholder_text = Some(placeholder_text.into());
 2364        if self.placeholder_text != placeholder_text {
 2365            self.placeholder_text = placeholder_text;
 2366            cx.notify();
 2367        }
 2368    }
 2369
 2370    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2371        self.cursor_shape = cursor_shape;
 2372
 2373        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2374        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2375
 2376        cx.notify();
 2377    }
 2378
 2379    pub fn set_current_line_highlight(
 2380        &mut self,
 2381        current_line_highlight: Option<CurrentLineHighlight>,
 2382    ) {
 2383        self.current_line_highlight = current_line_highlight;
 2384    }
 2385
 2386    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2387        self.collapse_matches = collapse_matches;
 2388    }
 2389
 2390    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2391        if self.collapse_matches {
 2392            return range.start..range.start;
 2393        }
 2394        range.clone()
 2395    }
 2396
 2397    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2398        if self.display_map.read(cx).clip_at_line_ends != clip {
 2399            self.display_map
 2400                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2401        }
 2402    }
 2403
 2404    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2405        self.input_enabled = input_enabled;
 2406    }
 2407
 2408    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2409        self.enable_inline_completions = enabled;
 2410    }
 2411
 2412    pub fn set_autoindent(&mut self, autoindent: bool) {
 2413        if autoindent {
 2414            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2415        } else {
 2416            self.autoindent_mode = None;
 2417        }
 2418    }
 2419
 2420    pub fn read_only(&self, cx: &AppContext) -> bool {
 2421        self.read_only || self.buffer.read(cx).read_only()
 2422    }
 2423
 2424    pub fn set_read_only(&mut self, read_only: bool) {
 2425        self.read_only = read_only;
 2426    }
 2427
 2428    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2429        self.use_autoclose = autoclose;
 2430    }
 2431
 2432    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2433        self.use_auto_surround = auto_surround;
 2434    }
 2435
 2436    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2437        self.auto_replace_emoji_shortcode = auto_replace;
 2438    }
 2439
 2440    pub fn toggle_inline_completions(
 2441        &mut self,
 2442        _: &ToggleInlineCompletions,
 2443        cx: &mut ViewContext<Self>,
 2444    ) {
 2445        if self.show_inline_completions_override.is_some() {
 2446            self.set_show_inline_completions(None, cx);
 2447        } else {
 2448            let cursor = self.selections.newest_anchor().head();
 2449            if let Some((buffer, cursor_buffer_position)) =
 2450                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2451            {
 2452                let show_inline_completions =
 2453                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2454                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2455            }
 2456        }
 2457    }
 2458
 2459    pub fn set_show_inline_completions(
 2460        &mut self,
 2461        show_inline_completions: Option<bool>,
 2462        cx: &mut ViewContext<Self>,
 2463    ) {
 2464        self.show_inline_completions_override = show_inline_completions;
 2465        self.refresh_inline_completion(false, true, cx);
 2466    }
 2467
 2468    fn should_show_inline_completions(
 2469        &self,
 2470        buffer: &Model<Buffer>,
 2471        buffer_position: language::Anchor,
 2472        cx: &AppContext,
 2473    ) -> bool {
 2474        if let Some(provider) = self.inline_completion_provider() {
 2475            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2476                show_inline_completions
 2477            } else {
 2478                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2479            }
 2480        } else {
 2481            false
 2482        }
 2483    }
 2484
 2485    pub fn set_use_modal_editing(&mut self, to: bool) {
 2486        self.use_modal_editing = to;
 2487    }
 2488
 2489    pub fn use_modal_editing(&self) -> bool {
 2490        self.use_modal_editing
 2491    }
 2492
 2493    fn selections_did_change(
 2494        &mut self,
 2495        local: bool,
 2496        old_cursor_position: &Anchor,
 2497        show_completions: bool,
 2498        cx: &mut ViewContext<Self>,
 2499    ) {
 2500        cx.invalidate_character_coordinates();
 2501
 2502        // Copy selections to primary selection buffer
 2503        #[cfg(target_os = "linux")]
 2504        if local {
 2505            let selections = self.selections.all::<usize>(cx);
 2506            let buffer_handle = self.buffer.read(cx).read(cx);
 2507
 2508            let mut text = String::new();
 2509            for (index, selection) in selections.iter().enumerate() {
 2510                let text_for_selection = buffer_handle
 2511                    .text_for_range(selection.start..selection.end)
 2512                    .collect::<String>();
 2513
 2514                text.push_str(&text_for_selection);
 2515                if index != selections.len() - 1 {
 2516                    text.push('\n');
 2517                }
 2518            }
 2519
 2520            if !text.is_empty() {
 2521                cx.write_to_primary(ClipboardItem::new_string(text));
 2522            }
 2523        }
 2524
 2525        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2526            self.buffer.update(cx, |buffer, cx| {
 2527                buffer.set_active_selections(
 2528                    &self.selections.disjoint_anchors(),
 2529                    self.selections.line_mode,
 2530                    self.cursor_shape,
 2531                    cx,
 2532                )
 2533            });
 2534        }
 2535        let display_map = self
 2536            .display_map
 2537            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2538        let buffer = &display_map.buffer_snapshot;
 2539        self.add_selections_state = None;
 2540        self.select_next_state = None;
 2541        self.select_prev_state = None;
 2542        self.select_larger_syntax_node_stack.clear();
 2543        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2544        self.snippet_stack
 2545            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2546        self.take_rename(false, cx);
 2547
 2548        let new_cursor_position = self.selections.newest_anchor().head();
 2549
 2550        self.push_to_nav_history(
 2551            *old_cursor_position,
 2552            Some(new_cursor_position.to_point(buffer)),
 2553            cx,
 2554        );
 2555
 2556        if local {
 2557            let new_cursor_position = self.selections.newest_anchor().head();
 2558            let mut context_menu = self.context_menu.write();
 2559            let completion_menu = match context_menu.as_ref() {
 2560                Some(ContextMenu::Completions(menu)) => Some(menu),
 2561
 2562                _ => {
 2563                    *context_menu = None;
 2564                    None
 2565                }
 2566            };
 2567
 2568            if let Some(completion_menu) = completion_menu {
 2569                let cursor_position = new_cursor_position.to_offset(buffer);
 2570                let (word_range, kind) =
 2571                    buffer.surrounding_word(completion_menu.initial_position, true);
 2572                if kind == Some(CharKind::Word)
 2573                    && word_range.to_inclusive().contains(&cursor_position)
 2574                {
 2575                    let mut completion_menu = completion_menu.clone();
 2576                    drop(context_menu);
 2577
 2578                    let query = Self::completion_query(buffer, cursor_position);
 2579                    cx.spawn(move |this, mut cx| async move {
 2580                        completion_menu
 2581                            .filter(query.as_deref(), cx.background_executor().clone())
 2582                            .await;
 2583
 2584                        this.update(&mut cx, |this, cx| {
 2585                            let mut context_menu = this.context_menu.write();
 2586                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2587                                return;
 2588                            };
 2589
 2590                            if menu.id > completion_menu.id {
 2591                                return;
 2592                            }
 2593
 2594                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2595                            drop(context_menu);
 2596                            cx.notify();
 2597                        })
 2598                    })
 2599                    .detach();
 2600
 2601                    if show_completions {
 2602                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2603                    }
 2604                } else {
 2605                    drop(context_menu);
 2606                    self.hide_context_menu(cx);
 2607                }
 2608            } else {
 2609                drop(context_menu);
 2610            }
 2611
 2612            hide_hover(self, cx);
 2613
 2614            if old_cursor_position.to_display_point(&display_map).row()
 2615                != new_cursor_position.to_display_point(&display_map).row()
 2616            {
 2617                self.available_code_actions.take();
 2618            }
 2619            self.refresh_code_actions(cx);
 2620            self.refresh_document_highlights(cx);
 2621            refresh_matching_bracket_highlights(self, cx);
 2622            self.discard_inline_completion(false, cx);
 2623            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2624            if self.git_blame_inline_enabled {
 2625                self.start_inline_blame_timer(cx);
 2626            }
 2627        }
 2628
 2629        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2630        cx.emit(EditorEvent::SelectionsChanged { local });
 2631
 2632        if self.selections.disjoint_anchors().len() == 1 {
 2633            cx.emit(SearchEvent::ActiveMatchChanged)
 2634        }
 2635        cx.notify();
 2636    }
 2637
 2638    pub fn change_selections<R>(
 2639        &mut self,
 2640        autoscroll: Option<Autoscroll>,
 2641        cx: &mut ViewContext<Self>,
 2642        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2643    ) -> R {
 2644        self.change_selections_inner(autoscroll, true, cx, change)
 2645    }
 2646
 2647    pub fn change_selections_inner<R>(
 2648        &mut self,
 2649        autoscroll: Option<Autoscroll>,
 2650        request_completions: bool,
 2651        cx: &mut ViewContext<Self>,
 2652        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2653    ) -> R {
 2654        let old_cursor_position = self.selections.newest_anchor().head();
 2655        self.push_to_selection_history();
 2656
 2657        let (changed, result) = self.selections.change_with(cx, change);
 2658
 2659        if changed {
 2660            if let Some(autoscroll) = autoscroll {
 2661                self.request_autoscroll(autoscroll, cx);
 2662            }
 2663            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2664
 2665            if self.should_open_signature_help_automatically(
 2666                &old_cursor_position,
 2667                self.signature_help_state.backspace_pressed(),
 2668                cx,
 2669            ) {
 2670                self.show_signature_help(&ShowSignatureHelp, cx);
 2671            }
 2672            self.signature_help_state.set_backspace_pressed(false);
 2673        }
 2674
 2675        result
 2676    }
 2677
 2678    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2679    where
 2680        I: IntoIterator<Item = (Range<S>, T)>,
 2681        S: ToOffset,
 2682        T: Into<Arc<str>>,
 2683    {
 2684        if self.read_only(cx) {
 2685            return;
 2686        }
 2687
 2688        self.buffer
 2689            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2690    }
 2691
 2692    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2693    where
 2694        I: IntoIterator<Item = (Range<S>, T)>,
 2695        S: ToOffset,
 2696        T: Into<Arc<str>>,
 2697    {
 2698        if self.read_only(cx) {
 2699            return;
 2700        }
 2701
 2702        self.buffer.update(cx, |buffer, cx| {
 2703            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2704        });
 2705    }
 2706
 2707    pub fn edit_with_block_indent<I, S, T>(
 2708        &mut self,
 2709        edits: I,
 2710        original_indent_columns: Vec<u32>,
 2711        cx: &mut ViewContext<Self>,
 2712    ) where
 2713        I: IntoIterator<Item = (Range<S>, T)>,
 2714        S: ToOffset,
 2715        T: Into<Arc<str>>,
 2716    {
 2717        if self.read_only(cx) {
 2718            return;
 2719        }
 2720
 2721        self.buffer.update(cx, |buffer, cx| {
 2722            buffer.edit(
 2723                edits,
 2724                Some(AutoindentMode::Block {
 2725                    original_indent_columns,
 2726                }),
 2727                cx,
 2728            )
 2729        });
 2730    }
 2731
 2732    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2733        self.hide_context_menu(cx);
 2734
 2735        match phase {
 2736            SelectPhase::Begin {
 2737                position,
 2738                add,
 2739                click_count,
 2740            } => self.begin_selection(position, add, click_count, cx),
 2741            SelectPhase::BeginColumnar {
 2742                position,
 2743                goal_column,
 2744                reset,
 2745            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2746            SelectPhase::Extend {
 2747                position,
 2748                click_count,
 2749            } => self.extend_selection(position, click_count, cx),
 2750            SelectPhase::Update {
 2751                position,
 2752                goal_column,
 2753                scroll_delta,
 2754            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2755            SelectPhase::End => self.end_selection(cx),
 2756        }
 2757    }
 2758
 2759    fn extend_selection(
 2760        &mut self,
 2761        position: DisplayPoint,
 2762        click_count: usize,
 2763        cx: &mut ViewContext<Self>,
 2764    ) {
 2765        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2766        let tail = self.selections.newest::<usize>(cx).tail();
 2767        self.begin_selection(position, false, click_count, cx);
 2768
 2769        let position = position.to_offset(&display_map, Bias::Left);
 2770        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2771
 2772        let mut pending_selection = self
 2773            .selections
 2774            .pending_anchor()
 2775            .expect("extend_selection not called with pending selection");
 2776        if position >= tail {
 2777            pending_selection.start = tail_anchor;
 2778        } else {
 2779            pending_selection.end = tail_anchor;
 2780            pending_selection.reversed = true;
 2781        }
 2782
 2783        let mut pending_mode = self.selections.pending_mode().unwrap();
 2784        match &mut pending_mode {
 2785            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2786            _ => {}
 2787        }
 2788
 2789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2790            s.set_pending(pending_selection, pending_mode)
 2791        });
 2792    }
 2793
 2794    fn begin_selection(
 2795        &mut self,
 2796        position: DisplayPoint,
 2797        add: bool,
 2798        click_count: usize,
 2799        cx: &mut ViewContext<Self>,
 2800    ) {
 2801        if !self.focus_handle.is_focused(cx) {
 2802            self.last_focused_descendant = None;
 2803            cx.focus(&self.focus_handle);
 2804        }
 2805
 2806        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2807        let buffer = &display_map.buffer_snapshot;
 2808        let newest_selection = self.selections.newest_anchor().clone();
 2809        let position = display_map.clip_point(position, Bias::Left);
 2810
 2811        let start;
 2812        let end;
 2813        let mode;
 2814        let auto_scroll;
 2815        match click_count {
 2816            1 => {
 2817                start = buffer.anchor_before(position.to_point(&display_map));
 2818                end = start;
 2819                mode = SelectMode::Character;
 2820                auto_scroll = true;
 2821            }
 2822            2 => {
 2823                let range = movement::surrounding_word(&display_map, position);
 2824                start = buffer.anchor_before(range.start.to_point(&display_map));
 2825                end = buffer.anchor_before(range.end.to_point(&display_map));
 2826                mode = SelectMode::Word(start..end);
 2827                auto_scroll = true;
 2828            }
 2829            3 => {
 2830                let position = display_map
 2831                    .clip_point(position, Bias::Left)
 2832                    .to_point(&display_map);
 2833                let line_start = display_map.prev_line_boundary(position).0;
 2834                let next_line_start = buffer.clip_point(
 2835                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2836                    Bias::Left,
 2837                );
 2838                start = buffer.anchor_before(line_start);
 2839                end = buffer.anchor_before(next_line_start);
 2840                mode = SelectMode::Line(start..end);
 2841                auto_scroll = true;
 2842            }
 2843            _ => {
 2844                start = buffer.anchor_before(0);
 2845                end = buffer.anchor_before(buffer.len());
 2846                mode = SelectMode::All;
 2847                auto_scroll = false;
 2848            }
 2849        }
 2850
 2851        let point_to_delete: Option<usize> = {
 2852            let selected_points: Vec<Selection<Point>> =
 2853                self.selections.disjoint_in_range(start..end, cx);
 2854
 2855            if !add || click_count > 1 {
 2856                None
 2857            } else if !selected_points.is_empty() {
 2858                Some(selected_points[0].id)
 2859            } else {
 2860                let clicked_point_already_selected =
 2861                    self.selections.disjoint.iter().find(|selection| {
 2862                        selection.start.to_point(buffer) == start.to_point(buffer)
 2863                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2864                    });
 2865
 2866                clicked_point_already_selected.map(|selection| selection.id)
 2867            }
 2868        };
 2869
 2870        let selections_count = self.selections.count();
 2871
 2872        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2873            if let Some(point_to_delete) = point_to_delete {
 2874                s.delete(point_to_delete);
 2875
 2876                if selections_count == 1 {
 2877                    s.set_pending_anchor_range(start..end, mode);
 2878                }
 2879            } else {
 2880                if !add {
 2881                    s.clear_disjoint();
 2882                } else if click_count > 1 {
 2883                    s.delete(newest_selection.id)
 2884                }
 2885
 2886                s.set_pending_anchor_range(start..end, mode);
 2887            }
 2888        });
 2889    }
 2890
 2891    fn begin_columnar_selection(
 2892        &mut self,
 2893        position: DisplayPoint,
 2894        goal_column: u32,
 2895        reset: bool,
 2896        cx: &mut ViewContext<Self>,
 2897    ) {
 2898        if !self.focus_handle.is_focused(cx) {
 2899            self.last_focused_descendant = None;
 2900            cx.focus(&self.focus_handle);
 2901        }
 2902
 2903        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2904
 2905        if reset {
 2906            let pointer_position = display_map
 2907                .buffer_snapshot
 2908                .anchor_before(position.to_point(&display_map));
 2909
 2910            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2911                s.clear_disjoint();
 2912                s.set_pending_anchor_range(
 2913                    pointer_position..pointer_position,
 2914                    SelectMode::Character,
 2915                );
 2916            });
 2917        }
 2918
 2919        let tail = self.selections.newest::<Point>(cx).tail();
 2920        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2921
 2922        if !reset {
 2923            self.select_columns(
 2924                tail.to_display_point(&display_map),
 2925                position,
 2926                goal_column,
 2927                &display_map,
 2928                cx,
 2929            );
 2930        }
 2931    }
 2932
 2933    fn update_selection(
 2934        &mut self,
 2935        position: DisplayPoint,
 2936        goal_column: u32,
 2937        scroll_delta: gpui::Point<f32>,
 2938        cx: &mut ViewContext<Self>,
 2939    ) {
 2940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2941
 2942        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2943            let tail = tail.to_display_point(&display_map);
 2944            self.select_columns(tail, position, goal_column, &display_map, cx);
 2945        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2946            let buffer = self.buffer.read(cx).snapshot(cx);
 2947            let head;
 2948            let tail;
 2949            let mode = self.selections.pending_mode().unwrap();
 2950            match &mode {
 2951                SelectMode::Character => {
 2952                    head = position.to_point(&display_map);
 2953                    tail = pending.tail().to_point(&buffer);
 2954                }
 2955                SelectMode::Word(original_range) => {
 2956                    let original_display_range = original_range.start.to_display_point(&display_map)
 2957                        ..original_range.end.to_display_point(&display_map);
 2958                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2959                        ..original_display_range.end.to_point(&display_map);
 2960                    if movement::is_inside_word(&display_map, position)
 2961                        || original_display_range.contains(&position)
 2962                    {
 2963                        let word_range = movement::surrounding_word(&display_map, position);
 2964                        if word_range.start < original_display_range.start {
 2965                            head = word_range.start.to_point(&display_map);
 2966                        } else {
 2967                            head = word_range.end.to_point(&display_map);
 2968                        }
 2969                    } else {
 2970                        head = position.to_point(&display_map);
 2971                    }
 2972
 2973                    if head <= original_buffer_range.start {
 2974                        tail = original_buffer_range.end;
 2975                    } else {
 2976                        tail = original_buffer_range.start;
 2977                    }
 2978                }
 2979                SelectMode::Line(original_range) => {
 2980                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2981
 2982                    let position = display_map
 2983                        .clip_point(position, Bias::Left)
 2984                        .to_point(&display_map);
 2985                    let line_start = display_map.prev_line_boundary(position).0;
 2986                    let next_line_start = buffer.clip_point(
 2987                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2988                        Bias::Left,
 2989                    );
 2990
 2991                    if line_start < original_range.start {
 2992                        head = line_start
 2993                    } else {
 2994                        head = next_line_start
 2995                    }
 2996
 2997                    if head <= original_range.start {
 2998                        tail = original_range.end;
 2999                    } else {
 3000                        tail = original_range.start;
 3001                    }
 3002                }
 3003                SelectMode::All => {
 3004                    return;
 3005                }
 3006            };
 3007
 3008            if head < tail {
 3009                pending.start = buffer.anchor_before(head);
 3010                pending.end = buffer.anchor_before(tail);
 3011                pending.reversed = true;
 3012            } else {
 3013                pending.start = buffer.anchor_before(tail);
 3014                pending.end = buffer.anchor_before(head);
 3015                pending.reversed = false;
 3016            }
 3017
 3018            self.change_selections(None, cx, |s| {
 3019                s.set_pending(pending, mode);
 3020            });
 3021        } else {
 3022            log::error!("update_selection dispatched with no pending selection");
 3023            return;
 3024        }
 3025
 3026        self.apply_scroll_delta(scroll_delta, cx);
 3027        cx.notify();
 3028    }
 3029
 3030    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3031        self.columnar_selection_tail.take();
 3032        if self.selections.pending_anchor().is_some() {
 3033            let selections = self.selections.all::<usize>(cx);
 3034            self.change_selections(None, cx, |s| {
 3035                s.select(selections);
 3036                s.clear_pending();
 3037            });
 3038        }
 3039    }
 3040
 3041    fn select_columns(
 3042        &mut self,
 3043        tail: DisplayPoint,
 3044        head: DisplayPoint,
 3045        goal_column: u32,
 3046        display_map: &DisplaySnapshot,
 3047        cx: &mut ViewContext<Self>,
 3048    ) {
 3049        let start_row = cmp::min(tail.row(), head.row());
 3050        let end_row = cmp::max(tail.row(), head.row());
 3051        let start_column = cmp::min(tail.column(), goal_column);
 3052        let end_column = cmp::max(tail.column(), goal_column);
 3053        let reversed = start_column < tail.column();
 3054
 3055        let selection_ranges = (start_row.0..=end_row.0)
 3056            .map(DisplayRow)
 3057            .filter_map(|row| {
 3058                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3059                    let start = display_map
 3060                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3061                        .to_point(display_map);
 3062                    let end = display_map
 3063                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3064                        .to_point(display_map);
 3065                    if reversed {
 3066                        Some(end..start)
 3067                    } else {
 3068                        Some(start..end)
 3069                    }
 3070                } else {
 3071                    None
 3072                }
 3073            })
 3074            .collect::<Vec<_>>();
 3075
 3076        self.change_selections(None, cx, |s| {
 3077            s.select_ranges(selection_ranges);
 3078        });
 3079        cx.notify();
 3080    }
 3081
 3082    pub fn has_pending_nonempty_selection(&self) -> bool {
 3083        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3084            Some(Selection { start, end, .. }) => start != end,
 3085            None => false,
 3086        };
 3087
 3088        pending_nonempty_selection
 3089            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3090    }
 3091
 3092    pub fn has_pending_selection(&self) -> bool {
 3093        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3094    }
 3095
 3096    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3097        if self.clear_expanded_diff_hunks(cx) {
 3098            cx.notify();
 3099            return;
 3100        }
 3101        if self.dismiss_menus_and_popups(true, cx) {
 3102            return;
 3103        }
 3104
 3105        if self.mode == EditorMode::Full
 3106            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3107        {
 3108            return;
 3109        }
 3110
 3111        cx.propagate();
 3112    }
 3113
 3114    pub fn dismiss_menus_and_popups(
 3115        &mut self,
 3116        should_report_inline_completion_event: bool,
 3117        cx: &mut ViewContext<Self>,
 3118    ) -> bool {
 3119        if self.take_rename(false, cx).is_some() {
 3120            return true;
 3121        }
 3122
 3123        if hide_hover(self, cx) {
 3124            return true;
 3125        }
 3126
 3127        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3128            return true;
 3129        }
 3130
 3131        if self.hide_context_menu(cx).is_some() {
 3132            return true;
 3133        }
 3134
 3135        if self.mouse_context_menu.take().is_some() {
 3136            return true;
 3137        }
 3138
 3139        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3140            return true;
 3141        }
 3142
 3143        if self.snippet_stack.pop().is_some() {
 3144            return true;
 3145        }
 3146
 3147        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3148            self.dismiss_diagnostics(cx);
 3149            return true;
 3150        }
 3151
 3152        false
 3153    }
 3154
 3155    fn linked_editing_ranges_for(
 3156        &self,
 3157        selection: Range<text::Anchor>,
 3158        cx: &AppContext,
 3159    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3160        if self.linked_edit_ranges.is_empty() {
 3161            return None;
 3162        }
 3163        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3164            selection.end.buffer_id.and_then(|end_buffer_id| {
 3165                if selection.start.buffer_id != Some(end_buffer_id) {
 3166                    return None;
 3167                }
 3168                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3169                let snapshot = buffer.read(cx).snapshot();
 3170                self.linked_edit_ranges
 3171                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3172                    .map(|ranges| (ranges, snapshot, buffer))
 3173            })?;
 3174        use text::ToOffset as TO;
 3175        // find offset from the start of current range to current cursor position
 3176        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3177
 3178        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3179        let start_difference = start_offset - start_byte_offset;
 3180        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3181        let end_difference = end_offset - start_byte_offset;
 3182        // Current range has associated linked ranges.
 3183        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3184        for range in linked_ranges.iter() {
 3185            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3186            let end_offset = start_offset + end_difference;
 3187            let start_offset = start_offset + start_difference;
 3188            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3189                continue;
 3190            }
 3191            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3192                if s.start.buffer_id != selection.start.buffer_id
 3193                    || s.end.buffer_id != selection.end.buffer_id
 3194                {
 3195                    return false;
 3196                }
 3197                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3198                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3199            }) {
 3200                continue;
 3201            }
 3202            let start = buffer_snapshot.anchor_after(start_offset);
 3203            let end = buffer_snapshot.anchor_after(end_offset);
 3204            linked_edits
 3205                .entry(buffer.clone())
 3206                .or_default()
 3207                .push(start..end);
 3208        }
 3209        Some(linked_edits)
 3210    }
 3211
 3212    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3213        let text: Arc<str> = text.into();
 3214
 3215        if self.read_only(cx) {
 3216            return;
 3217        }
 3218
 3219        let selections = self.selections.all_adjusted(cx);
 3220        let mut bracket_inserted = false;
 3221        let mut edits = Vec::new();
 3222        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3223        let mut new_selections = Vec::with_capacity(selections.len());
 3224        let mut new_autoclose_regions = Vec::new();
 3225        let snapshot = self.buffer.read(cx).read(cx);
 3226
 3227        for (selection, autoclose_region) in
 3228            self.selections_with_autoclose_regions(selections, &snapshot)
 3229        {
 3230            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3231                // Determine if the inserted text matches the opening or closing
 3232                // bracket of any of this language's bracket pairs.
 3233                let mut bracket_pair = None;
 3234                let mut is_bracket_pair_start = false;
 3235                let mut is_bracket_pair_end = false;
 3236                if !text.is_empty() {
 3237                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3238                    //  and they are removing the character that triggered IME popup.
 3239                    for (pair, enabled) in scope.brackets() {
 3240                        if !pair.close && !pair.surround {
 3241                            continue;
 3242                        }
 3243
 3244                        if enabled && pair.start.ends_with(text.as_ref()) {
 3245                            bracket_pair = Some(pair.clone());
 3246                            is_bracket_pair_start = true;
 3247                            break;
 3248                        }
 3249                        if pair.end.as_str() == text.as_ref() {
 3250                            bracket_pair = Some(pair.clone());
 3251                            is_bracket_pair_end = true;
 3252                            break;
 3253                        }
 3254                    }
 3255                }
 3256
 3257                if let Some(bracket_pair) = bracket_pair {
 3258                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3259                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3260                    let auto_surround =
 3261                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3262                    if selection.is_empty() {
 3263                        if is_bracket_pair_start {
 3264                            let prefix_len = bracket_pair.start.len() - text.len();
 3265
 3266                            // If the inserted text is a suffix of an opening bracket and the
 3267                            // selection is preceded by the rest of the opening bracket, then
 3268                            // insert the closing bracket.
 3269                            let following_text_allows_autoclose = snapshot
 3270                                .chars_at(selection.start)
 3271                                .next()
 3272                                .map_or(true, |c| scope.should_autoclose_before(c));
 3273                            let preceding_text_matches_prefix = prefix_len == 0
 3274                                || (selection.start.column >= (prefix_len as u32)
 3275                                    && snapshot.contains_str_at(
 3276                                        Point::new(
 3277                                            selection.start.row,
 3278                                            selection.start.column - (prefix_len as u32),
 3279                                        ),
 3280                                        &bracket_pair.start[..prefix_len],
 3281                                    ));
 3282
 3283                            if autoclose
 3284                                && bracket_pair.close
 3285                                && following_text_allows_autoclose
 3286                                && preceding_text_matches_prefix
 3287                            {
 3288                                let anchor = snapshot.anchor_before(selection.end);
 3289                                new_selections.push((selection.map(|_| anchor), text.len()));
 3290                                new_autoclose_regions.push((
 3291                                    anchor,
 3292                                    text.len(),
 3293                                    selection.id,
 3294                                    bracket_pair.clone(),
 3295                                ));
 3296                                edits.push((
 3297                                    selection.range(),
 3298                                    format!("{}{}", text, bracket_pair.end).into(),
 3299                                ));
 3300                                bracket_inserted = true;
 3301                                continue;
 3302                            }
 3303                        }
 3304
 3305                        if let Some(region) = autoclose_region {
 3306                            // If the selection is followed by an auto-inserted closing bracket,
 3307                            // then don't insert that closing bracket again; just move the selection
 3308                            // past the closing bracket.
 3309                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3310                                && text.as_ref() == region.pair.end.as_str();
 3311                            if should_skip {
 3312                                let anchor = snapshot.anchor_after(selection.end);
 3313                                new_selections
 3314                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3315                                continue;
 3316                            }
 3317                        }
 3318
 3319                        let always_treat_brackets_as_autoclosed = snapshot
 3320                            .settings_at(selection.start, cx)
 3321                            .always_treat_brackets_as_autoclosed;
 3322                        if always_treat_brackets_as_autoclosed
 3323                            && is_bracket_pair_end
 3324                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3325                        {
 3326                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3327                            // and the inserted text is a closing bracket and the selection is followed
 3328                            // by the closing bracket then move the selection past the closing bracket.
 3329                            let anchor = snapshot.anchor_after(selection.end);
 3330                            new_selections.push((selection.map(|_| anchor), text.len()));
 3331                            continue;
 3332                        }
 3333                    }
 3334                    // If an opening bracket is 1 character long and is typed while
 3335                    // text is selected, then surround that text with the bracket pair.
 3336                    else if auto_surround
 3337                        && bracket_pair.surround
 3338                        && is_bracket_pair_start
 3339                        && bracket_pair.start.chars().count() == 1
 3340                    {
 3341                        edits.push((selection.start..selection.start, text.clone()));
 3342                        edits.push((
 3343                            selection.end..selection.end,
 3344                            bracket_pair.end.as_str().into(),
 3345                        ));
 3346                        bracket_inserted = true;
 3347                        new_selections.push((
 3348                            Selection {
 3349                                id: selection.id,
 3350                                start: snapshot.anchor_after(selection.start),
 3351                                end: snapshot.anchor_before(selection.end),
 3352                                reversed: selection.reversed,
 3353                                goal: selection.goal,
 3354                            },
 3355                            0,
 3356                        ));
 3357                        continue;
 3358                    }
 3359                }
 3360            }
 3361
 3362            if self.auto_replace_emoji_shortcode
 3363                && selection.is_empty()
 3364                && text.as_ref().ends_with(':')
 3365            {
 3366                if let Some(possible_emoji_short_code) =
 3367                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3368                {
 3369                    if !possible_emoji_short_code.is_empty() {
 3370                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3371                            let emoji_shortcode_start = Point::new(
 3372                                selection.start.row,
 3373                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3374                            );
 3375
 3376                            // Remove shortcode from buffer
 3377                            edits.push((
 3378                                emoji_shortcode_start..selection.start,
 3379                                "".to_string().into(),
 3380                            ));
 3381                            new_selections.push((
 3382                                Selection {
 3383                                    id: selection.id,
 3384                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3385                                    end: snapshot.anchor_before(selection.start),
 3386                                    reversed: selection.reversed,
 3387                                    goal: selection.goal,
 3388                                },
 3389                                0,
 3390                            ));
 3391
 3392                            // Insert emoji
 3393                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3394                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3395                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3396
 3397                            continue;
 3398                        }
 3399                    }
 3400                }
 3401            }
 3402
 3403            // If not handling any auto-close operation, then just replace the selected
 3404            // text with the given input and move the selection to the end of the
 3405            // newly inserted text.
 3406            let anchor = snapshot.anchor_after(selection.end);
 3407            if !self.linked_edit_ranges.is_empty() {
 3408                let start_anchor = snapshot.anchor_before(selection.start);
 3409
 3410                let is_word_char = text.chars().next().map_or(true, |char| {
 3411                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3412                    classifier.is_word(char)
 3413                });
 3414
 3415                if is_word_char {
 3416                    if let Some(ranges) = self
 3417                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3418                    {
 3419                        for (buffer, edits) in ranges {
 3420                            linked_edits
 3421                                .entry(buffer.clone())
 3422                                .or_default()
 3423                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3424                        }
 3425                    }
 3426                }
 3427            }
 3428
 3429            new_selections.push((selection.map(|_| anchor), 0));
 3430            edits.push((selection.start..selection.end, text.clone()));
 3431        }
 3432
 3433        drop(snapshot);
 3434
 3435        self.transact(cx, |this, cx| {
 3436            this.buffer.update(cx, |buffer, cx| {
 3437                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3438            });
 3439            for (buffer, edits) in linked_edits {
 3440                buffer.update(cx, |buffer, cx| {
 3441                    let snapshot = buffer.snapshot();
 3442                    let edits = edits
 3443                        .into_iter()
 3444                        .map(|(range, text)| {
 3445                            use text::ToPoint as TP;
 3446                            let end_point = TP::to_point(&range.end, &snapshot);
 3447                            let start_point = TP::to_point(&range.start, &snapshot);
 3448                            (start_point..end_point, text)
 3449                        })
 3450                        .sorted_by_key(|(range, _)| range.start)
 3451                        .collect::<Vec<_>>();
 3452                    buffer.edit(edits, None, cx);
 3453                })
 3454            }
 3455            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3456            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3457            let snapshot = this.buffer.read(cx).read(cx);
 3458            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3459                .zip(new_selection_deltas)
 3460                .map(|(selection, delta)| Selection {
 3461                    id: selection.id,
 3462                    start: selection.start + delta,
 3463                    end: selection.end + delta,
 3464                    reversed: selection.reversed,
 3465                    goal: SelectionGoal::None,
 3466                })
 3467                .collect::<Vec<_>>();
 3468
 3469            let mut i = 0;
 3470            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3471                let position = position.to_offset(&snapshot) + delta;
 3472                let start = snapshot.anchor_before(position);
 3473                let end = snapshot.anchor_after(position);
 3474                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3475                    match existing_state.range.start.cmp(&start, &snapshot) {
 3476                        Ordering::Less => i += 1,
 3477                        Ordering::Greater => break,
 3478                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3479                            Ordering::Less => i += 1,
 3480                            Ordering::Equal => break,
 3481                            Ordering::Greater => break,
 3482                        },
 3483                    }
 3484                }
 3485                this.autoclose_regions.insert(
 3486                    i,
 3487                    AutocloseRegion {
 3488                        selection_id,
 3489                        range: start..end,
 3490                        pair,
 3491                    },
 3492                );
 3493            }
 3494
 3495            drop(snapshot);
 3496            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3497            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3498                s.select(new_selections)
 3499            });
 3500
 3501            if !bracket_inserted {
 3502                if let Some(on_type_format_task) =
 3503                    this.trigger_on_type_formatting(text.to_string(), cx)
 3504                {
 3505                    on_type_format_task.detach_and_log_err(cx);
 3506                }
 3507            }
 3508
 3509            let editor_settings = EditorSettings::get_global(cx);
 3510            if bracket_inserted
 3511                && (editor_settings.auto_signature_help
 3512                    || editor_settings.show_signature_help_after_edits)
 3513            {
 3514                this.show_signature_help(&ShowSignatureHelp, cx);
 3515            }
 3516
 3517            let trigger_in_words = !had_active_inline_completion;
 3518            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3519            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3520            this.refresh_inline_completion(true, false, cx);
 3521        });
 3522    }
 3523
 3524    fn find_possible_emoji_shortcode_at_position(
 3525        snapshot: &MultiBufferSnapshot,
 3526        position: Point,
 3527    ) -> Option<String> {
 3528        let mut chars = Vec::new();
 3529        let mut found_colon = false;
 3530        for char in snapshot.reversed_chars_at(position).take(100) {
 3531            // Found a possible emoji shortcode in the middle of the buffer
 3532            if found_colon {
 3533                if char.is_whitespace() {
 3534                    chars.reverse();
 3535                    return Some(chars.iter().collect());
 3536                }
 3537                // If the previous character is not a whitespace, we are in the middle of a word
 3538                // and we only want to complete the shortcode if the word is made up of other emojis
 3539                let mut containing_word = String::new();
 3540                for ch in snapshot
 3541                    .reversed_chars_at(position)
 3542                    .skip(chars.len() + 1)
 3543                    .take(100)
 3544                {
 3545                    if ch.is_whitespace() {
 3546                        break;
 3547                    }
 3548                    containing_word.push(ch);
 3549                }
 3550                let containing_word = containing_word.chars().rev().collect::<String>();
 3551                if util::word_consists_of_emojis(containing_word.as_str()) {
 3552                    chars.reverse();
 3553                    return Some(chars.iter().collect());
 3554                }
 3555            }
 3556
 3557            if char.is_whitespace() || !char.is_ascii() {
 3558                return None;
 3559            }
 3560            if char == ':' {
 3561                found_colon = true;
 3562            } else {
 3563                chars.push(char);
 3564            }
 3565        }
 3566        // Found a possible emoji shortcode at the beginning of the buffer
 3567        chars.reverse();
 3568        Some(chars.iter().collect())
 3569    }
 3570
 3571    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3572        self.transact(cx, |this, cx| {
 3573            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3574                let selections = this.selections.all::<usize>(cx);
 3575                let multi_buffer = this.buffer.read(cx);
 3576                let buffer = multi_buffer.snapshot(cx);
 3577                selections
 3578                    .iter()
 3579                    .map(|selection| {
 3580                        let start_point = selection.start.to_point(&buffer);
 3581                        let mut indent =
 3582                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3583                        indent.len = cmp::min(indent.len, start_point.column);
 3584                        let start = selection.start;
 3585                        let end = selection.end;
 3586                        let selection_is_empty = start == end;
 3587                        let language_scope = buffer.language_scope_at(start);
 3588                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3589                            &language_scope
 3590                        {
 3591                            let leading_whitespace_len = buffer
 3592                                .reversed_chars_at(start)
 3593                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3594                                .map(|c| c.len_utf8())
 3595                                .sum::<usize>();
 3596
 3597                            let trailing_whitespace_len = buffer
 3598                                .chars_at(end)
 3599                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3600                                .map(|c| c.len_utf8())
 3601                                .sum::<usize>();
 3602
 3603                            let insert_extra_newline =
 3604                                language.brackets().any(|(pair, enabled)| {
 3605                                    let pair_start = pair.start.trim_end();
 3606                                    let pair_end = pair.end.trim_start();
 3607
 3608                                    enabled
 3609                                        && pair.newline
 3610                                        && buffer.contains_str_at(
 3611                                            end + trailing_whitespace_len,
 3612                                            pair_end,
 3613                                        )
 3614                                        && buffer.contains_str_at(
 3615                                            (start - leading_whitespace_len)
 3616                                                .saturating_sub(pair_start.len()),
 3617                                            pair_start,
 3618                                        )
 3619                                });
 3620
 3621                            // Comment extension on newline is allowed only for cursor selections
 3622                            let comment_delimiter = maybe!({
 3623                                if !selection_is_empty {
 3624                                    return None;
 3625                                }
 3626
 3627                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3628                                    return None;
 3629                                }
 3630
 3631                                let delimiters = language.line_comment_prefixes();
 3632                                let max_len_of_delimiter =
 3633                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3634                                let (snapshot, range) =
 3635                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3636
 3637                                let mut index_of_first_non_whitespace = 0;
 3638                                let comment_candidate = snapshot
 3639                                    .chars_for_range(range)
 3640                                    .skip_while(|c| {
 3641                                        let should_skip = c.is_whitespace();
 3642                                        if should_skip {
 3643                                            index_of_first_non_whitespace += 1;
 3644                                        }
 3645                                        should_skip
 3646                                    })
 3647                                    .take(max_len_of_delimiter)
 3648                                    .collect::<String>();
 3649                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3650                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3651                                })?;
 3652                                let cursor_is_placed_after_comment_marker =
 3653                                    index_of_first_non_whitespace + comment_prefix.len()
 3654                                        <= start_point.column as usize;
 3655                                if cursor_is_placed_after_comment_marker {
 3656                                    Some(comment_prefix.clone())
 3657                                } else {
 3658                                    None
 3659                                }
 3660                            });
 3661                            (comment_delimiter, insert_extra_newline)
 3662                        } else {
 3663                            (None, false)
 3664                        };
 3665
 3666                        let capacity_for_delimiter = comment_delimiter
 3667                            .as_deref()
 3668                            .map(str::len)
 3669                            .unwrap_or_default();
 3670                        let mut new_text =
 3671                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3672                        new_text.push('\n');
 3673                        new_text.extend(indent.chars());
 3674                        if let Some(delimiter) = &comment_delimiter {
 3675                            new_text.push_str(delimiter);
 3676                        }
 3677                        if insert_extra_newline {
 3678                            new_text = new_text.repeat(2);
 3679                        }
 3680
 3681                        let anchor = buffer.anchor_after(end);
 3682                        let new_selection = selection.map(|_| anchor);
 3683                        (
 3684                            (start..end, new_text),
 3685                            (insert_extra_newline, new_selection),
 3686                        )
 3687                    })
 3688                    .unzip()
 3689            };
 3690
 3691            this.edit_with_autoindent(edits, cx);
 3692            let buffer = this.buffer.read(cx).snapshot(cx);
 3693            let new_selections = selection_fixup_info
 3694                .into_iter()
 3695                .map(|(extra_newline_inserted, new_selection)| {
 3696                    let mut cursor = new_selection.end.to_point(&buffer);
 3697                    if extra_newline_inserted {
 3698                        cursor.row -= 1;
 3699                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3700                    }
 3701                    new_selection.map(|_| cursor)
 3702                })
 3703                .collect();
 3704
 3705            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3706            this.refresh_inline_completion(true, false, cx);
 3707        });
 3708    }
 3709
 3710    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3711        let buffer = self.buffer.read(cx);
 3712        let snapshot = buffer.snapshot(cx);
 3713
 3714        let mut edits = Vec::new();
 3715        let mut rows = Vec::new();
 3716
 3717        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3718            let cursor = selection.head();
 3719            let row = cursor.row;
 3720
 3721            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3722
 3723            let newline = "\n".to_string();
 3724            edits.push((start_of_line..start_of_line, newline));
 3725
 3726            rows.push(row + rows_inserted as u32);
 3727        }
 3728
 3729        self.transact(cx, |editor, cx| {
 3730            editor.edit(edits, cx);
 3731
 3732            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3733                let mut index = 0;
 3734                s.move_cursors_with(|map, _, _| {
 3735                    let row = rows[index];
 3736                    index += 1;
 3737
 3738                    let point = Point::new(row, 0);
 3739                    let boundary = map.next_line_boundary(point).1;
 3740                    let clipped = map.clip_point(boundary, Bias::Left);
 3741
 3742                    (clipped, SelectionGoal::None)
 3743                });
 3744            });
 3745
 3746            let mut indent_edits = Vec::new();
 3747            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3748            for row in rows {
 3749                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3750                for (row, indent) in indents {
 3751                    if indent.len == 0 {
 3752                        continue;
 3753                    }
 3754
 3755                    let text = match indent.kind {
 3756                        IndentKind::Space => " ".repeat(indent.len as usize),
 3757                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3758                    };
 3759                    let point = Point::new(row.0, 0);
 3760                    indent_edits.push((point..point, text));
 3761                }
 3762            }
 3763            editor.edit(indent_edits, cx);
 3764        });
 3765    }
 3766
 3767    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3768        let buffer = self.buffer.read(cx);
 3769        let snapshot = buffer.snapshot(cx);
 3770
 3771        let mut edits = Vec::new();
 3772        let mut rows = Vec::new();
 3773        let mut rows_inserted = 0;
 3774
 3775        for selection in self.selections.all_adjusted(cx) {
 3776            let cursor = selection.head();
 3777            let row = cursor.row;
 3778
 3779            let point = Point::new(row + 1, 0);
 3780            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3781
 3782            let newline = "\n".to_string();
 3783            edits.push((start_of_line..start_of_line, newline));
 3784
 3785            rows_inserted += 1;
 3786            rows.push(row + rows_inserted);
 3787        }
 3788
 3789        self.transact(cx, |editor, cx| {
 3790            editor.edit(edits, cx);
 3791
 3792            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3793                let mut index = 0;
 3794                s.move_cursors_with(|map, _, _| {
 3795                    let row = rows[index];
 3796                    index += 1;
 3797
 3798                    let point = Point::new(row, 0);
 3799                    let boundary = map.next_line_boundary(point).1;
 3800                    let clipped = map.clip_point(boundary, Bias::Left);
 3801
 3802                    (clipped, SelectionGoal::None)
 3803                });
 3804            });
 3805
 3806            let mut indent_edits = Vec::new();
 3807            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3808            for row in rows {
 3809                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3810                for (row, indent) in indents {
 3811                    if indent.len == 0 {
 3812                        continue;
 3813                    }
 3814
 3815                    let text = match indent.kind {
 3816                        IndentKind::Space => " ".repeat(indent.len as usize),
 3817                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3818                    };
 3819                    let point = Point::new(row.0, 0);
 3820                    indent_edits.push((point..point, text));
 3821                }
 3822            }
 3823            editor.edit(indent_edits, cx);
 3824        });
 3825    }
 3826
 3827    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3828        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3829            original_indent_columns: Vec::new(),
 3830        });
 3831        self.insert_with_autoindent_mode(text, autoindent, cx);
 3832    }
 3833
 3834    fn insert_with_autoindent_mode(
 3835        &mut self,
 3836        text: &str,
 3837        autoindent_mode: Option<AutoindentMode>,
 3838        cx: &mut ViewContext<Self>,
 3839    ) {
 3840        if self.read_only(cx) {
 3841            return;
 3842        }
 3843
 3844        let text: Arc<str> = text.into();
 3845        self.transact(cx, |this, cx| {
 3846            let old_selections = this.selections.all_adjusted(cx);
 3847            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3848                let anchors = {
 3849                    let snapshot = buffer.read(cx);
 3850                    old_selections
 3851                        .iter()
 3852                        .map(|s| {
 3853                            let anchor = snapshot.anchor_after(s.head());
 3854                            s.map(|_| anchor)
 3855                        })
 3856                        .collect::<Vec<_>>()
 3857                };
 3858                buffer.edit(
 3859                    old_selections
 3860                        .iter()
 3861                        .map(|s| (s.start..s.end, text.clone())),
 3862                    autoindent_mode,
 3863                    cx,
 3864                );
 3865                anchors
 3866            });
 3867
 3868            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3869                s.select_anchors(selection_anchors);
 3870            })
 3871        });
 3872    }
 3873
 3874    fn trigger_completion_on_input(
 3875        &mut self,
 3876        text: &str,
 3877        trigger_in_words: bool,
 3878        cx: &mut ViewContext<Self>,
 3879    ) {
 3880        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3881            self.show_completions(
 3882                &ShowCompletions {
 3883                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3884                },
 3885                cx,
 3886            );
 3887        } else {
 3888            self.hide_context_menu(cx);
 3889        }
 3890    }
 3891
 3892    fn is_completion_trigger(
 3893        &self,
 3894        text: &str,
 3895        trigger_in_words: bool,
 3896        cx: &mut ViewContext<Self>,
 3897    ) -> bool {
 3898        let position = self.selections.newest_anchor().head();
 3899        let multibuffer = self.buffer.read(cx);
 3900        let Some(buffer) = position
 3901            .buffer_id
 3902            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3903        else {
 3904            return false;
 3905        };
 3906
 3907        if let Some(completion_provider) = &self.completion_provider {
 3908            completion_provider.is_completion_trigger(
 3909                &buffer,
 3910                position.text_anchor,
 3911                text,
 3912                trigger_in_words,
 3913                cx,
 3914            )
 3915        } else {
 3916            false
 3917        }
 3918    }
 3919
 3920    /// If any empty selections is touching the start of its innermost containing autoclose
 3921    /// region, expand it to select the brackets.
 3922    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3923        let selections = self.selections.all::<usize>(cx);
 3924        let buffer = self.buffer.read(cx).read(cx);
 3925        let new_selections = self
 3926            .selections_with_autoclose_regions(selections, &buffer)
 3927            .map(|(mut selection, region)| {
 3928                if !selection.is_empty() {
 3929                    return selection;
 3930                }
 3931
 3932                if let Some(region) = region {
 3933                    let mut range = region.range.to_offset(&buffer);
 3934                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3935                        range.start -= region.pair.start.len();
 3936                        if buffer.contains_str_at(range.start, &region.pair.start)
 3937                            && buffer.contains_str_at(range.end, &region.pair.end)
 3938                        {
 3939                            range.end += region.pair.end.len();
 3940                            selection.start = range.start;
 3941                            selection.end = range.end;
 3942
 3943                            return selection;
 3944                        }
 3945                    }
 3946                }
 3947
 3948                let always_treat_brackets_as_autoclosed = buffer
 3949                    .settings_at(selection.start, cx)
 3950                    .always_treat_brackets_as_autoclosed;
 3951
 3952                if !always_treat_brackets_as_autoclosed {
 3953                    return selection;
 3954                }
 3955
 3956                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3957                    for (pair, enabled) in scope.brackets() {
 3958                        if !enabled || !pair.close {
 3959                            continue;
 3960                        }
 3961
 3962                        if buffer.contains_str_at(selection.start, &pair.end) {
 3963                            let pair_start_len = pair.start.len();
 3964                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3965                            {
 3966                                selection.start -= pair_start_len;
 3967                                selection.end += pair.end.len();
 3968
 3969                                return selection;
 3970                            }
 3971                        }
 3972                    }
 3973                }
 3974
 3975                selection
 3976            })
 3977            .collect();
 3978
 3979        drop(buffer);
 3980        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3981    }
 3982
 3983    /// Iterate the given selections, and for each one, find the smallest surrounding
 3984    /// autoclose region. This uses the ordering of the selections and the autoclose
 3985    /// regions to avoid repeated comparisons.
 3986    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3987        &'a self,
 3988        selections: impl IntoIterator<Item = Selection<D>>,
 3989        buffer: &'a MultiBufferSnapshot,
 3990    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3991        let mut i = 0;
 3992        let mut regions = self.autoclose_regions.as_slice();
 3993        selections.into_iter().map(move |selection| {
 3994            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3995
 3996            let mut enclosing = None;
 3997            while let Some(pair_state) = regions.get(i) {
 3998                if pair_state.range.end.to_offset(buffer) < range.start {
 3999                    regions = &regions[i + 1..];
 4000                    i = 0;
 4001                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4002                    break;
 4003                } else {
 4004                    if pair_state.selection_id == selection.id {
 4005                        enclosing = Some(pair_state);
 4006                    }
 4007                    i += 1;
 4008                }
 4009            }
 4010
 4011            (selection.clone(), enclosing)
 4012        })
 4013    }
 4014
 4015    /// Remove any autoclose regions that no longer contain their selection.
 4016    fn invalidate_autoclose_regions(
 4017        &mut self,
 4018        mut selections: &[Selection<Anchor>],
 4019        buffer: &MultiBufferSnapshot,
 4020    ) {
 4021        self.autoclose_regions.retain(|state| {
 4022            let mut i = 0;
 4023            while let Some(selection) = selections.get(i) {
 4024                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4025                    selections = &selections[1..];
 4026                    continue;
 4027                }
 4028                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4029                    break;
 4030                }
 4031                if selection.id == state.selection_id {
 4032                    return true;
 4033                } else {
 4034                    i += 1;
 4035                }
 4036            }
 4037            false
 4038        });
 4039    }
 4040
 4041    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4042        let offset = position.to_offset(buffer);
 4043        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4044        if offset > word_range.start && kind == Some(CharKind::Word) {
 4045            Some(
 4046                buffer
 4047                    .text_for_range(word_range.start..offset)
 4048                    .collect::<String>(),
 4049            )
 4050        } else {
 4051            None
 4052        }
 4053    }
 4054
 4055    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4056        self.refresh_inlay_hints(
 4057            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4058            cx,
 4059        );
 4060    }
 4061
 4062    pub fn inlay_hints_enabled(&self) -> bool {
 4063        self.inlay_hint_cache.enabled
 4064    }
 4065
 4066    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4067        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4068            return;
 4069        }
 4070
 4071        let reason_description = reason.description();
 4072        let ignore_debounce = matches!(
 4073            reason,
 4074            InlayHintRefreshReason::SettingsChange(_)
 4075                | InlayHintRefreshReason::Toggle(_)
 4076                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4077        );
 4078        let (invalidate_cache, required_languages) = match reason {
 4079            InlayHintRefreshReason::Toggle(enabled) => {
 4080                self.inlay_hint_cache.enabled = enabled;
 4081                if enabled {
 4082                    (InvalidationStrategy::RefreshRequested, None)
 4083                } else {
 4084                    self.inlay_hint_cache.clear();
 4085                    self.splice_inlays(
 4086                        self.visible_inlay_hints(cx)
 4087                            .iter()
 4088                            .map(|inlay| inlay.id)
 4089                            .collect(),
 4090                        Vec::new(),
 4091                        cx,
 4092                    );
 4093                    return;
 4094                }
 4095            }
 4096            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4097                match self.inlay_hint_cache.update_settings(
 4098                    &self.buffer,
 4099                    new_settings,
 4100                    self.visible_inlay_hints(cx),
 4101                    cx,
 4102                ) {
 4103                    ControlFlow::Break(Some(InlaySplice {
 4104                        to_remove,
 4105                        to_insert,
 4106                    })) => {
 4107                        self.splice_inlays(to_remove, to_insert, cx);
 4108                        return;
 4109                    }
 4110                    ControlFlow::Break(None) => return,
 4111                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4112                }
 4113            }
 4114            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4115                if let Some(InlaySplice {
 4116                    to_remove,
 4117                    to_insert,
 4118                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4119                {
 4120                    self.splice_inlays(to_remove, to_insert, cx);
 4121                }
 4122                return;
 4123            }
 4124            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4125            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4126                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4127            }
 4128            InlayHintRefreshReason::RefreshRequested => {
 4129                (InvalidationStrategy::RefreshRequested, None)
 4130            }
 4131        };
 4132
 4133        if let Some(InlaySplice {
 4134            to_remove,
 4135            to_insert,
 4136        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4137            reason_description,
 4138            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4139            invalidate_cache,
 4140            ignore_debounce,
 4141            cx,
 4142        ) {
 4143            self.splice_inlays(to_remove, to_insert, cx);
 4144        }
 4145    }
 4146
 4147    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4148        self.display_map
 4149            .read(cx)
 4150            .current_inlays()
 4151            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4152            .cloned()
 4153            .collect()
 4154    }
 4155
 4156    pub fn excerpts_for_inlay_hints_query(
 4157        &self,
 4158        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4159        cx: &mut ViewContext<Editor>,
 4160    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4161        let Some(project) = self.project.as_ref() else {
 4162            return HashMap::default();
 4163        };
 4164        let project = project.read(cx);
 4165        let multi_buffer = self.buffer().read(cx);
 4166        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4167        let multi_buffer_visible_start = self
 4168            .scroll_manager
 4169            .anchor()
 4170            .anchor
 4171            .to_point(&multi_buffer_snapshot);
 4172        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4173            multi_buffer_visible_start
 4174                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4175            Bias::Left,
 4176        );
 4177        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4178        multi_buffer
 4179            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4180            .into_iter()
 4181            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4182            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4183                let buffer = buffer_handle.read(cx);
 4184                let buffer_file = project::File::from_dyn(buffer.file())?;
 4185                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4186                let worktree_entry = buffer_worktree
 4187                    .read(cx)
 4188                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4189                if worktree_entry.is_ignored {
 4190                    return None;
 4191                }
 4192
 4193                let language = buffer.language()?;
 4194                if let Some(restrict_to_languages) = restrict_to_languages {
 4195                    if !restrict_to_languages.contains(language) {
 4196                        return None;
 4197                    }
 4198                }
 4199                Some((
 4200                    excerpt_id,
 4201                    (
 4202                        buffer_handle,
 4203                        buffer.version().clone(),
 4204                        excerpt_visible_range,
 4205                    ),
 4206                ))
 4207            })
 4208            .collect()
 4209    }
 4210
 4211    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4212        TextLayoutDetails {
 4213            text_system: cx.text_system().clone(),
 4214            editor_style: self.style.clone().unwrap(),
 4215            rem_size: cx.rem_size(),
 4216            scroll_anchor: self.scroll_manager.anchor(),
 4217            visible_rows: self.visible_line_count(),
 4218            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4219        }
 4220    }
 4221
 4222    fn splice_inlays(
 4223        &self,
 4224        to_remove: Vec<InlayId>,
 4225        to_insert: Vec<Inlay>,
 4226        cx: &mut ViewContext<Self>,
 4227    ) {
 4228        self.display_map.update(cx, |display_map, cx| {
 4229            display_map.splice_inlays(to_remove, to_insert, cx);
 4230        });
 4231        cx.notify();
 4232    }
 4233
 4234    fn trigger_on_type_formatting(
 4235        &self,
 4236        input: String,
 4237        cx: &mut ViewContext<Self>,
 4238    ) -> Option<Task<Result<()>>> {
 4239        if input.len() != 1 {
 4240            return None;
 4241        }
 4242
 4243        let project = self.project.as_ref()?;
 4244        let position = self.selections.newest_anchor().head();
 4245        let (buffer, buffer_position) = self
 4246            .buffer
 4247            .read(cx)
 4248            .text_anchor_for_position(position, cx)?;
 4249
 4250        let settings = language_settings::language_settings(
 4251            buffer.read(cx).language_at(buffer_position).as_ref(),
 4252            buffer.read(cx).file(),
 4253            cx,
 4254        );
 4255        if !settings.use_on_type_format {
 4256            return None;
 4257        }
 4258
 4259        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4260        // hence we do LSP request & edit on host side only — add formats to host's history.
 4261        let push_to_lsp_host_history = true;
 4262        // If this is not the host, append its history with new edits.
 4263        let push_to_client_history = project.read(cx).is_via_collab();
 4264
 4265        let on_type_formatting = project.update(cx, |project, cx| {
 4266            project.on_type_format(
 4267                buffer.clone(),
 4268                buffer_position,
 4269                input,
 4270                push_to_lsp_host_history,
 4271                cx,
 4272            )
 4273        });
 4274        Some(cx.spawn(|editor, mut cx| async move {
 4275            if let Some(transaction) = on_type_formatting.await? {
 4276                if push_to_client_history {
 4277                    buffer
 4278                        .update(&mut cx, |buffer, _| {
 4279                            buffer.push_transaction(transaction, Instant::now());
 4280                        })
 4281                        .ok();
 4282                }
 4283                editor.update(&mut cx, |editor, cx| {
 4284                    editor.refresh_document_highlights(cx);
 4285                })?;
 4286            }
 4287            Ok(())
 4288        }))
 4289    }
 4290
 4291    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4292        if self.pending_rename.is_some() {
 4293            return;
 4294        }
 4295
 4296        let Some(provider) = self.completion_provider.as_ref() else {
 4297            return;
 4298        };
 4299
 4300        let position = self.selections.newest_anchor().head();
 4301        let (buffer, buffer_position) =
 4302            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4303                output
 4304            } else {
 4305                return;
 4306            };
 4307
 4308        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4309        let is_followup_invoke = {
 4310            let context_menu_state = self.context_menu.read();
 4311            matches!(
 4312                context_menu_state.deref(),
 4313                Some(ContextMenu::Completions(_))
 4314            )
 4315        };
 4316        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4317            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4318            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4319                CompletionTriggerKind::TRIGGER_CHARACTER
 4320            }
 4321
 4322            _ => CompletionTriggerKind::INVOKED,
 4323        };
 4324        let completion_context = CompletionContext {
 4325            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4326                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4327                    Some(String::from(trigger))
 4328                } else {
 4329                    None
 4330                }
 4331            }),
 4332            trigger_kind,
 4333        };
 4334        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4335        let sort_completions = provider.sort_completions();
 4336
 4337        let id = post_inc(&mut self.next_completion_id);
 4338        let task = cx.spawn(|this, mut cx| {
 4339            async move {
 4340                this.update(&mut cx, |this, _| {
 4341                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4342                })?;
 4343                let completions = completions.await.log_err();
 4344                let menu = if let Some(completions) = completions {
 4345                    let mut menu = CompletionsMenu {
 4346                        id,
 4347                        sort_completions,
 4348                        initial_position: position,
 4349                        match_candidates: completions
 4350                            .iter()
 4351                            .enumerate()
 4352                            .map(|(id, completion)| {
 4353                                StringMatchCandidate::new(
 4354                                    id,
 4355                                    completion.label.text[completion.label.filter_range.clone()]
 4356                                        .into(),
 4357                                )
 4358                            })
 4359                            .collect(),
 4360                        buffer: buffer.clone(),
 4361                        completions: Arc::new(RwLock::new(completions.into())),
 4362                        matches: Vec::new().into(),
 4363                        selected_item: 0,
 4364                        scroll_handle: UniformListScrollHandle::new(),
 4365                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4366                            DebouncedDelay::new(),
 4367                        )),
 4368                    };
 4369                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4370                        .await;
 4371
 4372                    if menu.matches.is_empty() {
 4373                        None
 4374                    } else {
 4375                        this.update(&mut cx, |editor, cx| {
 4376                            let completions = menu.completions.clone();
 4377                            let matches = menu.matches.clone();
 4378
 4379                            let delay_ms = EditorSettings::get_global(cx)
 4380                                .completion_documentation_secondary_query_debounce;
 4381                            let delay = Duration::from_millis(delay_ms);
 4382                            editor
 4383                                .completion_documentation_pre_resolve_debounce
 4384                                .fire_new(delay, cx, |editor, cx| {
 4385                                    CompletionsMenu::pre_resolve_completion_documentation(
 4386                                        buffer,
 4387                                        completions,
 4388                                        matches,
 4389                                        editor,
 4390                                        cx,
 4391                                    )
 4392                                });
 4393                        })
 4394                        .ok();
 4395                        Some(menu)
 4396                    }
 4397                } else {
 4398                    None
 4399                };
 4400
 4401                this.update(&mut cx, |this, cx| {
 4402                    let mut context_menu = this.context_menu.write();
 4403                    match context_menu.as_ref() {
 4404                        None => {}
 4405
 4406                        Some(ContextMenu::Completions(prev_menu)) => {
 4407                            if prev_menu.id > id {
 4408                                return;
 4409                            }
 4410                        }
 4411
 4412                        _ => return,
 4413                    }
 4414
 4415                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4416                        let menu = menu.unwrap();
 4417                        *context_menu = Some(ContextMenu::Completions(menu));
 4418                        drop(context_menu);
 4419                        this.discard_inline_completion(false, cx);
 4420                        cx.notify();
 4421                    } else if this.completion_tasks.len() <= 1 {
 4422                        // If there are no more completion tasks and the last menu was
 4423                        // empty, we should hide it. If it was already hidden, we should
 4424                        // also show the copilot completion when available.
 4425                        drop(context_menu);
 4426                        if this.hide_context_menu(cx).is_none() {
 4427                            this.update_visible_inline_completion(cx);
 4428                        }
 4429                    }
 4430                })?;
 4431
 4432                Ok::<_, anyhow::Error>(())
 4433            }
 4434            .log_err()
 4435        });
 4436
 4437        self.completion_tasks.push((id, task));
 4438    }
 4439
 4440    pub fn confirm_completion(
 4441        &mut self,
 4442        action: &ConfirmCompletion,
 4443        cx: &mut ViewContext<Self>,
 4444    ) -> Option<Task<Result<()>>> {
 4445        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4446    }
 4447
 4448    pub fn compose_completion(
 4449        &mut self,
 4450        action: &ComposeCompletion,
 4451        cx: &mut ViewContext<Self>,
 4452    ) -> Option<Task<Result<()>>> {
 4453        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4454    }
 4455
 4456    fn do_completion(
 4457        &mut self,
 4458        item_ix: Option<usize>,
 4459        intent: CompletionIntent,
 4460        cx: &mut ViewContext<Editor>,
 4461    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4462        use language::ToOffset as _;
 4463
 4464        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4465            menu
 4466        } else {
 4467            return None;
 4468        };
 4469
 4470        let mat = completions_menu
 4471            .matches
 4472            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4473        let buffer_handle = completions_menu.buffer;
 4474        let completions = completions_menu.completions.read();
 4475        let completion = completions.get(mat.candidate_id)?;
 4476        cx.stop_propagation();
 4477
 4478        let snippet;
 4479        let text;
 4480
 4481        if completion.is_snippet() {
 4482            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4483            text = snippet.as_ref().unwrap().text.clone();
 4484        } else {
 4485            snippet = None;
 4486            text = completion.new_text.clone();
 4487        };
 4488        let selections = self.selections.all::<usize>(cx);
 4489        let buffer = buffer_handle.read(cx);
 4490        let old_range = completion.old_range.to_offset(buffer);
 4491        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4492
 4493        let newest_selection = self.selections.newest_anchor();
 4494        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4495            return None;
 4496        }
 4497
 4498        let lookbehind = newest_selection
 4499            .start
 4500            .text_anchor
 4501            .to_offset(buffer)
 4502            .saturating_sub(old_range.start);
 4503        let lookahead = old_range
 4504            .end
 4505            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4506        let mut common_prefix_len = old_text
 4507            .bytes()
 4508            .zip(text.bytes())
 4509            .take_while(|(a, b)| a == b)
 4510            .count();
 4511
 4512        let snapshot = self.buffer.read(cx).snapshot(cx);
 4513        let mut range_to_replace: Option<Range<isize>> = None;
 4514        let mut ranges = Vec::new();
 4515        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4516        for selection in &selections {
 4517            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4518                let start = selection.start.saturating_sub(lookbehind);
 4519                let end = selection.end + lookahead;
 4520                if selection.id == newest_selection.id {
 4521                    range_to_replace = Some(
 4522                        ((start + common_prefix_len) as isize - selection.start as isize)
 4523                            ..(end as isize - selection.start as isize),
 4524                    );
 4525                }
 4526                ranges.push(start + common_prefix_len..end);
 4527            } else {
 4528                common_prefix_len = 0;
 4529                ranges.clear();
 4530                ranges.extend(selections.iter().map(|s| {
 4531                    if s.id == newest_selection.id {
 4532                        range_to_replace = Some(
 4533                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4534                                - selection.start as isize
 4535                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4536                                    - selection.start as isize,
 4537                        );
 4538                        old_range.clone()
 4539                    } else {
 4540                        s.start..s.end
 4541                    }
 4542                }));
 4543                break;
 4544            }
 4545            if !self.linked_edit_ranges.is_empty() {
 4546                let start_anchor = snapshot.anchor_before(selection.head());
 4547                let end_anchor = snapshot.anchor_after(selection.tail());
 4548                if let Some(ranges) = self
 4549                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4550                {
 4551                    for (buffer, edits) in ranges {
 4552                        linked_edits.entry(buffer.clone()).or_default().extend(
 4553                            edits
 4554                                .into_iter()
 4555                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4556                        );
 4557                    }
 4558                }
 4559            }
 4560        }
 4561        let text = &text[common_prefix_len..];
 4562
 4563        cx.emit(EditorEvent::InputHandled {
 4564            utf16_range_to_replace: range_to_replace,
 4565            text: text.into(),
 4566        });
 4567
 4568        self.transact(cx, |this, cx| {
 4569            if let Some(mut snippet) = snippet {
 4570                snippet.text = text.to_string();
 4571                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4572                    tabstop.start -= common_prefix_len as isize;
 4573                    tabstop.end -= common_prefix_len as isize;
 4574                }
 4575
 4576                this.insert_snippet(&ranges, snippet, cx).log_err();
 4577            } else {
 4578                this.buffer.update(cx, |buffer, cx| {
 4579                    buffer.edit(
 4580                        ranges.iter().map(|range| (range.clone(), text)),
 4581                        this.autoindent_mode.clone(),
 4582                        cx,
 4583                    );
 4584                });
 4585            }
 4586            for (buffer, edits) in linked_edits {
 4587                buffer.update(cx, |buffer, cx| {
 4588                    let snapshot = buffer.snapshot();
 4589                    let edits = edits
 4590                        .into_iter()
 4591                        .map(|(range, text)| {
 4592                            use text::ToPoint as TP;
 4593                            let end_point = TP::to_point(&range.end, &snapshot);
 4594                            let start_point = TP::to_point(&range.start, &snapshot);
 4595                            (start_point..end_point, text)
 4596                        })
 4597                        .sorted_by_key(|(range, _)| range.start)
 4598                        .collect::<Vec<_>>();
 4599                    buffer.edit(edits, None, cx);
 4600                })
 4601            }
 4602
 4603            this.refresh_inline_completion(true, false, cx);
 4604        });
 4605
 4606        let show_new_completions_on_confirm = completion
 4607            .confirm
 4608            .as_ref()
 4609            .map_or(false, |confirm| confirm(intent, cx));
 4610        if show_new_completions_on_confirm {
 4611            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4612        }
 4613
 4614        let provider = self.completion_provider.as_ref()?;
 4615        let apply_edits = provider.apply_additional_edits_for_completion(
 4616            buffer_handle,
 4617            completion.clone(),
 4618            true,
 4619            cx,
 4620        );
 4621
 4622        let editor_settings = EditorSettings::get_global(cx);
 4623        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4624            // After the code completion is finished, users often want to know what signatures are needed.
 4625            // so we should automatically call signature_help
 4626            self.show_signature_help(&ShowSignatureHelp, cx);
 4627        }
 4628
 4629        Some(cx.foreground_executor().spawn(async move {
 4630            apply_edits.await?;
 4631            Ok(())
 4632        }))
 4633    }
 4634
 4635    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4636        let mut context_menu = self.context_menu.write();
 4637        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4638            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4639                // Toggle if we're selecting the same one
 4640                *context_menu = None;
 4641                cx.notify();
 4642                return;
 4643            } else {
 4644                // Otherwise, clear it and start a new one
 4645                *context_menu = None;
 4646                cx.notify();
 4647            }
 4648        }
 4649        drop(context_menu);
 4650        let snapshot = self.snapshot(cx);
 4651        let deployed_from_indicator = action.deployed_from_indicator;
 4652        let mut task = self.code_actions_task.take();
 4653        let action = action.clone();
 4654        cx.spawn(|editor, mut cx| async move {
 4655            while let Some(prev_task) = task {
 4656                prev_task.await.log_err();
 4657                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4658            }
 4659
 4660            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4661                if editor.focus_handle.is_focused(cx) {
 4662                    let multibuffer_point = action
 4663                        .deployed_from_indicator
 4664                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4665                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4666                    let (buffer, buffer_row) = snapshot
 4667                        .buffer_snapshot
 4668                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4669                        .and_then(|(buffer_snapshot, range)| {
 4670                            editor
 4671                                .buffer
 4672                                .read(cx)
 4673                                .buffer(buffer_snapshot.remote_id())
 4674                                .map(|buffer| (buffer, range.start.row))
 4675                        })?;
 4676                    let (_, code_actions) = editor
 4677                        .available_code_actions
 4678                        .clone()
 4679                        .and_then(|(location, code_actions)| {
 4680                            let snapshot = location.buffer.read(cx).snapshot();
 4681                            let point_range = location.range.to_point(&snapshot);
 4682                            let point_range = point_range.start.row..=point_range.end.row;
 4683                            if point_range.contains(&buffer_row) {
 4684                                Some((location, code_actions))
 4685                            } else {
 4686                                None
 4687                            }
 4688                        })
 4689                        .unzip();
 4690                    let buffer_id = buffer.read(cx).remote_id();
 4691                    let tasks = editor
 4692                        .tasks
 4693                        .get(&(buffer_id, buffer_row))
 4694                        .map(|t| Arc::new(t.to_owned()));
 4695                    if tasks.is_none() && code_actions.is_none() {
 4696                        return None;
 4697                    }
 4698
 4699                    editor.completion_tasks.clear();
 4700                    editor.discard_inline_completion(false, cx);
 4701                    let task_context =
 4702                        tasks
 4703                            .as_ref()
 4704                            .zip(editor.project.clone())
 4705                            .map(|(tasks, project)| {
 4706                                let position = Point::new(buffer_row, tasks.column);
 4707                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4708                                let location = Location {
 4709                                    buffer: buffer.clone(),
 4710                                    range: range_start..range_start,
 4711                                };
 4712                                // Fill in the environmental variables from the tree-sitter captures
 4713                                let mut captured_task_variables = TaskVariables::default();
 4714                                for (capture_name, value) in tasks.extra_variables.clone() {
 4715                                    captured_task_variables.insert(
 4716                                        task::VariableName::Custom(capture_name.into()),
 4717                                        value.clone(),
 4718                                    );
 4719                                }
 4720                                project.update(cx, |project, cx| {
 4721                                    project.task_store().update(cx, |task_store, cx| {
 4722                                        task_store.task_context_for_location(
 4723                                            captured_task_variables,
 4724                                            location,
 4725                                            cx,
 4726                                        )
 4727                                    })
 4728                                })
 4729                            });
 4730
 4731                    Some(cx.spawn(|editor, mut cx| async move {
 4732                        let task_context = match task_context {
 4733                            Some(task_context) => task_context.await,
 4734                            None => None,
 4735                        };
 4736                        let resolved_tasks =
 4737                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4738                                Arc::new(ResolvedTasks {
 4739                                    templates: tasks
 4740                                        .templates
 4741                                        .iter()
 4742                                        .filter_map(|(kind, template)| {
 4743                                            template
 4744                                                .resolve_task(&kind.to_id_base(), &task_context)
 4745                                                .map(|task| (kind.clone(), task))
 4746                                        })
 4747                                        .collect(),
 4748                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4749                                        multibuffer_point.row,
 4750                                        tasks.column,
 4751                                    )),
 4752                                })
 4753                            });
 4754                        let spawn_straight_away = resolved_tasks
 4755                            .as_ref()
 4756                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4757                            && code_actions
 4758                                .as_ref()
 4759                                .map_or(true, |actions| actions.is_empty());
 4760                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4761                            *editor.context_menu.write() =
 4762                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4763                                    buffer,
 4764                                    actions: CodeActionContents {
 4765                                        tasks: resolved_tasks,
 4766                                        actions: code_actions,
 4767                                    },
 4768                                    selected_item: Default::default(),
 4769                                    scroll_handle: UniformListScrollHandle::default(),
 4770                                    deployed_from_indicator,
 4771                                }));
 4772                            if spawn_straight_away {
 4773                                if let Some(task) = editor.confirm_code_action(
 4774                                    &ConfirmCodeAction { item_ix: Some(0) },
 4775                                    cx,
 4776                                ) {
 4777                                    cx.notify();
 4778                                    return task;
 4779                                }
 4780                            }
 4781                            cx.notify();
 4782                            Task::ready(Ok(()))
 4783                        }) {
 4784                            task.await
 4785                        } else {
 4786                            Ok(())
 4787                        }
 4788                    }))
 4789                } else {
 4790                    Some(Task::ready(Ok(())))
 4791                }
 4792            })?;
 4793            if let Some(task) = spawned_test_task {
 4794                task.await?;
 4795            }
 4796
 4797            Ok::<_, anyhow::Error>(())
 4798        })
 4799        .detach_and_log_err(cx);
 4800    }
 4801
 4802    pub fn confirm_code_action(
 4803        &mut self,
 4804        action: &ConfirmCodeAction,
 4805        cx: &mut ViewContext<Self>,
 4806    ) -> Option<Task<Result<()>>> {
 4807        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4808            menu
 4809        } else {
 4810            return None;
 4811        };
 4812        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4813        let action = actions_menu.actions.get(action_ix)?;
 4814        let title = action.label();
 4815        let buffer = actions_menu.buffer;
 4816        let workspace = self.workspace()?;
 4817
 4818        match action {
 4819            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4820                workspace.update(cx, |workspace, cx| {
 4821                    workspace::tasks::schedule_resolved_task(
 4822                        workspace,
 4823                        task_source_kind,
 4824                        resolved_task,
 4825                        false,
 4826                        cx,
 4827                    );
 4828
 4829                    Some(Task::ready(Ok(())))
 4830                })
 4831            }
 4832            CodeActionsItem::CodeAction {
 4833                excerpt_id,
 4834                action,
 4835                provider,
 4836            } => {
 4837                let apply_code_action =
 4838                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4839                let workspace = workspace.downgrade();
 4840                Some(cx.spawn(|editor, cx| async move {
 4841                    let project_transaction = apply_code_action.await?;
 4842                    Self::open_project_transaction(
 4843                        &editor,
 4844                        workspace,
 4845                        project_transaction,
 4846                        title,
 4847                        cx,
 4848                    )
 4849                    .await
 4850                }))
 4851            }
 4852        }
 4853    }
 4854
 4855    pub async fn open_project_transaction(
 4856        this: &WeakView<Editor>,
 4857        workspace: WeakView<Workspace>,
 4858        transaction: ProjectTransaction,
 4859        title: String,
 4860        mut cx: AsyncWindowContext,
 4861    ) -> Result<()> {
 4862        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4863        cx.update(|cx| {
 4864            entries.sort_unstable_by_key(|(buffer, _)| {
 4865                buffer.read(cx).file().map(|f| f.path().clone())
 4866            });
 4867        })?;
 4868
 4869        // If the project transaction's edits are all contained within this editor, then
 4870        // avoid opening a new editor to display them.
 4871
 4872        if let Some((buffer, transaction)) = entries.first() {
 4873            if entries.len() == 1 {
 4874                let excerpt = this.update(&mut cx, |editor, cx| {
 4875                    editor
 4876                        .buffer()
 4877                        .read(cx)
 4878                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4879                })?;
 4880                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4881                    if excerpted_buffer == *buffer {
 4882                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4883                            let excerpt_range = excerpt_range.to_offset(buffer);
 4884                            buffer
 4885                                .edited_ranges_for_transaction::<usize>(transaction)
 4886                                .all(|range| {
 4887                                    excerpt_range.start <= range.start
 4888                                        && excerpt_range.end >= range.end
 4889                                })
 4890                        })?;
 4891
 4892                        if all_edits_within_excerpt {
 4893                            return Ok(());
 4894                        }
 4895                    }
 4896                }
 4897            }
 4898        } else {
 4899            return Ok(());
 4900        }
 4901
 4902        let mut ranges_to_highlight = Vec::new();
 4903        let excerpt_buffer = cx.new_model(|cx| {
 4904            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4905            for (buffer_handle, transaction) in &entries {
 4906                let buffer = buffer_handle.read(cx);
 4907                ranges_to_highlight.extend(
 4908                    multibuffer.push_excerpts_with_context_lines(
 4909                        buffer_handle.clone(),
 4910                        buffer
 4911                            .edited_ranges_for_transaction::<usize>(transaction)
 4912                            .collect(),
 4913                        DEFAULT_MULTIBUFFER_CONTEXT,
 4914                        cx,
 4915                    ),
 4916                );
 4917            }
 4918            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4919            multibuffer
 4920        })?;
 4921
 4922        workspace.update(&mut cx, |workspace, cx| {
 4923            let project = workspace.project().clone();
 4924            let editor =
 4925                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4926            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4927            editor.update(cx, |editor, cx| {
 4928                editor.highlight_background::<Self>(
 4929                    &ranges_to_highlight,
 4930                    |theme| theme.editor_highlighted_line_background,
 4931                    cx,
 4932                );
 4933            });
 4934        })?;
 4935
 4936        Ok(())
 4937    }
 4938
 4939    pub fn clear_code_action_providers(&mut self) {
 4940        self.code_action_providers.clear();
 4941        self.available_code_actions.take();
 4942    }
 4943
 4944    pub fn push_code_action_provider(
 4945        &mut self,
 4946        provider: Arc<dyn CodeActionProvider>,
 4947        cx: &mut ViewContext<Self>,
 4948    ) {
 4949        self.code_action_providers.push(provider);
 4950        self.refresh_code_actions(cx);
 4951    }
 4952
 4953    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4954        let buffer = self.buffer.read(cx);
 4955        let newest_selection = self.selections.newest_anchor().clone();
 4956        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4957        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4958        if start_buffer != end_buffer {
 4959            return None;
 4960        }
 4961
 4962        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4963            cx.background_executor()
 4964                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4965                .await;
 4966
 4967            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4968                let providers = this.code_action_providers.clone();
 4969                let tasks = this
 4970                    .code_action_providers
 4971                    .iter()
 4972                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4973                    .collect::<Vec<_>>();
 4974                (providers, tasks)
 4975            })?;
 4976
 4977            let mut actions = Vec::new();
 4978            for (provider, provider_actions) in
 4979                providers.into_iter().zip(future::join_all(tasks).await)
 4980            {
 4981                if let Some(provider_actions) = provider_actions.log_err() {
 4982                    actions.extend(provider_actions.into_iter().map(|action| {
 4983                        AvailableCodeAction {
 4984                            excerpt_id: newest_selection.start.excerpt_id,
 4985                            action,
 4986                            provider: provider.clone(),
 4987                        }
 4988                    }));
 4989                }
 4990            }
 4991
 4992            this.update(&mut cx, |this, cx| {
 4993                this.available_code_actions = if actions.is_empty() {
 4994                    None
 4995                } else {
 4996                    Some((
 4997                        Location {
 4998                            buffer: start_buffer,
 4999                            range: start..end,
 5000                        },
 5001                        actions.into(),
 5002                    ))
 5003                };
 5004                cx.notify();
 5005            })
 5006        }));
 5007        None
 5008    }
 5009
 5010    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5011        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5012            self.show_git_blame_inline = false;
 5013
 5014            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5015                cx.background_executor().timer(delay).await;
 5016
 5017                this.update(&mut cx, |this, cx| {
 5018                    this.show_git_blame_inline = true;
 5019                    cx.notify();
 5020                })
 5021                .log_err();
 5022            }));
 5023        }
 5024    }
 5025
 5026    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5027        if self.pending_rename.is_some() {
 5028            return None;
 5029        }
 5030
 5031        let provider = self.semantics_provider.clone()?;
 5032        let buffer = self.buffer.read(cx);
 5033        let newest_selection = self.selections.newest_anchor().clone();
 5034        let cursor_position = newest_selection.head();
 5035        let (cursor_buffer, cursor_buffer_position) =
 5036            buffer.text_anchor_for_position(cursor_position, cx)?;
 5037        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5038        if cursor_buffer != tail_buffer {
 5039            return None;
 5040        }
 5041
 5042        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5043            cx.background_executor()
 5044                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5045                .await;
 5046
 5047            let highlights = if let Some(highlights) = cx
 5048                .update(|cx| {
 5049                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5050                })
 5051                .ok()
 5052                .flatten()
 5053            {
 5054                highlights.await.log_err()
 5055            } else {
 5056                None
 5057            };
 5058
 5059            if let Some(highlights) = highlights {
 5060                this.update(&mut cx, |this, cx| {
 5061                    if this.pending_rename.is_some() {
 5062                        return;
 5063                    }
 5064
 5065                    let buffer_id = cursor_position.buffer_id;
 5066                    let buffer = this.buffer.read(cx);
 5067                    if !buffer
 5068                        .text_anchor_for_position(cursor_position, cx)
 5069                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5070                    {
 5071                        return;
 5072                    }
 5073
 5074                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5075                    let mut write_ranges = Vec::new();
 5076                    let mut read_ranges = Vec::new();
 5077                    for highlight in highlights {
 5078                        for (excerpt_id, excerpt_range) in
 5079                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5080                        {
 5081                            let start = highlight
 5082                                .range
 5083                                .start
 5084                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5085                            let end = highlight
 5086                                .range
 5087                                .end
 5088                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5089                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5090                                continue;
 5091                            }
 5092
 5093                            let range = Anchor {
 5094                                buffer_id,
 5095                                excerpt_id,
 5096                                text_anchor: start,
 5097                            }..Anchor {
 5098                                buffer_id,
 5099                                excerpt_id,
 5100                                text_anchor: end,
 5101                            };
 5102                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5103                                write_ranges.push(range);
 5104                            } else {
 5105                                read_ranges.push(range);
 5106                            }
 5107                        }
 5108                    }
 5109
 5110                    this.highlight_background::<DocumentHighlightRead>(
 5111                        &read_ranges,
 5112                        |theme| theme.editor_document_highlight_read_background,
 5113                        cx,
 5114                    );
 5115                    this.highlight_background::<DocumentHighlightWrite>(
 5116                        &write_ranges,
 5117                        |theme| theme.editor_document_highlight_write_background,
 5118                        cx,
 5119                    );
 5120                    cx.notify();
 5121                })
 5122                .log_err();
 5123            }
 5124        }));
 5125        None
 5126    }
 5127
 5128    pub fn refresh_inline_completion(
 5129        &mut self,
 5130        debounce: bool,
 5131        user_requested: bool,
 5132        cx: &mut ViewContext<Self>,
 5133    ) -> Option<()> {
 5134        let provider = self.inline_completion_provider()?;
 5135        let cursor = self.selections.newest_anchor().head();
 5136        let (buffer, cursor_buffer_position) =
 5137            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5138
 5139        if !user_requested
 5140            && (!self.enable_inline_completions
 5141                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5142        {
 5143            self.discard_inline_completion(false, cx);
 5144            return None;
 5145        }
 5146
 5147        self.update_visible_inline_completion(cx);
 5148        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5149        Some(())
 5150    }
 5151
 5152    fn cycle_inline_completion(
 5153        &mut self,
 5154        direction: Direction,
 5155        cx: &mut ViewContext<Self>,
 5156    ) -> Option<()> {
 5157        let provider = self.inline_completion_provider()?;
 5158        let cursor = self.selections.newest_anchor().head();
 5159        let (buffer, cursor_buffer_position) =
 5160            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5161        if !self.enable_inline_completions
 5162            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5163        {
 5164            return None;
 5165        }
 5166
 5167        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5168        self.update_visible_inline_completion(cx);
 5169
 5170        Some(())
 5171    }
 5172
 5173    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5174        if !self.has_active_inline_completion(cx) {
 5175            self.refresh_inline_completion(false, true, cx);
 5176            return;
 5177        }
 5178
 5179        self.update_visible_inline_completion(cx);
 5180    }
 5181
 5182    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5183        self.show_cursor_names(cx);
 5184    }
 5185
 5186    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5187        self.show_cursor_names = true;
 5188        cx.notify();
 5189        cx.spawn(|this, mut cx| async move {
 5190            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5191            this.update(&mut cx, |this, cx| {
 5192                this.show_cursor_names = false;
 5193                cx.notify()
 5194            })
 5195            .ok()
 5196        })
 5197        .detach();
 5198    }
 5199
 5200    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5201        if self.has_active_inline_completion(cx) {
 5202            self.cycle_inline_completion(Direction::Next, cx);
 5203        } else {
 5204            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5205            if is_copilot_disabled {
 5206                cx.propagate();
 5207            }
 5208        }
 5209    }
 5210
 5211    pub fn previous_inline_completion(
 5212        &mut self,
 5213        _: &PreviousInlineCompletion,
 5214        cx: &mut ViewContext<Self>,
 5215    ) {
 5216        if self.has_active_inline_completion(cx) {
 5217            self.cycle_inline_completion(Direction::Prev, cx);
 5218        } else {
 5219            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5220            if is_copilot_disabled {
 5221                cx.propagate();
 5222            }
 5223        }
 5224    }
 5225
 5226    pub fn accept_inline_completion(
 5227        &mut self,
 5228        _: &AcceptInlineCompletion,
 5229        cx: &mut ViewContext<Self>,
 5230    ) {
 5231        let Some(completion) = self.take_active_inline_completion(cx) else {
 5232            return;
 5233        };
 5234        if let Some(provider) = self.inline_completion_provider() {
 5235            provider.accept(cx);
 5236        }
 5237
 5238        cx.emit(EditorEvent::InputHandled {
 5239            utf16_range_to_replace: None,
 5240            text: completion.text.to_string().into(),
 5241        });
 5242
 5243        if let Some(range) = completion.delete_range {
 5244            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5245        }
 5246        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5247        self.refresh_inline_completion(true, true, cx);
 5248        cx.notify();
 5249    }
 5250
 5251    pub fn accept_partial_inline_completion(
 5252        &mut self,
 5253        _: &AcceptPartialInlineCompletion,
 5254        cx: &mut ViewContext<Self>,
 5255    ) {
 5256        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5257            if let Some(completion) = self.take_active_inline_completion(cx) {
 5258                let mut partial_completion = completion
 5259                    .text
 5260                    .chars()
 5261                    .by_ref()
 5262                    .take_while(|c| c.is_alphabetic())
 5263                    .collect::<String>();
 5264                if partial_completion.is_empty() {
 5265                    partial_completion = completion
 5266                        .text
 5267                        .chars()
 5268                        .by_ref()
 5269                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5270                        .collect::<String>();
 5271                }
 5272
 5273                cx.emit(EditorEvent::InputHandled {
 5274                    utf16_range_to_replace: None,
 5275                    text: partial_completion.clone().into(),
 5276                });
 5277
 5278                if let Some(range) = completion.delete_range {
 5279                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5280                }
 5281                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5282
 5283                self.refresh_inline_completion(true, true, cx);
 5284                cx.notify();
 5285            }
 5286        }
 5287    }
 5288
 5289    fn discard_inline_completion(
 5290        &mut self,
 5291        should_report_inline_completion_event: bool,
 5292        cx: &mut ViewContext<Self>,
 5293    ) -> bool {
 5294        if let Some(provider) = self.inline_completion_provider() {
 5295            provider.discard(should_report_inline_completion_event, cx);
 5296        }
 5297
 5298        self.take_active_inline_completion(cx).is_some()
 5299    }
 5300
 5301    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5302        if let Some(completion) = self.active_inline_completion.as_ref() {
 5303            let buffer = self.buffer.read(cx).read(cx);
 5304            completion.position.is_valid(&buffer)
 5305        } else {
 5306            false
 5307        }
 5308    }
 5309
 5310    fn take_active_inline_completion(
 5311        &mut self,
 5312        cx: &mut ViewContext<Self>,
 5313    ) -> Option<CompletionState> {
 5314        let completion = self.active_inline_completion.take()?;
 5315        let render_inlay_ids = completion.render_inlay_ids.clone();
 5316        self.display_map.update(cx, |map, cx| {
 5317            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5318        });
 5319        let buffer = self.buffer.read(cx).read(cx);
 5320
 5321        if completion.position.is_valid(&buffer) {
 5322            Some(completion)
 5323        } else {
 5324            None
 5325        }
 5326    }
 5327
 5328    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5329        let selection = self.selections.newest_anchor();
 5330        let cursor = selection.head();
 5331
 5332        let excerpt_id = cursor.excerpt_id;
 5333
 5334        if self.context_menu.read().is_none()
 5335            && self.completion_tasks.is_empty()
 5336            && selection.start == selection.end
 5337        {
 5338            if let Some(provider) = self.inline_completion_provider() {
 5339                if let Some((buffer, cursor_buffer_position)) =
 5340                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5341                {
 5342                    if let Some(proposal) =
 5343                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5344                    {
 5345                        let mut to_remove = Vec::new();
 5346                        if let Some(completion) = self.active_inline_completion.take() {
 5347                            to_remove.extend(completion.render_inlay_ids.iter());
 5348                        }
 5349
 5350                        let to_add = proposal
 5351                            .inlays
 5352                            .iter()
 5353                            .filter_map(|inlay| {
 5354                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5355                                let id = post_inc(&mut self.next_inlay_id);
 5356                                match inlay {
 5357                                    InlayProposal::Hint(position, hint) => {
 5358                                        let position =
 5359                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5360                                        Some(Inlay::hint(id, position, hint))
 5361                                    }
 5362                                    InlayProposal::Suggestion(position, text) => {
 5363                                        let position =
 5364                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5365                                        Some(Inlay::suggestion(id, position, text.clone()))
 5366                                    }
 5367                                }
 5368                            })
 5369                            .collect_vec();
 5370
 5371                        self.active_inline_completion = Some(CompletionState {
 5372                            position: cursor,
 5373                            text: proposal.text,
 5374                            delete_range: proposal.delete_range.and_then(|range| {
 5375                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5376                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5377                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5378                                Some(start?..end?)
 5379                            }),
 5380                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5381                        });
 5382
 5383                        self.display_map
 5384                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5385
 5386                        cx.notify();
 5387                        return;
 5388                    }
 5389                }
 5390            }
 5391        }
 5392
 5393        self.discard_inline_completion(false, cx);
 5394    }
 5395
 5396    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5397        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5398    }
 5399
 5400    fn render_code_actions_indicator(
 5401        &self,
 5402        _style: &EditorStyle,
 5403        row: DisplayRow,
 5404        is_active: bool,
 5405        cx: &mut ViewContext<Self>,
 5406    ) -> Option<IconButton> {
 5407        if self.available_code_actions.is_some() {
 5408            Some(
 5409                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5410                    .shape(ui::IconButtonShape::Square)
 5411                    .icon_size(IconSize::XSmall)
 5412                    .icon_color(Color::Muted)
 5413                    .selected(is_active)
 5414                    .tooltip({
 5415                        let focus_handle = self.focus_handle.clone();
 5416                        move |cx| {
 5417                            Tooltip::for_action_in(
 5418                                "Toggle Code Actions",
 5419                                &ToggleCodeActions {
 5420                                    deployed_from_indicator: None,
 5421                                },
 5422                                &focus_handle,
 5423                                cx,
 5424                            )
 5425                        }
 5426                    })
 5427                    .on_click(cx.listener(move |editor, _e, cx| {
 5428                        editor.focus(cx);
 5429                        editor.toggle_code_actions(
 5430                            &ToggleCodeActions {
 5431                                deployed_from_indicator: Some(row),
 5432                            },
 5433                            cx,
 5434                        );
 5435                    })),
 5436            )
 5437        } else {
 5438            None
 5439        }
 5440    }
 5441
 5442    fn clear_tasks(&mut self) {
 5443        self.tasks.clear()
 5444    }
 5445
 5446    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5447        if self.tasks.insert(key, value).is_some() {
 5448            // This case should hopefully be rare, but just in case...
 5449            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5450        }
 5451    }
 5452
 5453    fn render_run_indicator(
 5454        &self,
 5455        _style: &EditorStyle,
 5456        is_active: bool,
 5457        row: DisplayRow,
 5458        cx: &mut ViewContext<Self>,
 5459    ) -> IconButton {
 5460        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5461            .shape(ui::IconButtonShape::Square)
 5462            .icon_size(IconSize::XSmall)
 5463            .icon_color(Color::Muted)
 5464            .selected(is_active)
 5465            .on_click(cx.listener(move |editor, _e, cx| {
 5466                editor.focus(cx);
 5467                editor.toggle_code_actions(
 5468                    &ToggleCodeActions {
 5469                        deployed_from_indicator: Some(row),
 5470                    },
 5471                    cx,
 5472                );
 5473            }))
 5474    }
 5475
 5476    pub fn context_menu_visible(&self) -> bool {
 5477        self.context_menu
 5478            .read()
 5479            .as_ref()
 5480            .map_or(false, |menu| menu.visible())
 5481    }
 5482
 5483    fn render_context_menu(
 5484        &self,
 5485        cursor_position: DisplayPoint,
 5486        style: &EditorStyle,
 5487        max_height: Pixels,
 5488        cx: &mut ViewContext<Editor>,
 5489    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5490        self.context_menu.read().as_ref().map(|menu| {
 5491            menu.render(
 5492                cursor_position,
 5493                style,
 5494                max_height,
 5495                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5496                cx,
 5497            )
 5498        })
 5499    }
 5500
 5501    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5502        cx.notify();
 5503        self.completion_tasks.clear();
 5504        let context_menu = self.context_menu.write().take();
 5505        if context_menu.is_some() {
 5506            self.update_visible_inline_completion(cx);
 5507        }
 5508        context_menu
 5509    }
 5510
 5511    pub fn insert_snippet(
 5512        &mut self,
 5513        insertion_ranges: &[Range<usize>],
 5514        snippet: Snippet,
 5515        cx: &mut ViewContext<Self>,
 5516    ) -> Result<()> {
 5517        struct Tabstop<T> {
 5518            is_end_tabstop: bool,
 5519            ranges: Vec<Range<T>>,
 5520        }
 5521
 5522        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5523            let snippet_text: Arc<str> = snippet.text.clone().into();
 5524            buffer.edit(
 5525                insertion_ranges
 5526                    .iter()
 5527                    .cloned()
 5528                    .map(|range| (range, snippet_text.clone())),
 5529                Some(AutoindentMode::EachLine),
 5530                cx,
 5531            );
 5532
 5533            let snapshot = &*buffer.read(cx);
 5534            let snippet = &snippet;
 5535            snippet
 5536                .tabstops
 5537                .iter()
 5538                .map(|tabstop| {
 5539                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5540                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5541                    });
 5542                    let mut tabstop_ranges = tabstop
 5543                        .iter()
 5544                        .flat_map(|tabstop_range| {
 5545                            let mut delta = 0_isize;
 5546                            insertion_ranges.iter().map(move |insertion_range| {
 5547                                let insertion_start = insertion_range.start as isize + delta;
 5548                                delta +=
 5549                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5550
 5551                                let start = ((insertion_start + tabstop_range.start) as usize)
 5552                                    .min(snapshot.len());
 5553                                let end = ((insertion_start + tabstop_range.end) as usize)
 5554                                    .min(snapshot.len());
 5555                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5556                            })
 5557                        })
 5558                        .collect::<Vec<_>>();
 5559                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5560
 5561                    Tabstop {
 5562                        is_end_tabstop,
 5563                        ranges: tabstop_ranges,
 5564                    }
 5565                })
 5566                .collect::<Vec<_>>()
 5567        });
 5568        if let Some(tabstop) = tabstops.first() {
 5569            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5570                s.select_ranges(tabstop.ranges.iter().cloned());
 5571            });
 5572
 5573            // If we're already at the last tabstop and it's at the end of the snippet,
 5574            // we're done, we don't need to keep the state around.
 5575            if !tabstop.is_end_tabstop {
 5576                let ranges = tabstops
 5577                    .into_iter()
 5578                    .map(|tabstop| tabstop.ranges)
 5579                    .collect::<Vec<_>>();
 5580                self.snippet_stack.push(SnippetState {
 5581                    active_index: 0,
 5582                    ranges,
 5583                });
 5584            }
 5585
 5586            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5587            if self.autoclose_regions.is_empty() {
 5588                let snapshot = self.buffer.read(cx).snapshot(cx);
 5589                for selection in &mut self.selections.all::<Point>(cx) {
 5590                    let selection_head = selection.head();
 5591                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5592                        continue;
 5593                    };
 5594
 5595                    let mut bracket_pair = None;
 5596                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5597                    let prev_chars = snapshot
 5598                        .reversed_chars_at(selection_head)
 5599                        .collect::<String>();
 5600                    for (pair, enabled) in scope.brackets() {
 5601                        if enabled
 5602                            && pair.close
 5603                            && prev_chars.starts_with(pair.start.as_str())
 5604                            && next_chars.starts_with(pair.end.as_str())
 5605                        {
 5606                            bracket_pair = Some(pair.clone());
 5607                            break;
 5608                        }
 5609                    }
 5610                    if let Some(pair) = bracket_pair {
 5611                        let start = snapshot.anchor_after(selection_head);
 5612                        let end = snapshot.anchor_after(selection_head);
 5613                        self.autoclose_regions.push(AutocloseRegion {
 5614                            selection_id: selection.id,
 5615                            range: start..end,
 5616                            pair,
 5617                        });
 5618                    }
 5619                }
 5620            }
 5621        }
 5622        Ok(())
 5623    }
 5624
 5625    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5626        self.move_to_snippet_tabstop(Bias::Right, cx)
 5627    }
 5628
 5629    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5630        self.move_to_snippet_tabstop(Bias::Left, cx)
 5631    }
 5632
 5633    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5634        if let Some(mut snippet) = self.snippet_stack.pop() {
 5635            match bias {
 5636                Bias::Left => {
 5637                    if snippet.active_index > 0 {
 5638                        snippet.active_index -= 1;
 5639                    } else {
 5640                        self.snippet_stack.push(snippet);
 5641                        return false;
 5642                    }
 5643                }
 5644                Bias::Right => {
 5645                    if snippet.active_index + 1 < snippet.ranges.len() {
 5646                        snippet.active_index += 1;
 5647                    } else {
 5648                        self.snippet_stack.push(snippet);
 5649                        return false;
 5650                    }
 5651                }
 5652            }
 5653            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5654                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5655                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5656                });
 5657                // If snippet state is not at the last tabstop, push it back on the stack
 5658                if snippet.active_index + 1 < snippet.ranges.len() {
 5659                    self.snippet_stack.push(snippet);
 5660                }
 5661                return true;
 5662            }
 5663        }
 5664
 5665        false
 5666    }
 5667
 5668    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5669        self.transact(cx, |this, cx| {
 5670            this.select_all(&SelectAll, cx);
 5671            this.insert("", cx);
 5672        });
 5673    }
 5674
 5675    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5676        self.transact(cx, |this, cx| {
 5677            this.select_autoclose_pair(cx);
 5678            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5679            if !this.linked_edit_ranges.is_empty() {
 5680                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5681                let snapshot = this.buffer.read(cx).snapshot(cx);
 5682
 5683                for selection in selections.iter() {
 5684                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5685                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5686                    if selection_start.buffer_id != selection_end.buffer_id {
 5687                        continue;
 5688                    }
 5689                    if let Some(ranges) =
 5690                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5691                    {
 5692                        for (buffer, entries) in ranges {
 5693                            linked_ranges.entry(buffer).or_default().extend(entries);
 5694                        }
 5695                    }
 5696                }
 5697            }
 5698
 5699            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5700            if !this.selections.line_mode {
 5701                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5702                for selection in &mut selections {
 5703                    if selection.is_empty() {
 5704                        let old_head = selection.head();
 5705                        let mut new_head =
 5706                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5707                                .to_point(&display_map);
 5708                        if let Some((buffer, line_buffer_range)) = display_map
 5709                            .buffer_snapshot
 5710                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5711                        {
 5712                            let indent_size =
 5713                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5714                            let indent_len = match indent_size.kind {
 5715                                IndentKind::Space => {
 5716                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5717                                }
 5718                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5719                            };
 5720                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5721                                let indent_len = indent_len.get();
 5722                                new_head = cmp::min(
 5723                                    new_head,
 5724                                    MultiBufferPoint::new(
 5725                                        old_head.row,
 5726                                        ((old_head.column - 1) / indent_len) * indent_len,
 5727                                    ),
 5728                                );
 5729                            }
 5730                        }
 5731
 5732                        selection.set_head(new_head, SelectionGoal::None);
 5733                    }
 5734                }
 5735            }
 5736
 5737            this.signature_help_state.set_backspace_pressed(true);
 5738            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5739            this.insert("", cx);
 5740            let empty_str: Arc<str> = Arc::from("");
 5741            for (buffer, edits) in linked_ranges {
 5742                let snapshot = buffer.read(cx).snapshot();
 5743                use text::ToPoint as TP;
 5744
 5745                let edits = edits
 5746                    .into_iter()
 5747                    .map(|range| {
 5748                        let end_point = TP::to_point(&range.end, &snapshot);
 5749                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5750
 5751                        if end_point == start_point {
 5752                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5753                                .saturating_sub(1);
 5754                            start_point = TP::to_point(&offset, &snapshot);
 5755                        };
 5756
 5757                        (start_point..end_point, empty_str.clone())
 5758                    })
 5759                    .sorted_by_key(|(range, _)| range.start)
 5760                    .collect::<Vec<_>>();
 5761                buffer.update(cx, |this, cx| {
 5762                    this.edit(edits, None, cx);
 5763                })
 5764            }
 5765            this.refresh_inline_completion(true, false, cx);
 5766            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5767        });
 5768    }
 5769
 5770    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5771        self.transact(cx, |this, cx| {
 5772            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5773                let line_mode = s.line_mode;
 5774                s.move_with(|map, selection| {
 5775                    if selection.is_empty() && !line_mode {
 5776                        let cursor = movement::right(map, selection.head());
 5777                        selection.end = cursor;
 5778                        selection.reversed = true;
 5779                        selection.goal = SelectionGoal::None;
 5780                    }
 5781                })
 5782            });
 5783            this.insert("", cx);
 5784            this.refresh_inline_completion(true, false, cx);
 5785        });
 5786    }
 5787
 5788    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5789        if self.move_to_prev_snippet_tabstop(cx) {
 5790            return;
 5791        }
 5792
 5793        self.outdent(&Outdent, cx);
 5794    }
 5795
 5796    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5797        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5798            return;
 5799        }
 5800
 5801        let mut selections = self.selections.all_adjusted(cx);
 5802        let buffer = self.buffer.read(cx);
 5803        let snapshot = buffer.snapshot(cx);
 5804        let rows_iter = selections.iter().map(|s| s.head().row);
 5805        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5806
 5807        let mut edits = Vec::new();
 5808        let mut prev_edited_row = 0;
 5809        let mut row_delta = 0;
 5810        for selection in &mut selections {
 5811            if selection.start.row != prev_edited_row {
 5812                row_delta = 0;
 5813            }
 5814            prev_edited_row = selection.end.row;
 5815
 5816            // If the selection is non-empty, then increase the indentation of the selected lines.
 5817            if !selection.is_empty() {
 5818                row_delta =
 5819                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5820                continue;
 5821            }
 5822
 5823            // If the selection is empty and the cursor is in the leading whitespace before the
 5824            // suggested indentation, then auto-indent the line.
 5825            let cursor = selection.head();
 5826            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5827            if let Some(suggested_indent) =
 5828                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5829            {
 5830                if cursor.column < suggested_indent.len
 5831                    && cursor.column <= current_indent.len
 5832                    && current_indent.len <= suggested_indent.len
 5833                {
 5834                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5835                    selection.end = selection.start;
 5836                    if row_delta == 0 {
 5837                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5838                            cursor.row,
 5839                            current_indent,
 5840                            suggested_indent,
 5841                        ));
 5842                        row_delta = suggested_indent.len - current_indent.len;
 5843                    }
 5844                    continue;
 5845                }
 5846            }
 5847
 5848            // Otherwise, insert a hard or soft tab.
 5849            let settings = buffer.settings_at(cursor, cx);
 5850            let tab_size = if settings.hard_tabs {
 5851                IndentSize::tab()
 5852            } else {
 5853                let tab_size = settings.tab_size.get();
 5854                let char_column = snapshot
 5855                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5856                    .flat_map(str::chars)
 5857                    .count()
 5858                    + row_delta as usize;
 5859                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5860                IndentSize::spaces(chars_to_next_tab_stop)
 5861            };
 5862            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5863            selection.end = selection.start;
 5864            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5865            row_delta += tab_size.len;
 5866        }
 5867
 5868        self.transact(cx, |this, cx| {
 5869            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5870            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5871            this.refresh_inline_completion(true, false, cx);
 5872        });
 5873    }
 5874
 5875    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5876        if self.read_only(cx) {
 5877            return;
 5878        }
 5879        let mut selections = self.selections.all::<Point>(cx);
 5880        let mut prev_edited_row = 0;
 5881        let mut row_delta = 0;
 5882        let mut edits = Vec::new();
 5883        let buffer = self.buffer.read(cx);
 5884        let snapshot = buffer.snapshot(cx);
 5885        for selection in &mut selections {
 5886            if selection.start.row != prev_edited_row {
 5887                row_delta = 0;
 5888            }
 5889            prev_edited_row = selection.end.row;
 5890
 5891            row_delta =
 5892                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5893        }
 5894
 5895        self.transact(cx, |this, cx| {
 5896            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5897            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5898        });
 5899    }
 5900
 5901    fn indent_selection(
 5902        buffer: &MultiBuffer,
 5903        snapshot: &MultiBufferSnapshot,
 5904        selection: &mut Selection<Point>,
 5905        edits: &mut Vec<(Range<Point>, String)>,
 5906        delta_for_start_row: u32,
 5907        cx: &AppContext,
 5908    ) -> u32 {
 5909        let settings = buffer.settings_at(selection.start, cx);
 5910        let tab_size = settings.tab_size.get();
 5911        let indent_kind = if settings.hard_tabs {
 5912            IndentKind::Tab
 5913        } else {
 5914            IndentKind::Space
 5915        };
 5916        let mut start_row = selection.start.row;
 5917        let mut end_row = selection.end.row + 1;
 5918
 5919        // If a selection ends at the beginning of a line, don't indent
 5920        // that last line.
 5921        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5922            end_row -= 1;
 5923        }
 5924
 5925        // Avoid re-indenting a row that has already been indented by a
 5926        // previous selection, but still update this selection's column
 5927        // to reflect that indentation.
 5928        if delta_for_start_row > 0 {
 5929            start_row += 1;
 5930            selection.start.column += delta_for_start_row;
 5931            if selection.end.row == selection.start.row {
 5932                selection.end.column += delta_for_start_row;
 5933            }
 5934        }
 5935
 5936        let mut delta_for_end_row = 0;
 5937        let has_multiple_rows = start_row + 1 != end_row;
 5938        for row in start_row..end_row {
 5939            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5940            let indent_delta = match (current_indent.kind, indent_kind) {
 5941                (IndentKind::Space, IndentKind::Space) => {
 5942                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5943                    IndentSize::spaces(columns_to_next_tab_stop)
 5944                }
 5945                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5946                (_, IndentKind::Tab) => IndentSize::tab(),
 5947            };
 5948
 5949            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5950                0
 5951            } else {
 5952                selection.start.column
 5953            };
 5954            let row_start = Point::new(row, start);
 5955            edits.push((
 5956                row_start..row_start,
 5957                indent_delta.chars().collect::<String>(),
 5958            ));
 5959
 5960            // Update this selection's endpoints to reflect the indentation.
 5961            if row == selection.start.row {
 5962                selection.start.column += indent_delta.len;
 5963            }
 5964            if row == selection.end.row {
 5965                selection.end.column += indent_delta.len;
 5966                delta_for_end_row = indent_delta.len;
 5967            }
 5968        }
 5969
 5970        if selection.start.row == selection.end.row {
 5971            delta_for_start_row + delta_for_end_row
 5972        } else {
 5973            delta_for_end_row
 5974        }
 5975    }
 5976
 5977    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5978        if self.read_only(cx) {
 5979            return;
 5980        }
 5981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5982        let selections = self.selections.all::<Point>(cx);
 5983        let mut deletion_ranges = Vec::new();
 5984        let mut last_outdent = None;
 5985        {
 5986            let buffer = self.buffer.read(cx);
 5987            let snapshot = buffer.snapshot(cx);
 5988            for selection in &selections {
 5989                let settings = buffer.settings_at(selection.start, cx);
 5990                let tab_size = settings.tab_size.get();
 5991                let mut rows = selection.spanned_rows(false, &display_map);
 5992
 5993                // Avoid re-outdenting a row that has already been outdented by a
 5994                // previous selection.
 5995                if let Some(last_row) = last_outdent {
 5996                    if last_row == rows.start {
 5997                        rows.start = rows.start.next_row();
 5998                    }
 5999                }
 6000                let has_multiple_rows = rows.len() > 1;
 6001                for row in rows.iter_rows() {
 6002                    let indent_size = snapshot.indent_size_for_line(row);
 6003                    if indent_size.len > 0 {
 6004                        let deletion_len = match indent_size.kind {
 6005                            IndentKind::Space => {
 6006                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6007                                if columns_to_prev_tab_stop == 0 {
 6008                                    tab_size
 6009                                } else {
 6010                                    columns_to_prev_tab_stop
 6011                                }
 6012                            }
 6013                            IndentKind::Tab => 1,
 6014                        };
 6015                        let start = if has_multiple_rows
 6016                            || deletion_len > selection.start.column
 6017                            || indent_size.len < selection.start.column
 6018                        {
 6019                            0
 6020                        } else {
 6021                            selection.start.column - deletion_len
 6022                        };
 6023                        deletion_ranges.push(
 6024                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6025                        );
 6026                        last_outdent = Some(row);
 6027                    }
 6028                }
 6029            }
 6030        }
 6031
 6032        self.transact(cx, |this, cx| {
 6033            this.buffer.update(cx, |buffer, cx| {
 6034                let empty_str: Arc<str> = Arc::default();
 6035                buffer.edit(
 6036                    deletion_ranges
 6037                        .into_iter()
 6038                        .map(|range| (range, empty_str.clone())),
 6039                    None,
 6040                    cx,
 6041                );
 6042            });
 6043            let selections = this.selections.all::<usize>(cx);
 6044            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6045        });
 6046    }
 6047
 6048    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6049        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6050        let selections = self.selections.all::<Point>(cx);
 6051
 6052        let mut new_cursors = Vec::new();
 6053        let mut edit_ranges = Vec::new();
 6054        let mut selections = selections.iter().peekable();
 6055        while let Some(selection) = selections.next() {
 6056            let mut rows = selection.spanned_rows(false, &display_map);
 6057            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6058
 6059            // Accumulate contiguous regions of rows that we want to delete.
 6060            while let Some(next_selection) = selections.peek() {
 6061                let next_rows = next_selection.spanned_rows(false, &display_map);
 6062                if next_rows.start <= rows.end {
 6063                    rows.end = next_rows.end;
 6064                    selections.next().unwrap();
 6065                } else {
 6066                    break;
 6067                }
 6068            }
 6069
 6070            let buffer = &display_map.buffer_snapshot;
 6071            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6072            let edit_end;
 6073            let cursor_buffer_row;
 6074            if buffer.max_point().row >= rows.end.0 {
 6075                // If there's a line after the range, delete the \n from the end of the row range
 6076                // and position the cursor on the next line.
 6077                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6078                cursor_buffer_row = rows.end;
 6079            } else {
 6080                // If there isn't a line after the range, delete the \n from the line before the
 6081                // start of the row range and position the cursor there.
 6082                edit_start = edit_start.saturating_sub(1);
 6083                edit_end = buffer.len();
 6084                cursor_buffer_row = rows.start.previous_row();
 6085            }
 6086
 6087            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6088            *cursor.column_mut() =
 6089                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6090
 6091            new_cursors.push((
 6092                selection.id,
 6093                buffer.anchor_after(cursor.to_point(&display_map)),
 6094            ));
 6095            edit_ranges.push(edit_start..edit_end);
 6096        }
 6097
 6098        self.transact(cx, |this, cx| {
 6099            let buffer = this.buffer.update(cx, |buffer, cx| {
 6100                let empty_str: Arc<str> = Arc::default();
 6101                buffer.edit(
 6102                    edit_ranges
 6103                        .into_iter()
 6104                        .map(|range| (range, empty_str.clone())),
 6105                    None,
 6106                    cx,
 6107                );
 6108                buffer.snapshot(cx)
 6109            });
 6110            let new_selections = new_cursors
 6111                .into_iter()
 6112                .map(|(id, cursor)| {
 6113                    let cursor = cursor.to_point(&buffer);
 6114                    Selection {
 6115                        id,
 6116                        start: cursor,
 6117                        end: cursor,
 6118                        reversed: false,
 6119                        goal: SelectionGoal::None,
 6120                    }
 6121                })
 6122                .collect();
 6123
 6124            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6125                s.select(new_selections);
 6126            });
 6127        });
 6128    }
 6129
 6130    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6131        if self.read_only(cx) {
 6132            return;
 6133        }
 6134        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6135        for selection in self.selections.all::<Point>(cx) {
 6136            let start = MultiBufferRow(selection.start.row);
 6137            let end = if selection.start.row == selection.end.row {
 6138                MultiBufferRow(selection.start.row + 1)
 6139            } else {
 6140                MultiBufferRow(selection.end.row)
 6141            };
 6142
 6143            if let Some(last_row_range) = row_ranges.last_mut() {
 6144                if start <= last_row_range.end {
 6145                    last_row_range.end = end;
 6146                    continue;
 6147                }
 6148            }
 6149            row_ranges.push(start..end);
 6150        }
 6151
 6152        let snapshot = self.buffer.read(cx).snapshot(cx);
 6153        let mut cursor_positions = Vec::new();
 6154        for row_range in &row_ranges {
 6155            let anchor = snapshot.anchor_before(Point::new(
 6156                row_range.end.previous_row().0,
 6157                snapshot.line_len(row_range.end.previous_row()),
 6158            ));
 6159            cursor_positions.push(anchor..anchor);
 6160        }
 6161
 6162        self.transact(cx, |this, cx| {
 6163            for row_range in row_ranges.into_iter().rev() {
 6164                for row in row_range.iter_rows().rev() {
 6165                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6166                    let next_line_row = row.next_row();
 6167                    let indent = snapshot.indent_size_for_line(next_line_row);
 6168                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6169
 6170                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6171                        " "
 6172                    } else {
 6173                        ""
 6174                    };
 6175
 6176                    this.buffer.update(cx, |buffer, cx| {
 6177                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6178                    });
 6179                }
 6180            }
 6181
 6182            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6183                s.select_anchor_ranges(cursor_positions)
 6184            });
 6185        });
 6186    }
 6187
 6188    pub fn sort_lines_case_sensitive(
 6189        &mut self,
 6190        _: &SortLinesCaseSensitive,
 6191        cx: &mut ViewContext<Self>,
 6192    ) {
 6193        self.manipulate_lines(cx, |lines| lines.sort())
 6194    }
 6195
 6196    pub fn sort_lines_case_insensitive(
 6197        &mut self,
 6198        _: &SortLinesCaseInsensitive,
 6199        cx: &mut ViewContext<Self>,
 6200    ) {
 6201        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6202    }
 6203
 6204    pub fn unique_lines_case_insensitive(
 6205        &mut self,
 6206        _: &UniqueLinesCaseInsensitive,
 6207        cx: &mut ViewContext<Self>,
 6208    ) {
 6209        self.manipulate_lines(cx, |lines| {
 6210            let mut seen = HashSet::default();
 6211            lines.retain(|line| seen.insert(line.to_lowercase()));
 6212        })
 6213    }
 6214
 6215    pub fn unique_lines_case_sensitive(
 6216        &mut self,
 6217        _: &UniqueLinesCaseSensitive,
 6218        cx: &mut ViewContext<Self>,
 6219    ) {
 6220        self.manipulate_lines(cx, |lines| {
 6221            let mut seen = HashSet::default();
 6222            lines.retain(|line| seen.insert(*line));
 6223        })
 6224    }
 6225
 6226    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6227        let mut revert_changes = HashMap::default();
 6228        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6229        for hunk in hunks_for_rows(
 6230            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6231            &multi_buffer_snapshot,
 6232        ) {
 6233            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6234        }
 6235        if !revert_changes.is_empty() {
 6236            self.transact(cx, |editor, cx| {
 6237                editor.revert(revert_changes, cx);
 6238            });
 6239        }
 6240    }
 6241
 6242    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6243        let Some(project) = self.project.clone() else {
 6244            return;
 6245        };
 6246        self.reload(project, cx).detach_and_notify_err(cx);
 6247    }
 6248
 6249    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6250        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6251        if !revert_changes.is_empty() {
 6252            self.transact(cx, |editor, cx| {
 6253                editor.revert(revert_changes, cx);
 6254            });
 6255        }
 6256    }
 6257
 6258    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6259        let snapshot = self.buffer.read(cx).snapshot(cx);
 6260        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6261        let mut ranges_by_buffer = HashMap::default();
 6262        self.transact(cx, |editor, cx| {
 6263            for hunk in hunks {
 6264                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6265                    ranges_by_buffer
 6266                        .entry(buffer.clone())
 6267                        .or_insert_with(Vec::new)
 6268                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 6269                }
 6270            }
 6271
 6272            for (buffer, ranges) in ranges_by_buffer {
 6273                buffer.update(cx, |buffer, cx| {
 6274                    buffer.merge_into_base(ranges, cx);
 6275                });
 6276            }
 6277        });
 6278    }
 6279
 6280    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6281        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6282            let project_path = buffer.read(cx).project_path(cx)?;
 6283            let project = self.project.as_ref()?.read(cx);
 6284            let entry = project.entry_for_path(&project_path, cx)?;
 6285            let abs_path = project.absolute_path(&project_path, cx)?;
 6286            let parent = if entry.is_symlink {
 6287                abs_path.canonicalize().ok()?
 6288            } else {
 6289                abs_path
 6290            }
 6291            .parent()?
 6292            .to_path_buf();
 6293            Some(parent)
 6294        }) {
 6295            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6296        }
 6297    }
 6298
 6299    fn gather_revert_changes(
 6300        &mut self,
 6301        selections: &[Selection<Anchor>],
 6302        cx: &mut ViewContext<'_, Editor>,
 6303    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6304        let mut revert_changes = HashMap::default();
 6305        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6306        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6307            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6308        }
 6309        revert_changes
 6310    }
 6311
 6312    pub fn prepare_revert_change(
 6313        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6314        multi_buffer: &Model<MultiBuffer>,
 6315        hunk: &MultiBufferDiffHunk,
 6316        cx: &AppContext,
 6317    ) -> Option<()> {
 6318        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6319        let buffer = buffer.read(cx);
 6320        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6321        let buffer_snapshot = buffer.snapshot();
 6322        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6323        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6324            probe
 6325                .0
 6326                .start
 6327                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6328                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6329        }) {
 6330            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6331            Some(())
 6332        } else {
 6333            None
 6334        }
 6335    }
 6336
 6337    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6338        self.manipulate_lines(cx, |lines| lines.reverse())
 6339    }
 6340
 6341    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6342        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6343    }
 6344
 6345    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6346    where
 6347        Fn: FnMut(&mut Vec<&str>),
 6348    {
 6349        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6350        let buffer = self.buffer.read(cx).snapshot(cx);
 6351
 6352        let mut edits = Vec::new();
 6353
 6354        let selections = self.selections.all::<Point>(cx);
 6355        let mut selections = selections.iter().peekable();
 6356        let mut contiguous_row_selections = Vec::new();
 6357        let mut new_selections = Vec::new();
 6358        let mut added_lines = 0;
 6359        let mut removed_lines = 0;
 6360
 6361        while let Some(selection) = selections.next() {
 6362            let (start_row, end_row) = consume_contiguous_rows(
 6363                &mut contiguous_row_selections,
 6364                selection,
 6365                &display_map,
 6366                &mut selections,
 6367            );
 6368
 6369            let start_point = Point::new(start_row.0, 0);
 6370            let end_point = Point::new(
 6371                end_row.previous_row().0,
 6372                buffer.line_len(end_row.previous_row()),
 6373            );
 6374            let text = buffer
 6375                .text_for_range(start_point..end_point)
 6376                .collect::<String>();
 6377
 6378            let mut lines = text.split('\n').collect_vec();
 6379
 6380            let lines_before = lines.len();
 6381            callback(&mut lines);
 6382            let lines_after = lines.len();
 6383
 6384            edits.push((start_point..end_point, lines.join("\n")));
 6385
 6386            // Selections must change based on added and removed line count
 6387            let start_row =
 6388                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6389            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6390            new_selections.push(Selection {
 6391                id: selection.id,
 6392                start: start_row,
 6393                end: end_row,
 6394                goal: SelectionGoal::None,
 6395                reversed: selection.reversed,
 6396            });
 6397
 6398            if lines_after > lines_before {
 6399                added_lines += lines_after - lines_before;
 6400            } else if lines_before > lines_after {
 6401                removed_lines += lines_before - lines_after;
 6402            }
 6403        }
 6404
 6405        self.transact(cx, |this, cx| {
 6406            let buffer = this.buffer.update(cx, |buffer, cx| {
 6407                buffer.edit(edits, None, cx);
 6408                buffer.snapshot(cx)
 6409            });
 6410
 6411            // Recalculate offsets on newly edited buffer
 6412            let new_selections = new_selections
 6413                .iter()
 6414                .map(|s| {
 6415                    let start_point = Point::new(s.start.0, 0);
 6416                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6417                    Selection {
 6418                        id: s.id,
 6419                        start: buffer.point_to_offset(start_point),
 6420                        end: buffer.point_to_offset(end_point),
 6421                        goal: s.goal,
 6422                        reversed: s.reversed,
 6423                    }
 6424                })
 6425                .collect();
 6426
 6427            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6428                s.select(new_selections);
 6429            });
 6430
 6431            this.request_autoscroll(Autoscroll::fit(), cx);
 6432        });
 6433    }
 6434
 6435    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6436        self.manipulate_text(cx, |text| text.to_uppercase())
 6437    }
 6438
 6439    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6440        self.manipulate_text(cx, |text| text.to_lowercase())
 6441    }
 6442
 6443    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6444        self.manipulate_text(cx, |text| {
 6445            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6446            // https://github.com/rutrum/convert-case/issues/16
 6447            text.split('\n')
 6448                .map(|line| line.to_case(Case::Title))
 6449                .join("\n")
 6450        })
 6451    }
 6452
 6453    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6454        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6455    }
 6456
 6457    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6458        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6459    }
 6460
 6461    pub fn convert_to_upper_camel_case(
 6462        &mut self,
 6463        _: &ConvertToUpperCamelCase,
 6464        cx: &mut ViewContext<Self>,
 6465    ) {
 6466        self.manipulate_text(cx, |text| {
 6467            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6468            // https://github.com/rutrum/convert-case/issues/16
 6469            text.split('\n')
 6470                .map(|line| line.to_case(Case::UpperCamel))
 6471                .join("\n")
 6472        })
 6473    }
 6474
 6475    pub fn convert_to_lower_camel_case(
 6476        &mut self,
 6477        _: &ConvertToLowerCamelCase,
 6478        cx: &mut ViewContext<Self>,
 6479    ) {
 6480        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6481    }
 6482
 6483    pub fn convert_to_opposite_case(
 6484        &mut self,
 6485        _: &ConvertToOppositeCase,
 6486        cx: &mut ViewContext<Self>,
 6487    ) {
 6488        self.manipulate_text(cx, |text| {
 6489            text.chars()
 6490                .fold(String::with_capacity(text.len()), |mut t, c| {
 6491                    if c.is_uppercase() {
 6492                        t.extend(c.to_lowercase());
 6493                    } else {
 6494                        t.extend(c.to_uppercase());
 6495                    }
 6496                    t
 6497                })
 6498        })
 6499    }
 6500
 6501    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6502    where
 6503        Fn: FnMut(&str) -> String,
 6504    {
 6505        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6506        let buffer = self.buffer.read(cx).snapshot(cx);
 6507
 6508        let mut new_selections = Vec::new();
 6509        let mut edits = Vec::new();
 6510        let mut selection_adjustment = 0i32;
 6511
 6512        for selection in self.selections.all::<usize>(cx) {
 6513            let selection_is_empty = selection.is_empty();
 6514
 6515            let (start, end) = if selection_is_empty {
 6516                let word_range = movement::surrounding_word(
 6517                    &display_map,
 6518                    selection.start.to_display_point(&display_map),
 6519                );
 6520                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6521                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6522                (start, end)
 6523            } else {
 6524                (selection.start, selection.end)
 6525            };
 6526
 6527            let text = buffer.text_for_range(start..end).collect::<String>();
 6528            let old_length = text.len() as i32;
 6529            let text = callback(&text);
 6530
 6531            new_selections.push(Selection {
 6532                start: (start as i32 - selection_adjustment) as usize,
 6533                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6534                goal: SelectionGoal::None,
 6535                ..selection
 6536            });
 6537
 6538            selection_adjustment += old_length - text.len() as i32;
 6539
 6540            edits.push((start..end, text));
 6541        }
 6542
 6543        self.transact(cx, |this, cx| {
 6544            this.buffer.update(cx, |buffer, cx| {
 6545                buffer.edit(edits, None, cx);
 6546            });
 6547
 6548            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6549                s.select(new_selections);
 6550            });
 6551
 6552            this.request_autoscroll(Autoscroll::fit(), cx);
 6553        });
 6554    }
 6555
 6556    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6557        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6558        let buffer = &display_map.buffer_snapshot;
 6559        let selections = self.selections.all::<Point>(cx);
 6560
 6561        let mut edits = Vec::new();
 6562        let mut selections_iter = selections.iter().peekable();
 6563        while let Some(selection) = selections_iter.next() {
 6564            // Avoid duplicating the same lines twice.
 6565            let mut rows = selection.spanned_rows(false, &display_map);
 6566
 6567            while let Some(next_selection) = selections_iter.peek() {
 6568                let next_rows = next_selection.spanned_rows(false, &display_map);
 6569                if next_rows.start < rows.end {
 6570                    rows.end = next_rows.end;
 6571                    selections_iter.next().unwrap();
 6572                } else {
 6573                    break;
 6574                }
 6575            }
 6576
 6577            // Copy the text from the selected row region and splice it either at the start
 6578            // or end of the region.
 6579            let start = Point::new(rows.start.0, 0);
 6580            let end = Point::new(
 6581                rows.end.previous_row().0,
 6582                buffer.line_len(rows.end.previous_row()),
 6583            );
 6584            let text = buffer
 6585                .text_for_range(start..end)
 6586                .chain(Some("\n"))
 6587                .collect::<String>();
 6588            let insert_location = if upwards {
 6589                Point::new(rows.end.0, 0)
 6590            } else {
 6591                start
 6592            };
 6593            edits.push((insert_location..insert_location, text));
 6594        }
 6595
 6596        self.transact(cx, |this, cx| {
 6597            this.buffer.update(cx, |buffer, cx| {
 6598                buffer.edit(edits, None, cx);
 6599            });
 6600
 6601            this.request_autoscroll(Autoscroll::fit(), cx);
 6602        });
 6603    }
 6604
 6605    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6606        self.duplicate_line(true, cx);
 6607    }
 6608
 6609    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6610        self.duplicate_line(false, cx);
 6611    }
 6612
 6613    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6615        let buffer = self.buffer.read(cx).snapshot(cx);
 6616
 6617        let mut edits = Vec::new();
 6618        let mut unfold_ranges = Vec::new();
 6619        let mut refold_ranges = Vec::new();
 6620
 6621        let selections = self.selections.all::<Point>(cx);
 6622        let mut selections = selections.iter().peekable();
 6623        let mut contiguous_row_selections = Vec::new();
 6624        let mut new_selections = Vec::new();
 6625
 6626        while let Some(selection) = selections.next() {
 6627            // Find all the selections that span a contiguous row range
 6628            let (start_row, end_row) = consume_contiguous_rows(
 6629                &mut contiguous_row_selections,
 6630                selection,
 6631                &display_map,
 6632                &mut selections,
 6633            );
 6634
 6635            // Move the text spanned by the row range to be before the line preceding the row range
 6636            if start_row.0 > 0 {
 6637                let range_to_move = Point::new(
 6638                    start_row.previous_row().0,
 6639                    buffer.line_len(start_row.previous_row()),
 6640                )
 6641                    ..Point::new(
 6642                        end_row.previous_row().0,
 6643                        buffer.line_len(end_row.previous_row()),
 6644                    );
 6645                let insertion_point = display_map
 6646                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6647                    .0;
 6648
 6649                // Don't move lines across excerpts
 6650                if buffer
 6651                    .excerpt_boundaries_in_range((
 6652                        Bound::Excluded(insertion_point),
 6653                        Bound::Included(range_to_move.end),
 6654                    ))
 6655                    .next()
 6656                    .is_none()
 6657                {
 6658                    let text = buffer
 6659                        .text_for_range(range_to_move.clone())
 6660                        .flat_map(|s| s.chars())
 6661                        .skip(1)
 6662                        .chain(['\n'])
 6663                        .collect::<String>();
 6664
 6665                    edits.push((
 6666                        buffer.anchor_after(range_to_move.start)
 6667                            ..buffer.anchor_before(range_to_move.end),
 6668                        String::new(),
 6669                    ));
 6670                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6671                    edits.push((insertion_anchor..insertion_anchor, text));
 6672
 6673                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6674
 6675                    // Move selections up
 6676                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6677                        |mut selection| {
 6678                            selection.start.row -= row_delta;
 6679                            selection.end.row -= row_delta;
 6680                            selection
 6681                        },
 6682                    ));
 6683
 6684                    // Move folds up
 6685                    unfold_ranges.push(range_to_move.clone());
 6686                    for fold in display_map.folds_in_range(
 6687                        buffer.anchor_before(range_to_move.start)
 6688                            ..buffer.anchor_after(range_to_move.end),
 6689                    ) {
 6690                        let mut start = fold.range.start.to_point(&buffer);
 6691                        let mut end = fold.range.end.to_point(&buffer);
 6692                        start.row -= row_delta;
 6693                        end.row -= row_delta;
 6694                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6695                    }
 6696                }
 6697            }
 6698
 6699            // If we didn't move line(s), preserve the existing selections
 6700            new_selections.append(&mut contiguous_row_selections);
 6701        }
 6702
 6703        self.transact(cx, |this, cx| {
 6704            this.unfold_ranges(unfold_ranges, true, true, cx);
 6705            this.buffer.update(cx, |buffer, cx| {
 6706                for (range, text) in edits {
 6707                    buffer.edit([(range, text)], None, cx);
 6708                }
 6709            });
 6710            this.fold_ranges(refold_ranges, true, cx);
 6711            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6712                s.select(new_selections);
 6713            })
 6714        });
 6715    }
 6716
 6717    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6719        let buffer = self.buffer.read(cx).snapshot(cx);
 6720
 6721        let mut edits = Vec::new();
 6722        let mut unfold_ranges = Vec::new();
 6723        let mut refold_ranges = Vec::new();
 6724
 6725        let selections = self.selections.all::<Point>(cx);
 6726        let mut selections = selections.iter().peekable();
 6727        let mut contiguous_row_selections = Vec::new();
 6728        let mut new_selections = Vec::new();
 6729
 6730        while let Some(selection) = selections.next() {
 6731            // Find all the selections that span a contiguous row range
 6732            let (start_row, end_row) = consume_contiguous_rows(
 6733                &mut contiguous_row_selections,
 6734                selection,
 6735                &display_map,
 6736                &mut selections,
 6737            );
 6738
 6739            // Move the text spanned by the row range to be after the last line of the row range
 6740            if end_row.0 <= buffer.max_point().row {
 6741                let range_to_move =
 6742                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6743                let insertion_point = display_map
 6744                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6745                    .0;
 6746
 6747                // Don't move lines across excerpt boundaries
 6748                if buffer
 6749                    .excerpt_boundaries_in_range((
 6750                        Bound::Excluded(range_to_move.start),
 6751                        Bound::Included(insertion_point),
 6752                    ))
 6753                    .next()
 6754                    .is_none()
 6755                {
 6756                    let mut text = String::from("\n");
 6757                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6758                    text.pop(); // Drop trailing newline
 6759                    edits.push((
 6760                        buffer.anchor_after(range_to_move.start)
 6761                            ..buffer.anchor_before(range_to_move.end),
 6762                        String::new(),
 6763                    ));
 6764                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6765                    edits.push((insertion_anchor..insertion_anchor, text));
 6766
 6767                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6768
 6769                    // Move selections down
 6770                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6771                        |mut selection| {
 6772                            selection.start.row += row_delta;
 6773                            selection.end.row += row_delta;
 6774                            selection
 6775                        },
 6776                    ));
 6777
 6778                    // Move folds down
 6779                    unfold_ranges.push(range_to_move.clone());
 6780                    for fold in display_map.folds_in_range(
 6781                        buffer.anchor_before(range_to_move.start)
 6782                            ..buffer.anchor_after(range_to_move.end),
 6783                    ) {
 6784                        let mut start = fold.range.start.to_point(&buffer);
 6785                        let mut end = fold.range.end.to_point(&buffer);
 6786                        start.row += row_delta;
 6787                        end.row += row_delta;
 6788                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6789                    }
 6790                }
 6791            }
 6792
 6793            // If we didn't move line(s), preserve the existing selections
 6794            new_selections.append(&mut contiguous_row_selections);
 6795        }
 6796
 6797        self.transact(cx, |this, cx| {
 6798            this.unfold_ranges(unfold_ranges, true, true, cx);
 6799            this.buffer.update(cx, |buffer, cx| {
 6800                for (range, text) in edits {
 6801                    buffer.edit([(range, text)], None, cx);
 6802                }
 6803            });
 6804            this.fold_ranges(refold_ranges, true, cx);
 6805            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6806        });
 6807    }
 6808
 6809    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6810        let text_layout_details = &self.text_layout_details(cx);
 6811        self.transact(cx, |this, cx| {
 6812            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6813                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6814                let line_mode = s.line_mode;
 6815                s.move_with(|display_map, selection| {
 6816                    if !selection.is_empty() || line_mode {
 6817                        return;
 6818                    }
 6819
 6820                    let mut head = selection.head();
 6821                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6822                    if head.column() == display_map.line_len(head.row()) {
 6823                        transpose_offset = display_map
 6824                            .buffer_snapshot
 6825                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6826                    }
 6827
 6828                    if transpose_offset == 0 {
 6829                        return;
 6830                    }
 6831
 6832                    *head.column_mut() += 1;
 6833                    head = display_map.clip_point(head, Bias::Right);
 6834                    let goal = SelectionGoal::HorizontalPosition(
 6835                        display_map
 6836                            .x_for_display_point(head, text_layout_details)
 6837                            .into(),
 6838                    );
 6839                    selection.collapse_to(head, goal);
 6840
 6841                    let transpose_start = display_map
 6842                        .buffer_snapshot
 6843                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6844                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6845                        let transpose_end = display_map
 6846                            .buffer_snapshot
 6847                            .clip_offset(transpose_offset + 1, Bias::Right);
 6848                        if let Some(ch) =
 6849                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6850                        {
 6851                            edits.push((transpose_start..transpose_offset, String::new()));
 6852                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6853                        }
 6854                    }
 6855                });
 6856                edits
 6857            });
 6858            this.buffer
 6859                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6860            let selections = this.selections.all::<usize>(cx);
 6861            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6862                s.select(selections);
 6863            });
 6864        });
 6865    }
 6866
 6867    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6868        self.rewrap_impl(true, cx)
 6869    }
 6870
 6871    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6872        let buffer = self.buffer.read(cx).snapshot(cx);
 6873        let selections = self.selections.all::<Point>(cx);
 6874        let mut selections = selections.iter().peekable();
 6875
 6876        let mut edits = Vec::new();
 6877        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6878
 6879        while let Some(selection) = selections.next() {
 6880            let mut start_row = selection.start.row;
 6881            let mut end_row = selection.end.row;
 6882
 6883            // Skip selections that overlap with a range that has already been rewrapped.
 6884            let selection_range = start_row..end_row;
 6885            if rewrapped_row_ranges
 6886                .iter()
 6887                .any(|range| range.overlaps(&selection_range))
 6888            {
 6889                continue;
 6890            }
 6891
 6892            let mut should_rewrap = !only_text;
 6893
 6894            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6895                match language_scope.language_name().0.as_ref() {
 6896                    "Markdown" | "Plain Text" => {
 6897                        should_rewrap = true;
 6898                    }
 6899                    _ => {}
 6900                }
 6901            }
 6902
 6903            // Since not all lines in the selection may be at the same indent
 6904            // level, choose the indent size that is the most common between all
 6905            // of the lines.
 6906            //
 6907            // If there is a tie, we use the deepest indent.
 6908            let (indent_size, indent_end) = {
 6909                let mut indent_size_occurrences = HashMap::default();
 6910                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6911
 6912                for row in start_row..=end_row {
 6913                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6914                    rows_by_indent_size.entry(indent).or_default().push(row);
 6915                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6916                }
 6917
 6918                let indent_size = indent_size_occurrences
 6919                    .into_iter()
 6920                    .max_by_key(|(indent, count)| (*count, indent.len))
 6921                    .map(|(indent, _)| indent)
 6922                    .unwrap_or_default();
 6923                let row = rows_by_indent_size[&indent_size][0];
 6924                let indent_end = Point::new(row, indent_size.len);
 6925
 6926                (indent_size, indent_end)
 6927            };
 6928
 6929            let mut line_prefix = indent_size.chars().collect::<String>();
 6930
 6931            if let Some(comment_prefix) =
 6932                buffer
 6933                    .language_scope_at(selection.head())
 6934                    .and_then(|language| {
 6935                        language
 6936                            .line_comment_prefixes()
 6937                            .iter()
 6938                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6939                            .cloned()
 6940                    })
 6941            {
 6942                line_prefix.push_str(&comment_prefix);
 6943                should_rewrap = true;
 6944            }
 6945
 6946            if selection.is_empty() {
 6947                'expand_upwards: while start_row > 0 {
 6948                    let prev_row = start_row - 1;
 6949                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6950                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6951                    {
 6952                        start_row = prev_row;
 6953                    } else {
 6954                        break 'expand_upwards;
 6955                    }
 6956                }
 6957
 6958                'expand_downwards: while end_row < buffer.max_point().row {
 6959                    let next_row = end_row + 1;
 6960                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6961                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6962                    {
 6963                        end_row = next_row;
 6964                    } else {
 6965                        break 'expand_downwards;
 6966                    }
 6967                }
 6968            }
 6969
 6970            if !should_rewrap {
 6971                continue;
 6972            }
 6973
 6974            let start = Point::new(start_row, 0);
 6975            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6976            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6977            let Some(lines_without_prefixes) = selection_text
 6978                .lines()
 6979                .map(|line| {
 6980                    line.strip_prefix(&line_prefix)
 6981                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6982                        .ok_or_else(|| {
 6983                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6984                        })
 6985                })
 6986                .collect::<Result<Vec<_>, _>>()
 6987                .log_err()
 6988            else {
 6989                continue;
 6990            };
 6991
 6992            let unwrapped_text = lines_without_prefixes.join(" ");
 6993            let wrap_column = buffer
 6994                .settings_at(Point::new(start_row, 0), cx)
 6995                .preferred_line_length as usize;
 6996            let mut wrapped_text = String::new();
 6997            let mut current_line = line_prefix.clone();
 6998            for word in unwrapped_text.split_whitespace() {
 6999                if current_line.len() + word.len() >= wrap_column {
 7000                    wrapped_text.push_str(&current_line);
 7001                    wrapped_text.push('\n');
 7002                    current_line.truncate(line_prefix.len());
 7003                }
 7004
 7005                if current_line.len() > line_prefix.len() {
 7006                    current_line.push(' ');
 7007                }
 7008
 7009                current_line.push_str(word);
 7010            }
 7011
 7012            if !current_line.is_empty() {
 7013                wrapped_text.push_str(&current_line);
 7014            }
 7015
 7016            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7017            let mut offset = start.to_offset(&buffer);
 7018            let mut moved_since_edit = true;
 7019
 7020            for change in diff.iter_all_changes() {
 7021                let value = change.value();
 7022                match change.tag() {
 7023                    ChangeTag::Equal => {
 7024                        offset += value.len();
 7025                        moved_since_edit = true;
 7026                    }
 7027                    ChangeTag::Delete => {
 7028                        let start = buffer.anchor_after(offset);
 7029                        let end = buffer.anchor_before(offset + value.len());
 7030
 7031                        if moved_since_edit {
 7032                            edits.push((start..end, String::new()));
 7033                        } else {
 7034                            edits.last_mut().unwrap().0.end = end;
 7035                        }
 7036
 7037                        offset += value.len();
 7038                        moved_since_edit = false;
 7039                    }
 7040                    ChangeTag::Insert => {
 7041                        if moved_since_edit {
 7042                            let anchor = buffer.anchor_after(offset);
 7043                            edits.push((anchor..anchor, value.to_string()));
 7044                        } else {
 7045                            edits.last_mut().unwrap().1.push_str(value);
 7046                        }
 7047
 7048                        moved_since_edit = false;
 7049                    }
 7050                }
 7051            }
 7052
 7053            rewrapped_row_ranges.push(start_row..=end_row);
 7054        }
 7055
 7056        self.buffer
 7057            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7058    }
 7059
 7060    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7061        let mut text = String::new();
 7062        let buffer = self.buffer.read(cx).snapshot(cx);
 7063        let mut selections = self.selections.all::<Point>(cx);
 7064        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7065        {
 7066            let max_point = buffer.max_point();
 7067            let mut is_first = true;
 7068            for selection in &mut selections {
 7069                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7070                if is_entire_line {
 7071                    selection.start = Point::new(selection.start.row, 0);
 7072                    if !selection.is_empty() && selection.end.column == 0 {
 7073                        selection.end = cmp::min(max_point, selection.end);
 7074                    } else {
 7075                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7076                    }
 7077                    selection.goal = SelectionGoal::None;
 7078                }
 7079                if is_first {
 7080                    is_first = false;
 7081                } else {
 7082                    text += "\n";
 7083                }
 7084                let mut len = 0;
 7085                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7086                    text.push_str(chunk);
 7087                    len += chunk.len();
 7088                }
 7089                clipboard_selections.push(ClipboardSelection {
 7090                    len,
 7091                    is_entire_line,
 7092                    first_line_indent: buffer
 7093                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7094                        .len,
 7095                });
 7096            }
 7097        }
 7098
 7099        self.transact(cx, |this, cx| {
 7100            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7101                s.select(selections);
 7102            });
 7103            this.insert("", cx);
 7104            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7105                text,
 7106                clipboard_selections,
 7107            ));
 7108        });
 7109    }
 7110
 7111    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7112        let selections = self.selections.all::<Point>(cx);
 7113        let buffer = self.buffer.read(cx).read(cx);
 7114        let mut text = String::new();
 7115
 7116        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7117        {
 7118            let max_point = buffer.max_point();
 7119            let mut is_first = true;
 7120            for selection in selections.iter() {
 7121                let mut start = selection.start;
 7122                let mut end = selection.end;
 7123                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7124                if is_entire_line {
 7125                    start = Point::new(start.row, 0);
 7126                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7127                }
 7128                if is_first {
 7129                    is_first = false;
 7130                } else {
 7131                    text += "\n";
 7132                }
 7133                let mut len = 0;
 7134                for chunk in buffer.text_for_range(start..end) {
 7135                    text.push_str(chunk);
 7136                    len += chunk.len();
 7137                }
 7138                clipboard_selections.push(ClipboardSelection {
 7139                    len,
 7140                    is_entire_line,
 7141                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7142                });
 7143            }
 7144        }
 7145
 7146        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7147            text,
 7148            clipboard_selections,
 7149        ));
 7150    }
 7151
 7152    pub fn do_paste(
 7153        &mut self,
 7154        text: &String,
 7155        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7156        handle_entire_lines: bool,
 7157        cx: &mut ViewContext<Self>,
 7158    ) {
 7159        if self.read_only(cx) {
 7160            return;
 7161        }
 7162
 7163        let clipboard_text = Cow::Borrowed(text);
 7164
 7165        self.transact(cx, |this, cx| {
 7166            if let Some(mut clipboard_selections) = clipboard_selections {
 7167                let old_selections = this.selections.all::<usize>(cx);
 7168                let all_selections_were_entire_line =
 7169                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7170                let first_selection_indent_column =
 7171                    clipboard_selections.first().map(|s| s.first_line_indent);
 7172                if clipboard_selections.len() != old_selections.len() {
 7173                    clipboard_selections.drain(..);
 7174                }
 7175
 7176                this.buffer.update(cx, |buffer, cx| {
 7177                    let snapshot = buffer.read(cx);
 7178                    let mut start_offset = 0;
 7179                    let mut edits = Vec::new();
 7180                    let mut original_indent_columns = Vec::new();
 7181                    for (ix, selection) in old_selections.iter().enumerate() {
 7182                        let to_insert;
 7183                        let entire_line;
 7184                        let original_indent_column;
 7185                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7186                            let end_offset = start_offset + clipboard_selection.len;
 7187                            to_insert = &clipboard_text[start_offset..end_offset];
 7188                            entire_line = clipboard_selection.is_entire_line;
 7189                            start_offset = end_offset + 1;
 7190                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7191                        } else {
 7192                            to_insert = clipboard_text.as_str();
 7193                            entire_line = all_selections_were_entire_line;
 7194                            original_indent_column = first_selection_indent_column
 7195                        }
 7196
 7197                        // If the corresponding selection was empty when this slice of the
 7198                        // clipboard text was written, then the entire line containing the
 7199                        // selection was copied. If this selection is also currently empty,
 7200                        // then paste the line before the current line of the buffer.
 7201                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7202                            let column = selection.start.to_point(&snapshot).column as usize;
 7203                            let line_start = selection.start - column;
 7204                            line_start..line_start
 7205                        } else {
 7206                            selection.range()
 7207                        };
 7208
 7209                        edits.push((range, to_insert));
 7210                        original_indent_columns.extend(original_indent_column);
 7211                    }
 7212                    drop(snapshot);
 7213
 7214                    buffer.edit(
 7215                        edits,
 7216                        Some(AutoindentMode::Block {
 7217                            original_indent_columns,
 7218                        }),
 7219                        cx,
 7220                    );
 7221                });
 7222
 7223                let selections = this.selections.all::<usize>(cx);
 7224                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7225            } else {
 7226                this.insert(&clipboard_text, cx);
 7227            }
 7228        });
 7229    }
 7230
 7231    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7232        if let Some(item) = cx.read_from_clipboard() {
 7233            let entries = item.entries();
 7234
 7235            match entries.first() {
 7236                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7237                // of all the pasted entries.
 7238                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7239                    .do_paste(
 7240                        clipboard_string.text(),
 7241                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7242                        true,
 7243                        cx,
 7244                    ),
 7245                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7246            }
 7247        }
 7248    }
 7249
 7250    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7251        if self.read_only(cx) {
 7252            return;
 7253        }
 7254
 7255        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7256            if let Some((selections, _)) =
 7257                self.selection_history.transaction(transaction_id).cloned()
 7258            {
 7259                self.change_selections(None, cx, |s| {
 7260                    s.select_anchors(selections.to_vec());
 7261                });
 7262            }
 7263            self.request_autoscroll(Autoscroll::fit(), cx);
 7264            self.unmark_text(cx);
 7265            self.refresh_inline_completion(true, false, cx);
 7266            cx.emit(EditorEvent::Edited { transaction_id });
 7267            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7268        }
 7269    }
 7270
 7271    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7272        if self.read_only(cx) {
 7273            return;
 7274        }
 7275
 7276        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7277            if let Some((_, Some(selections))) =
 7278                self.selection_history.transaction(transaction_id).cloned()
 7279            {
 7280                self.change_selections(None, cx, |s| {
 7281                    s.select_anchors(selections.to_vec());
 7282                });
 7283            }
 7284            self.request_autoscroll(Autoscroll::fit(), cx);
 7285            self.unmark_text(cx);
 7286            self.refresh_inline_completion(true, false, cx);
 7287            cx.emit(EditorEvent::Edited { transaction_id });
 7288        }
 7289    }
 7290
 7291    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7292        self.buffer
 7293            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7294    }
 7295
 7296    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7297        self.buffer
 7298            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7299    }
 7300
 7301    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7302        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7303            let line_mode = s.line_mode;
 7304            s.move_with(|map, selection| {
 7305                let cursor = if selection.is_empty() && !line_mode {
 7306                    movement::left(map, selection.start)
 7307                } else {
 7308                    selection.start
 7309                };
 7310                selection.collapse_to(cursor, SelectionGoal::None);
 7311            });
 7312        })
 7313    }
 7314
 7315    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7316        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7317            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7318        })
 7319    }
 7320
 7321    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7322        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7323            let line_mode = s.line_mode;
 7324            s.move_with(|map, selection| {
 7325                let cursor = if selection.is_empty() && !line_mode {
 7326                    movement::right(map, selection.end)
 7327                } else {
 7328                    selection.end
 7329                };
 7330                selection.collapse_to(cursor, SelectionGoal::None)
 7331            });
 7332        })
 7333    }
 7334
 7335    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7337            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7338        })
 7339    }
 7340
 7341    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7342        if self.take_rename(true, cx).is_some() {
 7343            return;
 7344        }
 7345
 7346        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7347            cx.propagate();
 7348            return;
 7349        }
 7350
 7351        let text_layout_details = &self.text_layout_details(cx);
 7352        let selection_count = self.selections.count();
 7353        let first_selection = self.selections.first_anchor();
 7354
 7355        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7356            let line_mode = s.line_mode;
 7357            s.move_with(|map, selection| {
 7358                if !selection.is_empty() && !line_mode {
 7359                    selection.goal = SelectionGoal::None;
 7360                }
 7361                let (cursor, goal) = movement::up(
 7362                    map,
 7363                    selection.start,
 7364                    selection.goal,
 7365                    false,
 7366                    text_layout_details,
 7367                );
 7368                selection.collapse_to(cursor, goal);
 7369            });
 7370        });
 7371
 7372        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7373        {
 7374            cx.propagate();
 7375        }
 7376    }
 7377
 7378    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7379        if self.take_rename(true, cx).is_some() {
 7380            return;
 7381        }
 7382
 7383        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7384            cx.propagate();
 7385            return;
 7386        }
 7387
 7388        let text_layout_details = &self.text_layout_details(cx);
 7389
 7390        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7391            let line_mode = s.line_mode;
 7392            s.move_with(|map, selection| {
 7393                if !selection.is_empty() && !line_mode {
 7394                    selection.goal = SelectionGoal::None;
 7395                }
 7396                let (cursor, goal) = movement::up_by_rows(
 7397                    map,
 7398                    selection.start,
 7399                    action.lines,
 7400                    selection.goal,
 7401                    false,
 7402                    text_layout_details,
 7403                );
 7404                selection.collapse_to(cursor, goal);
 7405            });
 7406        })
 7407    }
 7408
 7409    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7410        if self.take_rename(true, cx).is_some() {
 7411            return;
 7412        }
 7413
 7414        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7415            cx.propagate();
 7416            return;
 7417        }
 7418
 7419        let text_layout_details = &self.text_layout_details(cx);
 7420
 7421        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7422            let line_mode = s.line_mode;
 7423            s.move_with(|map, selection| {
 7424                if !selection.is_empty() && !line_mode {
 7425                    selection.goal = SelectionGoal::None;
 7426                }
 7427                let (cursor, goal) = movement::down_by_rows(
 7428                    map,
 7429                    selection.start,
 7430                    action.lines,
 7431                    selection.goal,
 7432                    false,
 7433                    text_layout_details,
 7434                );
 7435                selection.collapse_to(cursor, goal);
 7436            });
 7437        })
 7438    }
 7439
 7440    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7441        let text_layout_details = &self.text_layout_details(cx);
 7442        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7443            s.move_heads_with(|map, head, goal| {
 7444                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7445            })
 7446        })
 7447    }
 7448
 7449    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7450        let text_layout_details = &self.text_layout_details(cx);
 7451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7452            s.move_heads_with(|map, head, goal| {
 7453                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7454            })
 7455        })
 7456    }
 7457
 7458    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7459        let Some(row_count) = self.visible_row_count() else {
 7460            return;
 7461        };
 7462
 7463        let text_layout_details = &self.text_layout_details(cx);
 7464
 7465        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7466            s.move_heads_with(|map, head, goal| {
 7467                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7468            })
 7469        })
 7470    }
 7471
 7472    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7473        if self.take_rename(true, cx).is_some() {
 7474            return;
 7475        }
 7476
 7477        if self
 7478            .context_menu
 7479            .write()
 7480            .as_mut()
 7481            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7482            .unwrap_or(false)
 7483        {
 7484            return;
 7485        }
 7486
 7487        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7488            cx.propagate();
 7489            return;
 7490        }
 7491
 7492        let Some(row_count) = self.visible_row_count() else {
 7493            return;
 7494        };
 7495
 7496        let autoscroll = if action.center_cursor {
 7497            Autoscroll::center()
 7498        } else {
 7499            Autoscroll::fit()
 7500        };
 7501
 7502        let text_layout_details = &self.text_layout_details(cx);
 7503
 7504        self.change_selections(Some(autoscroll), cx, |s| {
 7505            let line_mode = s.line_mode;
 7506            s.move_with(|map, selection| {
 7507                if !selection.is_empty() && !line_mode {
 7508                    selection.goal = SelectionGoal::None;
 7509                }
 7510                let (cursor, goal) = movement::up_by_rows(
 7511                    map,
 7512                    selection.end,
 7513                    row_count,
 7514                    selection.goal,
 7515                    false,
 7516                    text_layout_details,
 7517                );
 7518                selection.collapse_to(cursor, goal);
 7519            });
 7520        });
 7521    }
 7522
 7523    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7524        let text_layout_details = &self.text_layout_details(cx);
 7525        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7526            s.move_heads_with(|map, head, goal| {
 7527                movement::up(map, head, goal, false, text_layout_details)
 7528            })
 7529        })
 7530    }
 7531
 7532    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7533        self.take_rename(true, cx);
 7534
 7535        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7536            cx.propagate();
 7537            return;
 7538        }
 7539
 7540        let text_layout_details = &self.text_layout_details(cx);
 7541        let selection_count = self.selections.count();
 7542        let first_selection = self.selections.first_anchor();
 7543
 7544        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7545            let line_mode = s.line_mode;
 7546            s.move_with(|map, selection| {
 7547                if !selection.is_empty() && !line_mode {
 7548                    selection.goal = SelectionGoal::None;
 7549                }
 7550                let (cursor, goal) = movement::down(
 7551                    map,
 7552                    selection.end,
 7553                    selection.goal,
 7554                    false,
 7555                    text_layout_details,
 7556                );
 7557                selection.collapse_to(cursor, goal);
 7558            });
 7559        });
 7560
 7561        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7562        {
 7563            cx.propagate();
 7564        }
 7565    }
 7566
 7567    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7568        let Some(row_count) = self.visible_row_count() else {
 7569            return;
 7570        };
 7571
 7572        let text_layout_details = &self.text_layout_details(cx);
 7573
 7574        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7575            s.move_heads_with(|map, head, goal| {
 7576                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7577            })
 7578        })
 7579    }
 7580
 7581    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7582        if self.take_rename(true, cx).is_some() {
 7583            return;
 7584        }
 7585
 7586        if self
 7587            .context_menu
 7588            .write()
 7589            .as_mut()
 7590            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7591            .unwrap_or(false)
 7592        {
 7593            return;
 7594        }
 7595
 7596        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7597            cx.propagate();
 7598            return;
 7599        }
 7600
 7601        let Some(row_count) = self.visible_row_count() else {
 7602            return;
 7603        };
 7604
 7605        let autoscroll = if action.center_cursor {
 7606            Autoscroll::center()
 7607        } else {
 7608            Autoscroll::fit()
 7609        };
 7610
 7611        let text_layout_details = &self.text_layout_details(cx);
 7612        self.change_selections(Some(autoscroll), cx, |s| {
 7613            let line_mode = s.line_mode;
 7614            s.move_with(|map, selection| {
 7615                if !selection.is_empty() && !line_mode {
 7616                    selection.goal = SelectionGoal::None;
 7617                }
 7618                let (cursor, goal) = movement::down_by_rows(
 7619                    map,
 7620                    selection.end,
 7621                    row_count,
 7622                    selection.goal,
 7623                    false,
 7624                    text_layout_details,
 7625                );
 7626                selection.collapse_to(cursor, goal);
 7627            });
 7628        });
 7629    }
 7630
 7631    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7632        let text_layout_details = &self.text_layout_details(cx);
 7633        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7634            s.move_heads_with(|map, head, goal| {
 7635                movement::down(map, head, goal, false, text_layout_details)
 7636            })
 7637        });
 7638    }
 7639
 7640    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7641        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7642            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7643        }
 7644    }
 7645
 7646    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7647        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7648            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7649        }
 7650    }
 7651
 7652    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7653        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7654            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7655        }
 7656    }
 7657
 7658    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7659        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7660            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7661        }
 7662    }
 7663
 7664    pub fn move_to_previous_word_start(
 7665        &mut self,
 7666        _: &MoveToPreviousWordStart,
 7667        cx: &mut ViewContext<Self>,
 7668    ) {
 7669        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7670            s.move_cursors_with(|map, head, _| {
 7671                (
 7672                    movement::previous_word_start(map, head),
 7673                    SelectionGoal::None,
 7674                )
 7675            });
 7676        })
 7677    }
 7678
 7679    pub fn move_to_previous_subword_start(
 7680        &mut self,
 7681        _: &MoveToPreviousSubwordStart,
 7682        cx: &mut ViewContext<Self>,
 7683    ) {
 7684        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7685            s.move_cursors_with(|map, head, _| {
 7686                (
 7687                    movement::previous_subword_start(map, head),
 7688                    SelectionGoal::None,
 7689                )
 7690            });
 7691        })
 7692    }
 7693
 7694    pub fn select_to_previous_word_start(
 7695        &mut self,
 7696        _: &SelectToPreviousWordStart,
 7697        cx: &mut ViewContext<Self>,
 7698    ) {
 7699        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7700            s.move_heads_with(|map, head, _| {
 7701                (
 7702                    movement::previous_word_start(map, head),
 7703                    SelectionGoal::None,
 7704                )
 7705            });
 7706        })
 7707    }
 7708
 7709    pub fn select_to_previous_subword_start(
 7710        &mut self,
 7711        _: &SelectToPreviousSubwordStart,
 7712        cx: &mut ViewContext<Self>,
 7713    ) {
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            s.move_heads_with(|map, head, _| {
 7716                (
 7717                    movement::previous_subword_start(map, head),
 7718                    SelectionGoal::None,
 7719                )
 7720            });
 7721        })
 7722    }
 7723
 7724    pub fn delete_to_previous_word_start(
 7725        &mut self,
 7726        action: &DeleteToPreviousWordStart,
 7727        cx: &mut ViewContext<Self>,
 7728    ) {
 7729        self.transact(cx, |this, cx| {
 7730            this.select_autoclose_pair(cx);
 7731            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7732                let line_mode = s.line_mode;
 7733                s.move_with(|map, selection| {
 7734                    if selection.is_empty() && !line_mode {
 7735                        let cursor = if action.ignore_newlines {
 7736                            movement::previous_word_start(map, selection.head())
 7737                        } else {
 7738                            movement::previous_word_start_or_newline(map, selection.head())
 7739                        };
 7740                        selection.set_head(cursor, SelectionGoal::None);
 7741                    }
 7742                });
 7743            });
 7744            this.insert("", cx);
 7745        });
 7746    }
 7747
 7748    pub fn delete_to_previous_subword_start(
 7749        &mut self,
 7750        _: &DeleteToPreviousSubwordStart,
 7751        cx: &mut ViewContext<Self>,
 7752    ) {
 7753        self.transact(cx, |this, cx| {
 7754            this.select_autoclose_pair(cx);
 7755            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7756                let line_mode = s.line_mode;
 7757                s.move_with(|map, selection| {
 7758                    if selection.is_empty() && !line_mode {
 7759                        let cursor = movement::previous_subword_start(map, selection.head());
 7760                        selection.set_head(cursor, SelectionGoal::None);
 7761                    }
 7762                });
 7763            });
 7764            this.insert("", cx);
 7765        });
 7766    }
 7767
 7768    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7769        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7770            s.move_cursors_with(|map, head, _| {
 7771                (movement::next_word_end(map, head), SelectionGoal::None)
 7772            });
 7773        })
 7774    }
 7775
 7776    pub fn move_to_next_subword_end(
 7777        &mut self,
 7778        _: &MoveToNextSubwordEnd,
 7779        cx: &mut ViewContext<Self>,
 7780    ) {
 7781        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7782            s.move_cursors_with(|map, head, _| {
 7783                (movement::next_subword_end(map, head), SelectionGoal::None)
 7784            });
 7785        })
 7786    }
 7787
 7788    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7790            s.move_heads_with(|map, head, _| {
 7791                (movement::next_word_end(map, head), SelectionGoal::None)
 7792            });
 7793        })
 7794    }
 7795
 7796    pub fn select_to_next_subword_end(
 7797        &mut self,
 7798        _: &SelectToNextSubwordEnd,
 7799        cx: &mut ViewContext<Self>,
 7800    ) {
 7801        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7802            s.move_heads_with(|map, head, _| {
 7803                (movement::next_subword_end(map, head), SelectionGoal::None)
 7804            });
 7805        })
 7806    }
 7807
 7808    pub fn delete_to_next_word_end(
 7809        &mut self,
 7810        action: &DeleteToNextWordEnd,
 7811        cx: &mut ViewContext<Self>,
 7812    ) {
 7813        self.transact(cx, |this, cx| {
 7814            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7815                let line_mode = s.line_mode;
 7816                s.move_with(|map, selection| {
 7817                    if selection.is_empty() && !line_mode {
 7818                        let cursor = if action.ignore_newlines {
 7819                            movement::next_word_end(map, selection.head())
 7820                        } else {
 7821                            movement::next_word_end_or_newline(map, selection.head())
 7822                        };
 7823                        selection.set_head(cursor, SelectionGoal::None);
 7824                    }
 7825                });
 7826            });
 7827            this.insert("", cx);
 7828        });
 7829    }
 7830
 7831    pub fn delete_to_next_subword_end(
 7832        &mut self,
 7833        _: &DeleteToNextSubwordEnd,
 7834        cx: &mut ViewContext<Self>,
 7835    ) {
 7836        self.transact(cx, |this, cx| {
 7837            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7838                s.move_with(|map, selection| {
 7839                    if selection.is_empty() {
 7840                        let cursor = movement::next_subword_end(map, selection.head());
 7841                        selection.set_head(cursor, SelectionGoal::None);
 7842                    }
 7843                });
 7844            });
 7845            this.insert("", cx);
 7846        });
 7847    }
 7848
 7849    pub fn move_to_beginning_of_line(
 7850        &mut self,
 7851        action: &MoveToBeginningOfLine,
 7852        cx: &mut ViewContext<Self>,
 7853    ) {
 7854        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7855            s.move_cursors_with(|map, head, _| {
 7856                (
 7857                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7858                    SelectionGoal::None,
 7859                )
 7860            });
 7861        })
 7862    }
 7863
 7864    pub fn select_to_beginning_of_line(
 7865        &mut self,
 7866        action: &SelectToBeginningOfLine,
 7867        cx: &mut ViewContext<Self>,
 7868    ) {
 7869        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7870            s.move_heads_with(|map, head, _| {
 7871                (
 7872                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7873                    SelectionGoal::None,
 7874                )
 7875            });
 7876        });
 7877    }
 7878
 7879    pub fn delete_to_beginning_of_line(
 7880        &mut self,
 7881        _: &DeleteToBeginningOfLine,
 7882        cx: &mut ViewContext<Self>,
 7883    ) {
 7884        self.transact(cx, |this, cx| {
 7885            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7886                s.move_with(|_, selection| {
 7887                    selection.reversed = true;
 7888                });
 7889            });
 7890
 7891            this.select_to_beginning_of_line(
 7892                &SelectToBeginningOfLine {
 7893                    stop_at_soft_wraps: false,
 7894                },
 7895                cx,
 7896            );
 7897            this.backspace(&Backspace, cx);
 7898        });
 7899    }
 7900
 7901    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7903            s.move_cursors_with(|map, head, _| {
 7904                (
 7905                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7906                    SelectionGoal::None,
 7907                )
 7908            });
 7909        })
 7910    }
 7911
 7912    pub fn select_to_end_of_line(
 7913        &mut self,
 7914        action: &SelectToEndOfLine,
 7915        cx: &mut ViewContext<Self>,
 7916    ) {
 7917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7918            s.move_heads_with(|map, head, _| {
 7919                (
 7920                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7921                    SelectionGoal::None,
 7922                )
 7923            });
 7924        })
 7925    }
 7926
 7927    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7928        self.transact(cx, |this, cx| {
 7929            this.select_to_end_of_line(
 7930                &SelectToEndOfLine {
 7931                    stop_at_soft_wraps: false,
 7932                },
 7933                cx,
 7934            );
 7935            this.delete(&Delete, cx);
 7936        });
 7937    }
 7938
 7939    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7940        self.transact(cx, |this, cx| {
 7941            this.select_to_end_of_line(
 7942                &SelectToEndOfLine {
 7943                    stop_at_soft_wraps: false,
 7944                },
 7945                cx,
 7946            );
 7947            this.cut(&Cut, cx);
 7948        });
 7949    }
 7950
 7951    pub fn move_to_start_of_paragraph(
 7952        &mut self,
 7953        _: &MoveToStartOfParagraph,
 7954        cx: &mut ViewContext<Self>,
 7955    ) {
 7956        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7957            cx.propagate();
 7958            return;
 7959        }
 7960
 7961        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7962            s.move_with(|map, selection| {
 7963                selection.collapse_to(
 7964                    movement::start_of_paragraph(map, selection.head(), 1),
 7965                    SelectionGoal::None,
 7966                )
 7967            });
 7968        })
 7969    }
 7970
 7971    pub fn move_to_end_of_paragraph(
 7972        &mut self,
 7973        _: &MoveToEndOfParagraph,
 7974        cx: &mut ViewContext<Self>,
 7975    ) {
 7976        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7977            cx.propagate();
 7978            return;
 7979        }
 7980
 7981        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7982            s.move_with(|map, selection| {
 7983                selection.collapse_to(
 7984                    movement::end_of_paragraph(map, selection.head(), 1),
 7985                    SelectionGoal::None,
 7986                )
 7987            });
 7988        })
 7989    }
 7990
 7991    pub fn select_to_start_of_paragraph(
 7992        &mut self,
 7993        _: &SelectToStartOfParagraph,
 7994        cx: &mut ViewContext<Self>,
 7995    ) {
 7996        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7997            cx.propagate();
 7998            return;
 7999        }
 8000
 8001        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8002            s.move_heads_with(|map, head, _| {
 8003                (
 8004                    movement::start_of_paragraph(map, head, 1),
 8005                    SelectionGoal::None,
 8006                )
 8007            });
 8008        })
 8009    }
 8010
 8011    pub fn select_to_end_of_paragraph(
 8012        &mut self,
 8013        _: &SelectToEndOfParagraph,
 8014        cx: &mut ViewContext<Self>,
 8015    ) {
 8016        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8017            cx.propagate();
 8018            return;
 8019        }
 8020
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.move_heads_with(|map, head, _| {
 8023                (
 8024                    movement::end_of_paragraph(map, head, 1),
 8025                    SelectionGoal::None,
 8026                )
 8027            });
 8028        })
 8029    }
 8030
 8031    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8032        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8033            cx.propagate();
 8034            return;
 8035        }
 8036
 8037        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8038            s.select_ranges(vec![0..0]);
 8039        });
 8040    }
 8041
 8042    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8043        let mut selection = self.selections.last::<Point>(cx);
 8044        selection.set_head(Point::zero(), SelectionGoal::None);
 8045
 8046        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8047            s.select(vec![selection]);
 8048        });
 8049    }
 8050
 8051    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8052        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8053            cx.propagate();
 8054            return;
 8055        }
 8056
 8057        let cursor = self.buffer.read(cx).read(cx).len();
 8058        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8059            s.select_ranges(vec![cursor..cursor])
 8060        });
 8061    }
 8062
 8063    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8064        self.nav_history = nav_history;
 8065    }
 8066
 8067    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8068        self.nav_history.as_ref()
 8069    }
 8070
 8071    fn push_to_nav_history(
 8072        &mut self,
 8073        cursor_anchor: Anchor,
 8074        new_position: Option<Point>,
 8075        cx: &mut ViewContext<Self>,
 8076    ) {
 8077        if let Some(nav_history) = self.nav_history.as_mut() {
 8078            let buffer = self.buffer.read(cx).read(cx);
 8079            let cursor_position = cursor_anchor.to_point(&buffer);
 8080            let scroll_state = self.scroll_manager.anchor();
 8081            let scroll_top_row = scroll_state.top_row(&buffer);
 8082            drop(buffer);
 8083
 8084            if let Some(new_position) = new_position {
 8085                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8086                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8087                    return;
 8088                }
 8089            }
 8090
 8091            nav_history.push(
 8092                Some(NavigationData {
 8093                    cursor_anchor,
 8094                    cursor_position,
 8095                    scroll_anchor: scroll_state,
 8096                    scroll_top_row,
 8097                }),
 8098                cx,
 8099            );
 8100        }
 8101    }
 8102
 8103    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8104        let buffer = self.buffer.read(cx).snapshot(cx);
 8105        let mut selection = self.selections.first::<usize>(cx);
 8106        selection.set_head(buffer.len(), SelectionGoal::None);
 8107        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8108            s.select(vec![selection]);
 8109        });
 8110    }
 8111
 8112    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8113        let end = self.buffer.read(cx).read(cx).len();
 8114        self.change_selections(None, cx, |s| {
 8115            s.select_ranges(vec![0..end]);
 8116        });
 8117    }
 8118
 8119    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8120        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8121        let mut selections = self.selections.all::<Point>(cx);
 8122        let max_point = display_map.buffer_snapshot.max_point();
 8123        for selection in &mut selections {
 8124            let rows = selection.spanned_rows(true, &display_map);
 8125            selection.start = Point::new(rows.start.0, 0);
 8126            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8127            selection.reversed = false;
 8128        }
 8129        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8130            s.select(selections);
 8131        });
 8132    }
 8133
 8134    pub fn split_selection_into_lines(
 8135        &mut self,
 8136        _: &SplitSelectionIntoLines,
 8137        cx: &mut ViewContext<Self>,
 8138    ) {
 8139        let mut to_unfold = Vec::new();
 8140        let mut new_selection_ranges = Vec::new();
 8141        {
 8142            let selections = self.selections.all::<Point>(cx);
 8143            let buffer = self.buffer.read(cx).read(cx);
 8144            for selection in selections {
 8145                for row in selection.start.row..selection.end.row {
 8146                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8147                    new_selection_ranges.push(cursor..cursor);
 8148                }
 8149                new_selection_ranges.push(selection.end..selection.end);
 8150                to_unfold.push(selection.start..selection.end);
 8151            }
 8152        }
 8153        self.unfold_ranges(to_unfold, true, true, cx);
 8154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8155            s.select_ranges(new_selection_ranges);
 8156        });
 8157    }
 8158
 8159    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8160        self.add_selection(true, cx);
 8161    }
 8162
 8163    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8164        self.add_selection(false, cx);
 8165    }
 8166
 8167    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8169        let mut selections = self.selections.all::<Point>(cx);
 8170        let text_layout_details = self.text_layout_details(cx);
 8171        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8172            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8173            let range = oldest_selection.display_range(&display_map).sorted();
 8174
 8175            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8176            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8177            let positions = start_x.min(end_x)..start_x.max(end_x);
 8178
 8179            selections.clear();
 8180            let mut stack = Vec::new();
 8181            for row in range.start.row().0..=range.end.row().0 {
 8182                if let Some(selection) = self.selections.build_columnar_selection(
 8183                    &display_map,
 8184                    DisplayRow(row),
 8185                    &positions,
 8186                    oldest_selection.reversed,
 8187                    &text_layout_details,
 8188                ) {
 8189                    stack.push(selection.id);
 8190                    selections.push(selection);
 8191                }
 8192            }
 8193
 8194            if above {
 8195                stack.reverse();
 8196            }
 8197
 8198            AddSelectionsState { above, stack }
 8199        });
 8200
 8201        let last_added_selection = *state.stack.last().unwrap();
 8202        let mut new_selections = Vec::new();
 8203        if above == state.above {
 8204            let end_row = if above {
 8205                DisplayRow(0)
 8206            } else {
 8207                display_map.max_point().row()
 8208            };
 8209
 8210            'outer: for selection in selections {
 8211                if selection.id == last_added_selection {
 8212                    let range = selection.display_range(&display_map).sorted();
 8213                    debug_assert_eq!(range.start.row(), range.end.row());
 8214                    let mut row = range.start.row();
 8215                    let positions =
 8216                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8217                            px(start)..px(end)
 8218                        } else {
 8219                            let start_x =
 8220                                display_map.x_for_display_point(range.start, &text_layout_details);
 8221                            let end_x =
 8222                                display_map.x_for_display_point(range.end, &text_layout_details);
 8223                            start_x.min(end_x)..start_x.max(end_x)
 8224                        };
 8225
 8226                    while row != end_row {
 8227                        if above {
 8228                            row.0 -= 1;
 8229                        } else {
 8230                            row.0 += 1;
 8231                        }
 8232
 8233                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8234                            &display_map,
 8235                            row,
 8236                            &positions,
 8237                            selection.reversed,
 8238                            &text_layout_details,
 8239                        ) {
 8240                            state.stack.push(new_selection.id);
 8241                            if above {
 8242                                new_selections.push(new_selection);
 8243                                new_selections.push(selection);
 8244                            } else {
 8245                                new_selections.push(selection);
 8246                                new_selections.push(new_selection);
 8247                            }
 8248
 8249                            continue 'outer;
 8250                        }
 8251                    }
 8252                }
 8253
 8254                new_selections.push(selection);
 8255            }
 8256        } else {
 8257            new_selections = selections;
 8258            new_selections.retain(|s| s.id != last_added_selection);
 8259            state.stack.pop();
 8260        }
 8261
 8262        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8263            s.select(new_selections);
 8264        });
 8265        if state.stack.len() > 1 {
 8266            self.add_selections_state = Some(state);
 8267        }
 8268    }
 8269
 8270    pub fn select_next_match_internal(
 8271        &mut self,
 8272        display_map: &DisplaySnapshot,
 8273        replace_newest: bool,
 8274        autoscroll: Option<Autoscroll>,
 8275        cx: &mut ViewContext<Self>,
 8276    ) -> Result<()> {
 8277        fn select_next_match_ranges(
 8278            this: &mut Editor,
 8279            range: Range<usize>,
 8280            replace_newest: bool,
 8281            auto_scroll: Option<Autoscroll>,
 8282            cx: &mut ViewContext<Editor>,
 8283        ) {
 8284            this.unfold_ranges([range.clone()], false, true, cx);
 8285            this.change_selections(auto_scroll, cx, |s| {
 8286                if replace_newest {
 8287                    s.delete(s.newest_anchor().id);
 8288                }
 8289                s.insert_range(range.clone());
 8290            });
 8291        }
 8292
 8293        let buffer = &display_map.buffer_snapshot;
 8294        let mut selections = self.selections.all::<usize>(cx);
 8295        if let Some(mut select_next_state) = self.select_next_state.take() {
 8296            let query = &select_next_state.query;
 8297            if !select_next_state.done {
 8298                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8299                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8300                let mut next_selected_range = None;
 8301
 8302                let bytes_after_last_selection =
 8303                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8304                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8305                let query_matches = query
 8306                    .stream_find_iter(bytes_after_last_selection)
 8307                    .map(|result| (last_selection.end, result))
 8308                    .chain(
 8309                        query
 8310                            .stream_find_iter(bytes_before_first_selection)
 8311                            .map(|result| (0, result)),
 8312                    );
 8313
 8314                for (start_offset, query_match) in query_matches {
 8315                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8316                    let offset_range =
 8317                        start_offset + query_match.start()..start_offset + query_match.end();
 8318                    let display_range = offset_range.start.to_display_point(display_map)
 8319                        ..offset_range.end.to_display_point(display_map);
 8320
 8321                    if !select_next_state.wordwise
 8322                        || (!movement::is_inside_word(display_map, display_range.start)
 8323                            && !movement::is_inside_word(display_map, display_range.end))
 8324                    {
 8325                        // TODO: This is n^2, because we might check all the selections
 8326                        if !selections
 8327                            .iter()
 8328                            .any(|selection| selection.range().overlaps(&offset_range))
 8329                        {
 8330                            next_selected_range = Some(offset_range);
 8331                            break;
 8332                        }
 8333                    }
 8334                }
 8335
 8336                if let Some(next_selected_range) = next_selected_range {
 8337                    select_next_match_ranges(
 8338                        self,
 8339                        next_selected_range,
 8340                        replace_newest,
 8341                        autoscroll,
 8342                        cx,
 8343                    );
 8344                } else {
 8345                    select_next_state.done = true;
 8346                }
 8347            }
 8348
 8349            self.select_next_state = Some(select_next_state);
 8350        } else {
 8351            let mut only_carets = true;
 8352            let mut same_text_selected = true;
 8353            let mut selected_text = None;
 8354
 8355            let mut selections_iter = selections.iter().peekable();
 8356            while let Some(selection) = selections_iter.next() {
 8357                if selection.start != selection.end {
 8358                    only_carets = false;
 8359                }
 8360
 8361                if same_text_selected {
 8362                    if selected_text.is_none() {
 8363                        selected_text =
 8364                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8365                    }
 8366
 8367                    if let Some(next_selection) = selections_iter.peek() {
 8368                        if next_selection.range().len() == selection.range().len() {
 8369                            let next_selected_text = buffer
 8370                                .text_for_range(next_selection.range())
 8371                                .collect::<String>();
 8372                            if Some(next_selected_text) != selected_text {
 8373                                same_text_selected = false;
 8374                                selected_text = None;
 8375                            }
 8376                        } else {
 8377                            same_text_selected = false;
 8378                            selected_text = None;
 8379                        }
 8380                    }
 8381                }
 8382            }
 8383
 8384            if only_carets {
 8385                for selection in &mut selections {
 8386                    let word_range = movement::surrounding_word(
 8387                        display_map,
 8388                        selection.start.to_display_point(display_map),
 8389                    );
 8390                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8391                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8392                    selection.goal = SelectionGoal::None;
 8393                    selection.reversed = false;
 8394                    select_next_match_ranges(
 8395                        self,
 8396                        selection.start..selection.end,
 8397                        replace_newest,
 8398                        autoscroll,
 8399                        cx,
 8400                    );
 8401                }
 8402
 8403                if selections.len() == 1 {
 8404                    let selection = selections
 8405                        .last()
 8406                        .expect("ensured that there's only one selection");
 8407                    let query = buffer
 8408                        .text_for_range(selection.start..selection.end)
 8409                        .collect::<String>();
 8410                    let is_empty = query.is_empty();
 8411                    let select_state = SelectNextState {
 8412                        query: AhoCorasick::new(&[query])?,
 8413                        wordwise: true,
 8414                        done: is_empty,
 8415                    };
 8416                    self.select_next_state = Some(select_state);
 8417                } else {
 8418                    self.select_next_state = None;
 8419                }
 8420            } else if let Some(selected_text) = selected_text {
 8421                self.select_next_state = Some(SelectNextState {
 8422                    query: AhoCorasick::new(&[selected_text])?,
 8423                    wordwise: false,
 8424                    done: false,
 8425                });
 8426                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8427            }
 8428        }
 8429        Ok(())
 8430    }
 8431
 8432    pub fn select_all_matches(
 8433        &mut self,
 8434        _action: &SelectAllMatches,
 8435        cx: &mut ViewContext<Self>,
 8436    ) -> Result<()> {
 8437        self.push_to_selection_history();
 8438        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8439
 8440        self.select_next_match_internal(&display_map, false, None, cx)?;
 8441        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8442            return Ok(());
 8443        };
 8444        if select_next_state.done {
 8445            return Ok(());
 8446        }
 8447
 8448        let mut new_selections = self.selections.all::<usize>(cx);
 8449
 8450        let buffer = &display_map.buffer_snapshot;
 8451        let query_matches = select_next_state
 8452            .query
 8453            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8454
 8455        for query_match in query_matches {
 8456            let query_match = query_match.unwrap(); // can only fail due to I/O
 8457            let offset_range = query_match.start()..query_match.end();
 8458            let display_range = offset_range.start.to_display_point(&display_map)
 8459                ..offset_range.end.to_display_point(&display_map);
 8460
 8461            if !select_next_state.wordwise
 8462                || (!movement::is_inside_word(&display_map, display_range.start)
 8463                    && !movement::is_inside_word(&display_map, display_range.end))
 8464            {
 8465                self.selections.change_with(cx, |selections| {
 8466                    new_selections.push(Selection {
 8467                        id: selections.new_selection_id(),
 8468                        start: offset_range.start,
 8469                        end: offset_range.end,
 8470                        reversed: false,
 8471                        goal: SelectionGoal::None,
 8472                    });
 8473                });
 8474            }
 8475        }
 8476
 8477        new_selections.sort_by_key(|selection| selection.start);
 8478        let mut ix = 0;
 8479        while ix + 1 < new_selections.len() {
 8480            let current_selection = &new_selections[ix];
 8481            let next_selection = &new_selections[ix + 1];
 8482            if current_selection.range().overlaps(&next_selection.range()) {
 8483                if current_selection.id < next_selection.id {
 8484                    new_selections.remove(ix + 1);
 8485                } else {
 8486                    new_selections.remove(ix);
 8487                }
 8488            } else {
 8489                ix += 1;
 8490            }
 8491        }
 8492
 8493        select_next_state.done = true;
 8494        self.unfold_ranges(
 8495            new_selections.iter().map(|selection| selection.range()),
 8496            false,
 8497            false,
 8498            cx,
 8499        );
 8500        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8501            selections.select(new_selections)
 8502        });
 8503
 8504        Ok(())
 8505    }
 8506
 8507    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8508        self.push_to_selection_history();
 8509        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8510        self.select_next_match_internal(
 8511            &display_map,
 8512            action.replace_newest,
 8513            Some(Autoscroll::newest()),
 8514            cx,
 8515        )?;
 8516        Ok(())
 8517    }
 8518
 8519    pub fn select_previous(
 8520        &mut self,
 8521        action: &SelectPrevious,
 8522        cx: &mut ViewContext<Self>,
 8523    ) -> Result<()> {
 8524        self.push_to_selection_history();
 8525        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8526        let buffer = &display_map.buffer_snapshot;
 8527        let mut selections = self.selections.all::<usize>(cx);
 8528        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8529            let query = &select_prev_state.query;
 8530            if !select_prev_state.done {
 8531                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8532                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8533                let mut next_selected_range = None;
 8534                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8535                let bytes_before_last_selection =
 8536                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8537                let bytes_after_first_selection =
 8538                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8539                let query_matches = query
 8540                    .stream_find_iter(bytes_before_last_selection)
 8541                    .map(|result| (last_selection.start, result))
 8542                    .chain(
 8543                        query
 8544                            .stream_find_iter(bytes_after_first_selection)
 8545                            .map(|result| (buffer.len(), result)),
 8546                    );
 8547                for (end_offset, query_match) in query_matches {
 8548                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8549                    let offset_range =
 8550                        end_offset - query_match.end()..end_offset - query_match.start();
 8551                    let display_range = offset_range.start.to_display_point(&display_map)
 8552                        ..offset_range.end.to_display_point(&display_map);
 8553
 8554                    if !select_prev_state.wordwise
 8555                        || (!movement::is_inside_word(&display_map, display_range.start)
 8556                            && !movement::is_inside_word(&display_map, display_range.end))
 8557                    {
 8558                        next_selected_range = Some(offset_range);
 8559                        break;
 8560                    }
 8561                }
 8562
 8563                if let Some(next_selected_range) = next_selected_range {
 8564                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8565                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8566                        if action.replace_newest {
 8567                            s.delete(s.newest_anchor().id);
 8568                        }
 8569                        s.insert_range(next_selected_range);
 8570                    });
 8571                } else {
 8572                    select_prev_state.done = true;
 8573                }
 8574            }
 8575
 8576            self.select_prev_state = Some(select_prev_state);
 8577        } else {
 8578            let mut only_carets = true;
 8579            let mut same_text_selected = true;
 8580            let mut selected_text = None;
 8581
 8582            let mut selections_iter = selections.iter().peekable();
 8583            while let Some(selection) = selections_iter.next() {
 8584                if selection.start != selection.end {
 8585                    only_carets = false;
 8586                }
 8587
 8588                if same_text_selected {
 8589                    if selected_text.is_none() {
 8590                        selected_text =
 8591                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8592                    }
 8593
 8594                    if let Some(next_selection) = selections_iter.peek() {
 8595                        if next_selection.range().len() == selection.range().len() {
 8596                            let next_selected_text = buffer
 8597                                .text_for_range(next_selection.range())
 8598                                .collect::<String>();
 8599                            if Some(next_selected_text) != selected_text {
 8600                                same_text_selected = false;
 8601                                selected_text = None;
 8602                            }
 8603                        } else {
 8604                            same_text_selected = false;
 8605                            selected_text = None;
 8606                        }
 8607                    }
 8608                }
 8609            }
 8610
 8611            if only_carets {
 8612                for selection in &mut selections {
 8613                    let word_range = movement::surrounding_word(
 8614                        &display_map,
 8615                        selection.start.to_display_point(&display_map),
 8616                    );
 8617                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8618                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8619                    selection.goal = SelectionGoal::None;
 8620                    selection.reversed = false;
 8621                }
 8622                if selections.len() == 1 {
 8623                    let selection = selections
 8624                        .last()
 8625                        .expect("ensured that there's only one selection");
 8626                    let query = buffer
 8627                        .text_for_range(selection.start..selection.end)
 8628                        .collect::<String>();
 8629                    let is_empty = query.is_empty();
 8630                    let select_state = SelectNextState {
 8631                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8632                        wordwise: true,
 8633                        done: is_empty,
 8634                    };
 8635                    self.select_prev_state = Some(select_state);
 8636                } else {
 8637                    self.select_prev_state = None;
 8638                }
 8639
 8640                self.unfold_ranges(
 8641                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8642                    false,
 8643                    true,
 8644                    cx,
 8645                );
 8646                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8647                    s.select(selections);
 8648                });
 8649            } else if let Some(selected_text) = selected_text {
 8650                self.select_prev_state = Some(SelectNextState {
 8651                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8652                    wordwise: false,
 8653                    done: false,
 8654                });
 8655                self.select_previous(action, cx)?;
 8656            }
 8657        }
 8658        Ok(())
 8659    }
 8660
 8661    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8662        let text_layout_details = &self.text_layout_details(cx);
 8663        self.transact(cx, |this, cx| {
 8664            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8665            let mut edits = Vec::new();
 8666            let mut selection_edit_ranges = Vec::new();
 8667            let mut last_toggled_row = None;
 8668            let snapshot = this.buffer.read(cx).read(cx);
 8669            let empty_str: Arc<str> = Arc::default();
 8670            let mut suffixes_inserted = Vec::new();
 8671
 8672            fn comment_prefix_range(
 8673                snapshot: &MultiBufferSnapshot,
 8674                row: MultiBufferRow,
 8675                comment_prefix: &str,
 8676                comment_prefix_whitespace: &str,
 8677            ) -> Range<Point> {
 8678                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8679
 8680                let mut line_bytes = snapshot
 8681                    .bytes_in_range(start..snapshot.max_point())
 8682                    .flatten()
 8683                    .copied();
 8684
 8685                // If this line currently begins with the line comment prefix, then record
 8686                // the range containing the prefix.
 8687                if line_bytes
 8688                    .by_ref()
 8689                    .take(comment_prefix.len())
 8690                    .eq(comment_prefix.bytes())
 8691                {
 8692                    // Include any whitespace that matches the comment prefix.
 8693                    let matching_whitespace_len = line_bytes
 8694                        .zip(comment_prefix_whitespace.bytes())
 8695                        .take_while(|(a, b)| a == b)
 8696                        .count() as u32;
 8697                    let end = Point::new(
 8698                        start.row,
 8699                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8700                    );
 8701                    start..end
 8702                } else {
 8703                    start..start
 8704                }
 8705            }
 8706
 8707            fn comment_suffix_range(
 8708                snapshot: &MultiBufferSnapshot,
 8709                row: MultiBufferRow,
 8710                comment_suffix: &str,
 8711                comment_suffix_has_leading_space: bool,
 8712            ) -> Range<Point> {
 8713                let end = Point::new(row.0, snapshot.line_len(row));
 8714                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8715
 8716                let mut line_end_bytes = snapshot
 8717                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8718                    .flatten()
 8719                    .copied();
 8720
 8721                let leading_space_len = if suffix_start_column > 0
 8722                    && line_end_bytes.next() == Some(b' ')
 8723                    && comment_suffix_has_leading_space
 8724                {
 8725                    1
 8726                } else {
 8727                    0
 8728                };
 8729
 8730                // If this line currently begins with the line comment prefix, then record
 8731                // the range containing the prefix.
 8732                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8733                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8734                    start..end
 8735                } else {
 8736                    end..end
 8737                }
 8738            }
 8739
 8740            // TODO: Handle selections that cross excerpts
 8741            for selection in &mut selections {
 8742                let start_column = snapshot
 8743                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8744                    .len;
 8745                let language = if let Some(language) =
 8746                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8747                {
 8748                    language
 8749                } else {
 8750                    continue;
 8751                };
 8752
 8753                selection_edit_ranges.clear();
 8754
 8755                // If multiple selections contain a given row, avoid processing that
 8756                // row more than once.
 8757                let mut start_row = MultiBufferRow(selection.start.row);
 8758                if last_toggled_row == Some(start_row) {
 8759                    start_row = start_row.next_row();
 8760                }
 8761                let end_row =
 8762                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8763                        MultiBufferRow(selection.end.row - 1)
 8764                    } else {
 8765                        MultiBufferRow(selection.end.row)
 8766                    };
 8767                last_toggled_row = Some(end_row);
 8768
 8769                if start_row > end_row {
 8770                    continue;
 8771                }
 8772
 8773                // If the language has line comments, toggle those.
 8774                let full_comment_prefixes = language.line_comment_prefixes();
 8775                if !full_comment_prefixes.is_empty() {
 8776                    let first_prefix = full_comment_prefixes
 8777                        .first()
 8778                        .expect("prefixes is non-empty");
 8779                    let prefix_trimmed_lengths = full_comment_prefixes
 8780                        .iter()
 8781                        .map(|p| p.trim_end_matches(' ').len())
 8782                        .collect::<SmallVec<[usize; 4]>>();
 8783
 8784                    let mut all_selection_lines_are_comments = true;
 8785
 8786                    for row in start_row.0..=end_row.0 {
 8787                        let row = MultiBufferRow(row);
 8788                        if start_row < end_row && snapshot.is_line_blank(row) {
 8789                            continue;
 8790                        }
 8791
 8792                        let prefix_range = full_comment_prefixes
 8793                            .iter()
 8794                            .zip(prefix_trimmed_lengths.iter().copied())
 8795                            .map(|(prefix, trimmed_prefix_len)| {
 8796                                comment_prefix_range(
 8797                                    snapshot.deref(),
 8798                                    row,
 8799                                    &prefix[..trimmed_prefix_len],
 8800                                    &prefix[trimmed_prefix_len..],
 8801                                )
 8802                            })
 8803                            .max_by_key(|range| range.end.column - range.start.column)
 8804                            .expect("prefixes is non-empty");
 8805
 8806                        if prefix_range.is_empty() {
 8807                            all_selection_lines_are_comments = false;
 8808                        }
 8809
 8810                        selection_edit_ranges.push(prefix_range);
 8811                    }
 8812
 8813                    if all_selection_lines_are_comments {
 8814                        edits.extend(
 8815                            selection_edit_ranges
 8816                                .iter()
 8817                                .cloned()
 8818                                .map(|range| (range, empty_str.clone())),
 8819                        );
 8820                    } else {
 8821                        let min_column = selection_edit_ranges
 8822                            .iter()
 8823                            .map(|range| range.start.column)
 8824                            .min()
 8825                            .unwrap_or(0);
 8826                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8827                            let position = Point::new(range.start.row, min_column);
 8828                            (position..position, first_prefix.clone())
 8829                        }));
 8830                    }
 8831                } else if let Some((full_comment_prefix, comment_suffix)) =
 8832                    language.block_comment_delimiters()
 8833                {
 8834                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8835                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8836                    let prefix_range = comment_prefix_range(
 8837                        snapshot.deref(),
 8838                        start_row,
 8839                        comment_prefix,
 8840                        comment_prefix_whitespace,
 8841                    );
 8842                    let suffix_range = comment_suffix_range(
 8843                        snapshot.deref(),
 8844                        end_row,
 8845                        comment_suffix.trim_start_matches(' '),
 8846                        comment_suffix.starts_with(' '),
 8847                    );
 8848
 8849                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8850                        edits.push((
 8851                            prefix_range.start..prefix_range.start,
 8852                            full_comment_prefix.clone(),
 8853                        ));
 8854                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8855                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8856                    } else {
 8857                        edits.push((prefix_range, empty_str.clone()));
 8858                        edits.push((suffix_range, empty_str.clone()));
 8859                    }
 8860                } else {
 8861                    continue;
 8862                }
 8863            }
 8864
 8865            drop(snapshot);
 8866            this.buffer.update(cx, |buffer, cx| {
 8867                buffer.edit(edits, None, cx);
 8868            });
 8869
 8870            // Adjust selections so that they end before any comment suffixes that
 8871            // were inserted.
 8872            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8873            let mut selections = this.selections.all::<Point>(cx);
 8874            let snapshot = this.buffer.read(cx).read(cx);
 8875            for selection in &mut selections {
 8876                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8877                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8878                        Ordering::Less => {
 8879                            suffixes_inserted.next();
 8880                            continue;
 8881                        }
 8882                        Ordering::Greater => break,
 8883                        Ordering::Equal => {
 8884                            if selection.end.column == snapshot.line_len(row) {
 8885                                if selection.is_empty() {
 8886                                    selection.start.column -= suffix_len as u32;
 8887                                }
 8888                                selection.end.column -= suffix_len as u32;
 8889                            }
 8890                            break;
 8891                        }
 8892                    }
 8893                }
 8894            }
 8895
 8896            drop(snapshot);
 8897            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8898
 8899            let selections = this.selections.all::<Point>(cx);
 8900            let selections_on_single_row = selections.windows(2).all(|selections| {
 8901                selections[0].start.row == selections[1].start.row
 8902                    && selections[0].end.row == selections[1].end.row
 8903                    && selections[0].start.row == selections[0].end.row
 8904            });
 8905            let selections_selecting = selections
 8906                .iter()
 8907                .any(|selection| selection.start != selection.end);
 8908            let advance_downwards = action.advance_downwards
 8909                && selections_on_single_row
 8910                && !selections_selecting
 8911                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8912
 8913            if advance_downwards {
 8914                let snapshot = this.buffer.read(cx).snapshot(cx);
 8915
 8916                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8917                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8918                        let mut point = display_point.to_point(display_snapshot);
 8919                        point.row += 1;
 8920                        point = snapshot.clip_point(point, Bias::Left);
 8921                        let display_point = point.to_display_point(display_snapshot);
 8922                        let goal = SelectionGoal::HorizontalPosition(
 8923                            display_snapshot
 8924                                .x_for_display_point(display_point, text_layout_details)
 8925                                .into(),
 8926                        );
 8927                        (display_point, goal)
 8928                    })
 8929                });
 8930            }
 8931        });
 8932    }
 8933
 8934    pub fn select_enclosing_symbol(
 8935        &mut self,
 8936        _: &SelectEnclosingSymbol,
 8937        cx: &mut ViewContext<Self>,
 8938    ) {
 8939        let buffer = self.buffer.read(cx).snapshot(cx);
 8940        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8941
 8942        fn update_selection(
 8943            selection: &Selection<usize>,
 8944            buffer_snap: &MultiBufferSnapshot,
 8945        ) -> Option<Selection<usize>> {
 8946            let cursor = selection.head();
 8947            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8948            for symbol in symbols.iter().rev() {
 8949                let start = symbol.range.start.to_offset(buffer_snap);
 8950                let end = symbol.range.end.to_offset(buffer_snap);
 8951                let new_range = start..end;
 8952                if start < selection.start || end > selection.end {
 8953                    return Some(Selection {
 8954                        id: selection.id,
 8955                        start: new_range.start,
 8956                        end: new_range.end,
 8957                        goal: SelectionGoal::None,
 8958                        reversed: selection.reversed,
 8959                    });
 8960                }
 8961            }
 8962            None
 8963        }
 8964
 8965        let mut selected_larger_symbol = false;
 8966        let new_selections = old_selections
 8967            .iter()
 8968            .map(|selection| match update_selection(selection, &buffer) {
 8969                Some(new_selection) => {
 8970                    if new_selection.range() != selection.range() {
 8971                        selected_larger_symbol = true;
 8972                    }
 8973                    new_selection
 8974                }
 8975                None => selection.clone(),
 8976            })
 8977            .collect::<Vec<_>>();
 8978
 8979        if selected_larger_symbol {
 8980            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8981                s.select(new_selections);
 8982            });
 8983        }
 8984    }
 8985
 8986    pub fn select_larger_syntax_node(
 8987        &mut self,
 8988        _: &SelectLargerSyntaxNode,
 8989        cx: &mut ViewContext<Self>,
 8990    ) {
 8991        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8992        let buffer = self.buffer.read(cx).snapshot(cx);
 8993        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8994
 8995        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8996        let mut selected_larger_node = false;
 8997        let new_selections = old_selections
 8998            .iter()
 8999            .map(|selection| {
 9000                let old_range = selection.start..selection.end;
 9001                let mut new_range = old_range.clone();
 9002                while let Some(containing_range) =
 9003                    buffer.range_for_syntax_ancestor(new_range.clone())
 9004                {
 9005                    new_range = containing_range;
 9006                    if !display_map.intersects_fold(new_range.start)
 9007                        && !display_map.intersects_fold(new_range.end)
 9008                    {
 9009                        break;
 9010                    }
 9011                }
 9012
 9013                selected_larger_node |= new_range != old_range;
 9014                Selection {
 9015                    id: selection.id,
 9016                    start: new_range.start,
 9017                    end: new_range.end,
 9018                    goal: SelectionGoal::None,
 9019                    reversed: selection.reversed,
 9020                }
 9021            })
 9022            .collect::<Vec<_>>();
 9023
 9024        if selected_larger_node {
 9025            stack.push(old_selections);
 9026            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9027                s.select(new_selections);
 9028            });
 9029        }
 9030        self.select_larger_syntax_node_stack = stack;
 9031    }
 9032
 9033    pub fn select_smaller_syntax_node(
 9034        &mut self,
 9035        _: &SelectSmallerSyntaxNode,
 9036        cx: &mut ViewContext<Self>,
 9037    ) {
 9038        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9039        if let Some(selections) = stack.pop() {
 9040            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9041                s.select(selections.to_vec());
 9042            });
 9043        }
 9044        self.select_larger_syntax_node_stack = stack;
 9045    }
 9046
 9047    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9048        if !EditorSettings::get_global(cx).gutter.runnables {
 9049            self.clear_tasks();
 9050            return Task::ready(());
 9051        }
 9052        let project = self.project.clone();
 9053        cx.spawn(|this, mut cx| async move {
 9054            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9055                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9056            }) else {
 9057                return;
 9058            };
 9059
 9060            let Some(project) = project else {
 9061                return;
 9062            };
 9063
 9064            let hide_runnables = project
 9065                .update(&mut cx, |project, cx| {
 9066                    // Do not display any test indicators in non-dev server remote projects.
 9067                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9068                })
 9069                .unwrap_or(true);
 9070            if hide_runnables {
 9071                return;
 9072            }
 9073            let new_rows =
 9074                cx.background_executor()
 9075                    .spawn({
 9076                        let snapshot = display_snapshot.clone();
 9077                        async move {
 9078                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9079                        }
 9080                    })
 9081                    .await;
 9082            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9083
 9084            this.update(&mut cx, |this, _| {
 9085                this.clear_tasks();
 9086                for (key, value) in rows {
 9087                    this.insert_tasks(key, value);
 9088                }
 9089            })
 9090            .ok();
 9091        })
 9092    }
 9093    fn fetch_runnable_ranges(
 9094        snapshot: &DisplaySnapshot,
 9095        range: Range<Anchor>,
 9096    ) -> Vec<language::RunnableRange> {
 9097        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9098    }
 9099
 9100    fn runnable_rows(
 9101        project: Model<Project>,
 9102        snapshot: DisplaySnapshot,
 9103        runnable_ranges: Vec<RunnableRange>,
 9104        mut cx: AsyncWindowContext,
 9105    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9106        runnable_ranges
 9107            .into_iter()
 9108            .filter_map(|mut runnable| {
 9109                let tasks = cx
 9110                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9111                    .ok()?;
 9112                if tasks.is_empty() {
 9113                    return None;
 9114                }
 9115
 9116                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9117
 9118                let row = snapshot
 9119                    .buffer_snapshot
 9120                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9121                    .1
 9122                    .start
 9123                    .row;
 9124
 9125                let context_range =
 9126                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9127                Some((
 9128                    (runnable.buffer_id, row),
 9129                    RunnableTasks {
 9130                        templates: tasks,
 9131                        offset: MultiBufferOffset(runnable.run_range.start),
 9132                        context_range,
 9133                        column: point.column,
 9134                        extra_variables: runnable.extra_captures,
 9135                    },
 9136                ))
 9137            })
 9138            .collect()
 9139    }
 9140
 9141    fn templates_with_tags(
 9142        project: &Model<Project>,
 9143        runnable: &mut Runnable,
 9144        cx: &WindowContext<'_>,
 9145    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9146        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9147            let (worktree_id, file) = project
 9148                .buffer_for_id(runnable.buffer, cx)
 9149                .and_then(|buffer| buffer.read(cx).file())
 9150                .map(|file| (file.worktree_id(cx), file.clone()))
 9151                .unzip();
 9152
 9153            (
 9154                project.task_store().read(cx).task_inventory().cloned(),
 9155                worktree_id,
 9156                file,
 9157            )
 9158        });
 9159
 9160        let tags = mem::take(&mut runnable.tags);
 9161        let mut tags: Vec<_> = tags
 9162            .into_iter()
 9163            .flat_map(|tag| {
 9164                let tag = tag.0.clone();
 9165                inventory
 9166                    .as_ref()
 9167                    .into_iter()
 9168                    .flat_map(|inventory| {
 9169                        inventory.read(cx).list_tasks(
 9170                            file.clone(),
 9171                            Some(runnable.language.clone()),
 9172                            worktree_id,
 9173                            cx,
 9174                        )
 9175                    })
 9176                    .filter(move |(_, template)| {
 9177                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9178                    })
 9179            })
 9180            .sorted_by_key(|(kind, _)| kind.to_owned())
 9181            .collect();
 9182        if let Some((leading_tag_source, _)) = tags.first() {
 9183            // Strongest source wins; if we have worktree tag binding, prefer that to
 9184            // global and language bindings;
 9185            // if we have a global binding, prefer that to language binding.
 9186            let first_mismatch = tags
 9187                .iter()
 9188                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9189            if let Some(index) = first_mismatch {
 9190                tags.truncate(index);
 9191            }
 9192        }
 9193
 9194        tags
 9195    }
 9196
 9197    pub fn move_to_enclosing_bracket(
 9198        &mut self,
 9199        _: &MoveToEnclosingBracket,
 9200        cx: &mut ViewContext<Self>,
 9201    ) {
 9202        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9203            s.move_offsets_with(|snapshot, selection| {
 9204                let Some(enclosing_bracket_ranges) =
 9205                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9206                else {
 9207                    return;
 9208                };
 9209
 9210                let mut best_length = usize::MAX;
 9211                let mut best_inside = false;
 9212                let mut best_in_bracket_range = false;
 9213                let mut best_destination = None;
 9214                for (open, close) in enclosing_bracket_ranges {
 9215                    let close = close.to_inclusive();
 9216                    let length = close.end() - open.start;
 9217                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9218                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9219                        || close.contains(&selection.head());
 9220
 9221                    // If best is next to a bracket and current isn't, skip
 9222                    if !in_bracket_range && best_in_bracket_range {
 9223                        continue;
 9224                    }
 9225
 9226                    // Prefer smaller lengths unless best is inside and current isn't
 9227                    if length > best_length && (best_inside || !inside) {
 9228                        continue;
 9229                    }
 9230
 9231                    best_length = length;
 9232                    best_inside = inside;
 9233                    best_in_bracket_range = in_bracket_range;
 9234                    best_destination = Some(
 9235                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9236                            if inside {
 9237                                open.end
 9238                            } else {
 9239                                open.start
 9240                            }
 9241                        } else if inside {
 9242                            *close.start()
 9243                        } else {
 9244                            *close.end()
 9245                        },
 9246                    );
 9247                }
 9248
 9249                if let Some(destination) = best_destination {
 9250                    selection.collapse_to(destination, SelectionGoal::None);
 9251                }
 9252            })
 9253        });
 9254    }
 9255
 9256    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9257        self.end_selection(cx);
 9258        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9259        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9260            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9261            self.select_next_state = entry.select_next_state;
 9262            self.select_prev_state = entry.select_prev_state;
 9263            self.add_selections_state = entry.add_selections_state;
 9264            self.request_autoscroll(Autoscroll::newest(), cx);
 9265        }
 9266        self.selection_history.mode = SelectionHistoryMode::Normal;
 9267    }
 9268
 9269    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9270        self.end_selection(cx);
 9271        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9272        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9273            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9274            self.select_next_state = entry.select_next_state;
 9275            self.select_prev_state = entry.select_prev_state;
 9276            self.add_selections_state = entry.add_selections_state;
 9277            self.request_autoscroll(Autoscroll::newest(), cx);
 9278        }
 9279        self.selection_history.mode = SelectionHistoryMode::Normal;
 9280    }
 9281
 9282    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9283        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9284    }
 9285
 9286    pub fn expand_excerpts_down(
 9287        &mut self,
 9288        action: &ExpandExcerptsDown,
 9289        cx: &mut ViewContext<Self>,
 9290    ) {
 9291        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9292    }
 9293
 9294    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9295        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9296    }
 9297
 9298    pub fn expand_excerpts_for_direction(
 9299        &mut self,
 9300        lines: u32,
 9301        direction: ExpandExcerptDirection,
 9302        cx: &mut ViewContext<Self>,
 9303    ) {
 9304        let selections = self.selections.disjoint_anchors();
 9305
 9306        let lines = if lines == 0 {
 9307            EditorSettings::get_global(cx).expand_excerpt_lines
 9308        } else {
 9309            lines
 9310        };
 9311
 9312        self.buffer.update(cx, |buffer, cx| {
 9313            buffer.expand_excerpts(
 9314                selections
 9315                    .iter()
 9316                    .map(|selection| selection.head().excerpt_id)
 9317                    .dedup(),
 9318                lines,
 9319                direction,
 9320                cx,
 9321            )
 9322        })
 9323    }
 9324
 9325    pub fn expand_excerpt(
 9326        &mut self,
 9327        excerpt: ExcerptId,
 9328        direction: ExpandExcerptDirection,
 9329        cx: &mut ViewContext<Self>,
 9330    ) {
 9331        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9332        self.buffer.update(cx, |buffer, cx| {
 9333            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9334        })
 9335    }
 9336
 9337    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9338        self.go_to_diagnostic_impl(Direction::Next, cx)
 9339    }
 9340
 9341    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9342        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9343    }
 9344
 9345    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9346        let buffer = self.buffer.read(cx).snapshot(cx);
 9347        let selection = self.selections.newest::<usize>(cx);
 9348
 9349        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9350        if direction == Direction::Next {
 9351            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9352                let (group_id, jump_to) = popover.activation_info();
 9353                if self.activate_diagnostics(group_id, cx) {
 9354                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9355                        let mut new_selection = s.newest_anchor().clone();
 9356                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9357                        s.select_anchors(vec![new_selection.clone()]);
 9358                    });
 9359                }
 9360                return;
 9361            }
 9362        }
 9363
 9364        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9365            active_diagnostics
 9366                .primary_range
 9367                .to_offset(&buffer)
 9368                .to_inclusive()
 9369        });
 9370        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9371            if active_primary_range.contains(&selection.head()) {
 9372                *active_primary_range.start()
 9373            } else {
 9374                selection.head()
 9375            }
 9376        } else {
 9377            selection.head()
 9378        };
 9379        let snapshot = self.snapshot(cx);
 9380        loop {
 9381            let diagnostics = if direction == Direction::Prev {
 9382                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9383            } else {
 9384                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9385            }
 9386            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9387            let group = diagnostics
 9388                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9389                // be sorted in a stable way
 9390                // skip until we are at current active diagnostic, if it exists
 9391                .skip_while(|entry| {
 9392                    (match direction {
 9393                        Direction::Prev => entry.range.start >= search_start,
 9394                        Direction::Next => entry.range.start <= search_start,
 9395                    }) && self
 9396                        .active_diagnostics
 9397                        .as_ref()
 9398                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9399                })
 9400                .find_map(|entry| {
 9401                    if entry.diagnostic.is_primary
 9402                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9403                        && !entry.range.is_empty()
 9404                        // if we match with the active diagnostic, skip it
 9405                        && Some(entry.diagnostic.group_id)
 9406                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9407                    {
 9408                        Some((entry.range, entry.diagnostic.group_id))
 9409                    } else {
 9410                        None
 9411                    }
 9412                });
 9413
 9414            if let Some((primary_range, group_id)) = group {
 9415                if self.activate_diagnostics(group_id, cx) {
 9416                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9417                        s.select(vec![Selection {
 9418                            id: selection.id,
 9419                            start: primary_range.start,
 9420                            end: primary_range.start,
 9421                            reversed: false,
 9422                            goal: SelectionGoal::None,
 9423                        }]);
 9424                    });
 9425                }
 9426                break;
 9427            } else {
 9428                // Cycle around to the start of the buffer, potentially moving back to the start of
 9429                // the currently active diagnostic.
 9430                active_primary_range.take();
 9431                if direction == Direction::Prev {
 9432                    if search_start == buffer.len() {
 9433                        break;
 9434                    } else {
 9435                        search_start = buffer.len();
 9436                    }
 9437                } else if search_start == 0 {
 9438                    break;
 9439                } else {
 9440                    search_start = 0;
 9441                }
 9442            }
 9443        }
 9444    }
 9445
 9446    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9447        let snapshot = self
 9448            .display_map
 9449            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9450        let selection = self.selections.newest::<Point>(cx);
 9451        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9452    }
 9453
 9454    fn go_to_hunk_after_position(
 9455        &mut self,
 9456        snapshot: &DisplaySnapshot,
 9457        position: Point,
 9458        cx: &mut ViewContext<'_, Editor>,
 9459    ) -> Option<MultiBufferDiffHunk> {
 9460        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9461            snapshot,
 9462            position,
 9463            false,
 9464            snapshot
 9465                .buffer_snapshot
 9466                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9467            cx,
 9468        ) {
 9469            return Some(hunk);
 9470        }
 9471
 9472        let wrapped_point = Point::zero();
 9473        self.go_to_next_hunk_in_direction(
 9474            snapshot,
 9475            wrapped_point,
 9476            true,
 9477            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9478                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9479            ),
 9480            cx,
 9481        )
 9482    }
 9483
 9484    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9485        let snapshot = self
 9486            .display_map
 9487            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9488        let selection = self.selections.newest::<Point>(cx);
 9489
 9490        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9491    }
 9492
 9493    fn go_to_hunk_before_position(
 9494        &mut self,
 9495        snapshot: &DisplaySnapshot,
 9496        position: Point,
 9497        cx: &mut ViewContext<'_, Editor>,
 9498    ) -> Option<MultiBufferDiffHunk> {
 9499        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9500            snapshot,
 9501            position,
 9502            false,
 9503            snapshot
 9504                .buffer_snapshot
 9505                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9506            cx,
 9507        ) {
 9508            return Some(hunk);
 9509        }
 9510
 9511        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9512        self.go_to_next_hunk_in_direction(
 9513            snapshot,
 9514            wrapped_point,
 9515            true,
 9516            snapshot
 9517                .buffer_snapshot
 9518                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9519            cx,
 9520        )
 9521    }
 9522
 9523    fn go_to_next_hunk_in_direction(
 9524        &mut self,
 9525        snapshot: &DisplaySnapshot,
 9526        initial_point: Point,
 9527        is_wrapped: bool,
 9528        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9529        cx: &mut ViewContext<Editor>,
 9530    ) -> Option<MultiBufferDiffHunk> {
 9531        let display_point = initial_point.to_display_point(snapshot);
 9532        let mut hunks = hunks
 9533            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9534            .filter(|(display_hunk, _)| {
 9535                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9536            })
 9537            .dedup();
 9538
 9539        if let Some((display_hunk, hunk)) = hunks.next() {
 9540            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9541                let row = display_hunk.start_display_row();
 9542                let point = DisplayPoint::new(row, 0);
 9543                s.select_display_ranges([point..point]);
 9544            });
 9545
 9546            Some(hunk)
 9547        } else {
 9548            None
 9549        }
 9550    }
 9551
 9552    pub fn go_to_definition(
 9553        &mut self,
 9554        _: &GoToDefinition,
 9555        cx: &mut ViewContext<Self>,
 9556    ) -> Task<Result<Navigated>> {
 9557        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9558        cx.spawn(|editor, mut cx| async move {
 9559            if definition.await? == Navigated::Yes {
 9560                return Ok(Navigated::Yes);
 9561            }
 9562            match editor.update(&mut cx, |editor, cx| {
 9563                editor.find_all_references(&FindAllReferences, cx)
 9564            })? {
 9565                Some(references) => references.await,
 9566                None => Ok(Navigated::No),
 9567            }
 9568        })
 9569    }
 9570
 9571    pub fn go_to_declaration(
 9572        &mut self,
 9573        _: &GoToDeclaration,
 9574        cx: &mut ViewContext<Self>,
 9575    ) -> Task<Result<Navigated>> {
 9576        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9577    }
 9578
 9579    pub fn go_to_declaration_split(
 9580        &mut self,
 9581        _: &GoToDeclaration,
 9582        cx: &mut ViewContext<Self>,
 9583    ) -> Task<Result<Navigated>> {
 9584        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9585    }
 9586
 9587    pub fn go_to_implementation(
 9588        &mut self,
 9589        _: &GoToImplementation,
 9590        cx: &mut ViewContext<Self>,
 9591    ) -> Task<Result<Navigated>> {
 9592        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9593    }
 9594
 9595    pub fn go_to_implementation_split(
 9596        &mut self,
 9597        _: &GoToImplementationSplit,
 9598        cx: &mut ViewContext<Self>,
 9599    ) -> Task<Result<Navigated>> {
 9600        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9601    }
 9602
 9603    pub fn go_to_type_definition(
 9604        &mut self,
 9605        _: &GoToTypeDefinition,
 9606        cx: &mut ViewContext<Self>,
 9607    ) -> Task<Result<Navigated>> {
 9608        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9609    }
 9610
 9611    pub fn go_to_definition_split(
 9612        &mut self,
 9613        _: &GoToDefinitionSplit,
 9614        cx: &mut ViewContext<Self>,
 9615    ) -> Task<Result<Navigated>> {
 9616        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9617    }
 9618
 9619    pub fn go_to_type_definition_split(
 9620        &mut self,
 9621        _: &GoToTypeDefinitionSplit,
 9622        cx: &mut ViewContext<Self>,
 9623    ) -> Task<Result<Navigated>> {
 9624        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9625    }
 9626
 9627    fn go_to_definition_of_kind(
 9628        &mut self,
 9629        kind: GotoDefinitionKind,
 9630        split: bool,
 9631        cx: &mut ViewContext<Self>,
 9632    ) -> Task<Result<Navigated>> {
 9633        let Some(provider) = self.semantics_provider.clone() else {
 9634            return Task::ready(Ok(Navigated::No));
 9635        };
 9636        let buffer = self.buffer.read(cx);
 9637        let head = self.selections.newest::<usize>(cx).head();
 9638        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9639            text_anchor
 9640        } else {
 9641            return Task::ready(Ok(Navigated::No));
 9642        };
 9643
 9644        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9645            return Task::ready(Ok(Navigated::No));
 9646        };
 9647
 9648        cx.spawn(|editor, mut cx| async move {
 9649            let definitions = definitions.await?;
 9650            let navigated = editor
 9651                .update(&mut cx, |editor, cx| {
 9652                    editor.navigate_to_hover_links(
 9653                        Some(kind),
 9654                        definitions
 9655                            .into_iter()
 9656                            .filter(|location| {
 9657                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9658                            })
 9659                            .map(HoverLink::Text)
 9660                            .collect::<Vec<_>>(),
 9661                        split,
 9662                        cx,
 9663                    )
 9664                })?
 9665                .await?;
 9666            anyhow::Ok(navigated)
 9667        })
 9668    }
 9669
 9670    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9671        let position = self.selections.newest_anchor().head();
 9672        let Some((buffer, buffer_position)) =
 9673            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9674        else {
 9675            return;
 9676        };
 9677
 9678        cx.spawn(|editor, mut cx| async move {
 9679            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9680                editor.update(&mut cx, |_, cx| {
 9681                    cx.open_url(&url);
 9682                })
 9683            } else {
 9684                Ok(())
 9685            }
 9686        })
 9687        .detach();
 9688    }
 9689
 9690    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9691        let Some(workspace) = self.workspace() else {
 9692            return;
 9693        };
 9694
 9695        let position = self.selections.newest_anchor().head();
 9696
 9697        let Some((buffer, buffer_position)) =
 9698            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9699        else {
 9700            return;
 9701        };
 9702
 9703        let project = self.project.clone();
 9704
 9705        cx.spawn(|_, mut cx| async move {
 9706            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9707
 9708            if let Some((_, path)) = result {
 9709                workspace
 9710                    .update(&mut cx, |workspace, cx| {
 9711                        workspace.open_resolved_path(path, cx)
 9712                    })?
 9713                    .await?;
 9714            }
 9715            anyhow::Ok(())
 9716        })
 9717        .detach();
 9718    }
 9719
 9720    pub(crate) fn navigate_to_hover_links(
 9721        &mut self,
 9722        kind: Option<GotoDefinitionKind>,
 9723        mut definitions: Vec<HoverLink>,
 9724        split: bool,
 9725        cx: &mut ViewContext<Editor>,
 9726    ) -> Task<Result<Navigated>> {
 9727        // If there is one definition, just open it directly
 9728        if definitions.len() == 1 {
 9729            let definition = definitions.pop().unwrap();
 9730
 9731            enum TargetTaskResult {
 9732                Location(Option<Location>),
 9733                AlreadyNavigated,
 9734            }
 9735
 9736            let target_task = match definition {
 9737                HoverLink::Text(link) => {
 9738                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9739                }
 9740                HoverLink::InlayHint(lsp_location, server_id) => {
 9741                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9742                    cx.background_executor().spawn(async move {
 9743                        let location = computation.await?;
 9744                        Ok(TargetTaskResult::Location(location))
 9745                    })
 9746                }
 9747                HoverLink::Url(url) => {
 9748                    cx.open_url(&url);
 9749                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9750                }
 9751                HoverLink::File(path) => {
 9752                    if let Some(workspace) = self.workspace() {
 9753                        cx.spawn(|_, mut cx| async move {
 9754                            workspace
 9755                                .update(&mut cx, |workspace, cx| {
 9756                                    workspace.open_resolved_path(path, cx)
 9757                                })?
 9758                                .await
 9759                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9760                        })
 9761                    } else {
 9762                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9763                    }
 9764                }
 9765            };
 9766            cx.spawn(|editor, mut cx| async move {
 9767                let target = match target_task.await.context("target resolution task")? {
 9768                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9769                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9770                    TargetTaskResult::Location(Some(target)) => target,
 9771                };
 9772
 9773                editor.update(&mut cx, |editor, cx| {
 9774                    let Some(workspace) = editor.workspace() else {
 9775                        return Navigated::No;
 9776                    };
 9777                    let pane = workspace.read(cx).active_pane().clone();
 9778
 9779                    let range = target.range.to_offset(target.buffer.read(cx));
 9780                    let range = editor.range_for_match(&range);
 9781
 9782                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9783                        let buffer = target.buffer.read(cx);
 9784                        let range = check_multiline_range(buffer, range);
 9785                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9786                            s.select_ranges([range]);
 9787                        });
 9788                    } else {
 9789                        cx.window_context().defer(move |cx| {
 9790                            let target_editor: View<Self> =
 9791                                workspace.update(cx, |workspace, cx| {
 9792                                    let pane = if split {
 9793                                        workspace.adjacent_pane(cx)
 9794                                    } else {
 9795                                        workspace.active_pane().clone()
 9796                                    };
 9797
 9798                                    workspace.open_project_item(
 9799                                        pane,
 9800                                        target.buffer.clone(),
 9801                                        true,
 9802                                        true,
 9803                                        cx,
 9804                                    )
 9805                                });
 9806                            target_editor.update(cx, |target_editor, cx| {
 9807                                // When selecting a definition in a different buffer, disable the nav history
 9808                                // to avoid creating a history entry at the previous cursor location.
 9809                                pane.update(cx, |pane, _| pane.disable_history());
 9810                                let buffer = target.buffer.read(cx);
 9811                                let range = check_multiline_range(buffer, range);
 9812                                target_editor.change_selections(
 9813                                    Some(Autoscroll::focused()),
 9814                                    cx,
 9815                                    |s| {
 9816                                        s.select_ranges([range]);
 9817                                    },
 9818                                );
 9819                                pane.update(cx, |pane, _| pane.enable_history());
 9820                            });
 9821                        });
 9822                    }
 9823                    Navigated::Yes
 9824                })
 9825            })
 9826        } else if !definitions.is_empty() {
 9827            cx.spawn(|editor, mut cx| async move {
 9828                let (title, location_tasks, workspace) = editor
 9829                    .update(&mut cx, |editor, cx| {
 9830                        let tab_kind = match kind {
 9831                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9832                            _ => "Definitions",
 9833                        };
 9834                        let title = definitions
 9835                            .iter()
 9836                            .find_map(|definition| match definition {
 9837                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9838                                    let buffer = origin.buffer.read(cx);
 9839                                    format!(
 9840                                        "{} for {}",
 9841                                        tab_kind,
 9842                                        buffer
 9843                                            .text_for_range(origin.range.clone())
 9844                                            .collect::<String>()
 9845                                    )
 9846                                }),
 9847                                HoverLink::InlayHint(_, _) => None,
 9848                                HoverLink::Url(_) => None,
 9849                                HoverLink::File(_) => None,
 9850                            })
 9851                            .unwrap_or(tab_kind.to_string());
 9852                        let location_tasks = definitions
 9853                            .into_iter()
 9854                            .map(|definition| match definition {
 9855                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9856                                HoverLink::InlayHint(lsp_location, server_id) => {
 9857                                    editor.compute_target_location(lsp_location, server_id, cx)
 9858                                }
 9859                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9860                                HoverLink::File(_) => Task::ready(Ok(None)),
 9861                            })
 9862                            .collect::<Vec<_>>();
 9863                        (title, location_tasks, editor.workspace().clone())
 9864                    })
 9865                    .context("location tasks preparation")?;
 9866
 9867                let locations = future::join_all(location_tasks)
 9868                    .await
 9869                    .into_iter()
 9870                    .filter_map(|location| location.transpose())
 9871                    .collect::<Result<_>>()
 9872                    .context("location tasks")?;
 9873
 9874                let Some(workspace) = workspace else {
 9875                    return Ok(Navigated::No);
 9876                };
 9877                let opened = workspace
 9878                    .update(&mut cx, |workspace, cx| {
 9879                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9880                    })
 9881                    .ok();
 9882
 9883                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9884            })
 9885        } else {
 9886            Task::ready(Ok(Navigated::No))
 9887        }
 9888    }
 9889
 9890    fn compute_target_location(
 9891        &self,
 9892        lsp_location: lsp::Location,
 9893        server_id: LanguageServerId,
 9894        cx: &mut ViewContext<Self>,
 9895    ) -> Task<anyhow::Result<Option<Location>>> {
 9896        let Some(project) = self.project.clone() else {
 9897            return Task::Ready(Some(Ok(None)));
 9898        };
 9899
 9900        cx.spawn(move |editor, mut cx| async move {
 9901            let location_task = editor.update(&mut cx, |_, cx| {
 9902                project.update(cx, |project, cx| {
 9903                    let language_server_name = project
 9904                        .language_server_statuses(cx)
 9905                        .find(|(id, _)| server_id == *id)
 9906                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9907                    language_server_name.map(|language_server_name| {
 9908                        project.open_local_buffer_via_lsp(
 9909                            lsp_location.uri.clone(),
 9910                            server_id,
 9911                            language_server_name,
 9912                            cx,
 9913                        )
 9914                    })
 9915                })
 9916            })?;
 9917            let location = match location_task {
 9918                Some(task) => Some({
 9919                    let target_buffer_handle = task.await.context("open local buffer")?;
 9920                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9921                        let target_start = target_buffer
 9922                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9923                        let target_end = target_buffer
 9924                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9925                        target_buffer.anchor_after(target_start)
 9926                            ..target_buffer.anchor_before(target_end)
 9927                    })?;
 9928                    Location {
 9929                        buffer: target_buffer_handle,
 9930                        range,
 9931                    }
 9932                }),
 9933                None => None,
 9934            };
 9935            Ok(location)
 9936        })
 9937    }
 9938
 9939    pub fn find_all_references(
 9940        &mut self,
 9941        _: &FindAllReferences,
 9942        cx: &mut ViewContext<Self>,
 9943    ) -> Option<Task<Result<Navigated>>> {
 9944        let multi_buffer = self.buffer.read(cx);
 9945        let selection = self.selections.newest::<usize>(cx);
 9946        let head = selection.head();
 9947
 9948        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9949        let head_anchor = multi_buffer_snapshot.anchor_at(
 9950            head,
 9951            if head < selection.tail() {
 9952                Bias::Right
 9953            } else {
 9954                Bias::Left
 9955            },
 9956        );
 9957
 9958        match self
 9959            .find_all_references_task_sources
 9960            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9961        {
 9962            Ok(_) => {
 9963                log::info!(
 9964                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9965                );
 9966                return None;
 9967            }
 9968            Err(i) => {
 9969                self.find_all_references_task_sources.insert(i, head_anchor);
 9970            }
 9971        }
 9972
 9973        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9974        let workspace = self.workspace()?;
 9975        let project = workspace.read(cx).project().clone();
 9976        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9977        Some(cx.spawn(|editor, mut cx| async move {
 9978            let _cleanup = defer({
 9979                let mut cx = cx.clone();
 9980                move || {
 9981                    let _ = editor.update(&mut cx, |editor, _| {
 9982                        if let Ok(i) =
 9983                            editor
 9984                                .find_all_references_task_sources
 9985                                .binary_search_by(|anchor| {
 9986                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9987                                })
 9988                        {
 9989                            editor.find_all_references_task_sources.remove(i);
 9990                        }
 9991                    });
 9992                }
 9993            });
 9994
 9995            let locations = references.await?;
 9996            if locations.is_empty() {
 9997                return anyhow::Ok(Navigated::No);
 9998            }
 9999
10000            workspace.update(&mut cx, |workspace, cx| {
10001                let title = locations
10002                    .first()
10003                    .as_ref()
10004                    .map(|location| {
10005                        let buffer = location.buffer.read(cx);
10006                        format!(
10007                            "References to `{}`",
10008                            buffer
10009                                .text_for_range(location.range.clone())
10010                                .collect::<String>()
10011                        )
10012                    })
10013                    .unwrap();
10014                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10015                Navigated::Yes
10016            })
10017        }))
10018    }
10019
10020    /// Opens a multibuffer with the given project locations in it
10021    pub fn open_locations_in_multibuffer(
10022        workspace: &mut Workspace,
10023        mut locations: Vec<Location>,
10024        title: String,
10025        split: bool,
10026        cx: &mut ViewContext<Workspace>,
10027    ) {
10028        // If there are multiple definitions, open them in a multibuffer
10029        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10030        let mut locations = locations.into_iter().peekable();
10031        let mut ranges_to_highlight = Vec::new();
10032        let capability = workspace.project().read(cx).capability();
10033
10034        let excerpt_buffer = cx.new_model(|cx| {
10035            let mut multibuffer = MultiBuffer::new(capability);
10036            while let Some(location) = locations.next() {
10037                let buffer = location.buffer.read(cx);
10038                let mut ranges_for_buffer = Vec::new();
10039                let range = location.range.to_offset(buffer);
10040                ranges_for_buffer.push(range.clone());
10041
10042                while let Some(next_location) = locations.peek() {
10043                    if next_location.buffer == location.buffer {
10044                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10045                        locations.next();
10046                    } else {
10047                        break;
10048                    }
10049                }
10050
10051                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10052                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10053                    location.buffer.clone(),
10054                    ranges_for_buffer,
10055                    DEFAULT_MULTIBUFFER_CONTEXT,
10056                    cx,
10057                ))
10058            }
10059
10060            multibuffer.with_title(title)
10061        });
10062
10063        let editor = cx.new_view(|cx| {
10064            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10065        });
10066        editor.update(cx, |editor, cx| {
10067            if let Some(first_range) = ranges_to_highlight.first() {
10068                editor.change_selections(None, cx, |selections| {
10069                    selections.clear_disjoint();
10070                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10071                });
10072            }
10073            editor.highlight_background::<Self>(
10074                &ranges_to_highlight,
10075                |theme| theme.editor_highlighted_line_background,
10076                cx,
10077            );
10078        });
10079
10080        let item = Box::new(editor);
10081        let item_id = item.item_id();
10082
10083        if split {
10084            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10085        } else {
10086            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10087                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10088                    pane.close_current_preview_item(cx)
10089                } else {
10090                    None
10091                }
10092            });
10093            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10094        }
10095        workspace.active_pane().update(cx, |pane, cx| {
10096            pane.set_preview_item_id(Some(item_id), cx);
10097        });
10098    }
10099
10100    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10101        use language::ToOffset as _;
10102
10103        let provider = self.semantics_provider.clone()?;
10104        let selection = self.selections.newest_anchor().clone();
10105        let (cursor_buffer, cursor_buffer_position) = self
10106            .buffer
10107            .read(cx)
10108            .text_anchor_for_position(selection.head(), cx)?;
10109        let (tail_buffer, cursor_buffer_position_end) = self
10110            .buffer
10111            .read(cx)
10112            .text_anchor_for_position(selection.tail(), cx)?;
10113        if tail_buffer != cursor_buffer {
10114            return None;
10115        }
10116
10117        let snapshot = cursor_buffer.read(cx).snapshot();
10118        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10119        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10120        let prepare_rename = provider
10121            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10122            .unwrap_or_else(|| Task::ready(Ok(None)));
10123        drop(snapshot);
10124
10125        Some(cx.spawn(|this, mut cx| async move {
10126            let rename_range = if let Some(range) = prepare_rename.await? {
10127                Some(range)
10128            } else {
10129                this.update(&mut cx, |this, cx| {
10130                    let buffer = this.buffer.read(cx).snapshot(cx);
10131                    let mut buffer_highlights = this
10132                        .document_highlights_for_position(selection.head(), &buffer)
10133                        .filter(|highlight| {
10134                            highlight.start.excerpt_id == selection.head().excerpt_id
10135                                && highlight.end.excerpt_id == selection.head().excerpt_id
10136                        });
10137                    buffer_highlights
10138                        .next()
10139                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10140                })?
10141            };
10142            if let Some(rename_range) = rename_range {
10143                this.update(&mut cx, |this, cx| {
10144                    let snapshot = cursor_buffer.read(cx).snapshot();
10145                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10146                    let cursor_offset_in_rename_range =
10147                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10148                    let cursor_offset_in_rename_range_end =
10149                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10150
10151                    this.take_rename(false, cx);
10152                    let buffer = this.buffer.read(cx).read(cx);
10153                    let cursor_offset = selection.head().to_offset(&buffer);
10154                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10155                    let rename_end = rename_start + rename_buffer_range.len();
10156                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10157                    let mut old_highlight_id = None;
10158                    let old_name: Arc<str> = buffer
10159                        .chunks(rename_start..rename_end, true)
10160                        .map(|chunk| {
10161                            if old_highlight_id.is_none() {
10162                                old_highlight_id = chunk.syntax_highlight_id;
10163                            }
10164                            chunk.text
10165                        })
10166                        .collect::<String>()
10167                        .into();
10168
10169                    drop(buffer);
10170
10171                    // Position the selection in the rename editor so that it matches the current selection.
10172                    this.show_local_selections = false;
10173                    let rename_editor = cx.new_view(|cx| {
10174                        let mut editor = Editor::single_line(cx);
10175                        editor.buffer.update(cx, |buffer, cx| {
10176                            buffer.edit([(0..0, old_name.clone())], None, cx)
10177                        });
10178                        let rename_selection_range = match cursor_offset_in_rename_range
10179                            .cmp(&cursor_offset_in_rename_range_end)
10180                        {
10181                            Ordering::Equal => {
10182                                editor.select_all(&SelectAll, cx);
10183                                return editor;
10184                            }
10185                            Ordering::Less => {
10186                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10187                            }
10188                            Ordering::Greater => {
10189                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10190                            }
10191                        };
10192                        if rename_selection_range.end > old_name.len() {
10193                            editor.select_all(&SelectAll, cx);
10194                        } else {
10195                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10196                                s.select_ranges([rename_selection_range]);
10197                            });
10198                        }
10199                        editor
10200                    });
10201                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10202                        if e == &EditorEvent::Focused {
10203                            cx.emit(EditorEvent::FocusedIn)
10204                        }
10205                    })
10206                    .detach();
10207
10208                    let write_highlights =
10209                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10210                    let read_highlights =
10211                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10212                    let ranges = write_highlights
10213                        .iter()
10214                        .flat_map(|(_, ranges)| ranges.iter())
10215                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10216                        .cloned()
10217                        .collect();
10218
10219                    this.highlight_text::<Rename>(
10220                        ranges,
10221                        HighlightStyle {
10222                            fade_out: Some(0.6),
10223                            ..Default::default()
10224                        },
10225                        cx,
10226                    );
10227                    let rename_focus_handle = rename_editor.focus_handle(cx);
10228                    cx.focus(&rename_focus_handle);
10229                    let block_id = this.insert_blocks(
10230                        [BlockProperties {
10231                            style: BlockStyle::Flex,
10232                            position: range.start,
10233                            height: 1,
10234                            render: Box::new({
10235                                let rename_editor = rename_editor.clone();
10236                                move |cx: &mut BlockContext| {
10237                                    let mut text_style = cx.editor_style.text.clone();
10238                                    if let Some(highlight_style) = old_highlight_id
10239                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10240                                    {
10241                                        text_style = text_style.highlight(highlight_style);
10242                                    }
10243                                    div()
10244                                        .pl(cx.anchor_x)
10245                                        .child(EditorElement::new(
10246                                            &rename_editor,
10247                                            EditorStyle {
10248                                                background: cx.theme().system().transparent,
10249                                                local_player: cx.editor_style.local_player,
10250                                                text: text_style,
10251                                                scrollbar_width: cx.editor_style.scrollbar_width,
10252                                                syntax: cx.editor_style.syntax.clone(),
10253                                                status: cx.editor_style.status.clone(),
10254                                                inlay_hints_style: HighlightStyle {
10255                                                    font_weight: Some(FontWeight::BOLD),
10256                                                    ..make_inlay_hints_style(cx)
10257                                                },
10258                                                suggestions_style: HighlightStyle {
10259                                                    color: Some(cx.theme().status().predictive),
10260                                                    ..HighlightStyle::default()
10261                                                },
10262                                                ..EditorStyle::default()
10263                                            },
10264                                        ))
10265                                        .into_any_element()
10266                                }
10267                            }),
10268                            disposition: BlockDisposition::Below,
10269                            priority: 0,
10270                        }],
10271                        Some(Autoscroll::fit()),
10272                        cx,
10273                    )[0];
10274                    this.pending_rename = Some(RenameState {
10275                        range,
10276                        old_name,
10277                        editor: rename_editor,
10278                        block_id,
10279                    });
10280                })?;
10281            }
10282
10283            Ok(())
10284        }))
10285    }
10286
10287    pub fn confirm_rename(
10288        &mut self,
10289        _: &ConfirmRename,
10290        cx: &mut ViewContext<Self>,
10291    ) -> Option<Task<Result<()>>> {
10292        let rename = self.take_rename(false, cx)?;
10293        let workspace = self.workspace()?.downgrade();
10294        let (buffer, start) = self
10295            .buffer
10296            .read(cx)
10297            .text_anchor_for_position(rename.range.start, cx)?;
10298        let (end_buffer, _) = self
10299            .buffer
10300            .read(cx)
10301            .text_anchor_for_position(rename.range.end, cx)?;
10302        if buffer != end_buffer {
10303            return None;
10304        }
10305
10306        let old_name = rename.old_name;
10307        let new_name = rename.editor.read(cx).text(cx);
10308
10309        let rename = self.semantics_provider.as_ref()?.perform_rename(
10310            &buffer,
10311            start,
10312            new_name.clone(),
10313            cx,
10314        )?;
10315
10316        Some(cx.spawn(|editor, mut cx| async move {
10317            let project_transaction = rename.await?;
10318            Self::open_project_transaction(
10319                &editor,
10320                workspace,
10321                project_transaction,
10322                format!("Rename: {}{}", old_name, new_name),
10323                cx.clone(),
10324            )
10325            .await?;
10326
10327            editor.update(&mut cx, |editor, cx| {
10328                editor.refresh_document_highlights(cx);
10329            })?;
10330            Ok(())
10331        }))
10332    }
10333
10334    fn take_rename(
10335        &mut self,
10336        moving_cursor: bool,
10337        cx: &mut ViewContext<Self>,
10338    ) -> Option<RenameState> {
10339        let rename = self.pending_rename.take()?;
10340        if rename.editor.focus_handle(cx).is_focused(cx) {
10341            cx.focus(&self.focus_handle);
10342        }
10343
10344        self.remove_blocks(
10345            [rename.block_id].into_iter().collect(),
10346            Some(Autoscroll::fit()),
10347            cx,
10348        );
10349        self.clear_highlights::<Rename>(cx);
10350        self.show_local_selections = true;
10351
10352        if moving_cursor {
10353            let rename_editor = rename.editor.read(cx);
10354            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10355
10356            // Update the selection to match the position of the selection inside
10357            // the rename editor.
10358            let snapshot = self.buffer.read(cx).read(cx);
10359            let rename_range = rename.range.to_offset(&snapshot);
10360            let cursor_in_editor = snapshot
10361                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10362                .min(rename_range.end);
10363            drop(snapshot);
10364
10365            self.change_selections(None, cx, |s| {
10366                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10367            });
10368        } else {
10369            self.refresh_document_highlights(cx);
10370        }
10371
10372        Some(rename)
10373    }
10374
10375    pub fn pending_rename(&self) -> Option<&RenameState> {
10376        self.pending_rename.as_ref()
10377    }
10378
10379    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10380        let project = match &self.project {
10381            Some(project) => project.clone(),
10382            None => return None,
10383        };
10384
10385        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10386    }
10387
10388    fn format_selections(
10389        &mut self,
10390        _: &FormatSelections,
10391        cx: &mut ViewContext<Self>,
10392    ) -> Option<Task<Result<()>>> {
10393        let project = match &self.project {
10394            Some(project) => project.clone(),
10395            None => return None,
10396        };
10397
10398        let selections = self
10399            .selections
10400            .all_adjusted(cx)
10401            .into_iter()
10402            .filter(|s| !s.is_empty())
10403            .collect_vec();
10404
10405        Some(self.perform_format(
10406            project,
10407            FormatTrigger::Manual,
10408            FormatTarget::Ranges(selections),
10409            cx,
10410        ))
10411    }
10412
10413    fn perform_format(
10414        &mut self,
10415        project: Model<Project>,
10416        trigger: FormatTrigger,
10417        target: FormatTarget,
10418        cx: &mut ViewContext<Self>,
10419    ) -> Task<Result<()>> {
10420        let buffer = self.buffer().clone();
10421        let mut buffers = buffer.read(cx).all_buffers();
10422        if trigger == FormatTrigger::Save {
10423            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10424        }
10425
10426        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10427        let format = project.update(cx, |project, cx| {
10428            project.format(buffers, true, trigger, target, cx)
10429        });
10430
10431        cx.spawn(|_, mut cx| async move {
10432            let transaction = futures::select_biased! {
10433                () = timeout => {
10434                    log::warn!("timed out waiting for formatting");
10435                    None
10436                }
10437                transaction = format.log_err().fuse() => transaction,
10438            };
10439
10440            buffer
10441                .update(&mut cx, |buffer, cx| {
10442                    if let Some(transaction) = transaction {
10443                        if !buffer.is_singleton() {
10444                            buffer.push_transaction(&transaction.0, cx);
10445                        }
10446                    }
10447
10448                    cx.notify();
10449                })
10450                .ok();
10451
10452            Ok(())
10453        })
10454    }
10455
10456    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10457        if let Some(project) = self.project.clone() {
10458            self.buffer.update(cx, |multi_buffer, cx| {
10459                project.update(cx, |project, cx| {
10460                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10461                });
10462            })
10463        }
10464    }
10465
10466    fn cancel_language_server_work(
10467        &mut self,
10468        _: &CancelLanguageServerWork,
10469        cx: &mut ViewContext<Self>,
10470    ) {
10471        if let Some(project) = self.project.clone() {
10472            self.buffer.update(cx, |multi_buffer, cx| {
10473                project.update(cx, |project, cx| {
10474                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10475                });
10476            })
10477        }
10478    }
10479
10480    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10481        cx.show_character_palette();
10482    }
10483
10484    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10485        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10486            let buffer = self.buffer.read(cx).snapshot(cx);
10487            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10488            let is_valid = buffer
10489                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10490                .any(|entry| {
10491                    entry.diagnostic.is_primary
10492                        && !entry.range.is_empty()
10493                        && entry.range.start == primary_range_start
10494                        && entry.diagnostic.message == active_diagnostics.primary_message
10495                });
10496
10497            if is_valid != active_diagnostics.is_valid {
10498                active_diagnostics.is_valid = is_valid;
10499                let mut new_styles = HashMap::default();
10500                for (block_id, diagnostic) in &active_diagnostics.blocks {
10501                    new_styles.insert(
10502                        *block_id,
10503                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10504                    );
10505                }
10506                self.display_map.update(cx, |display_map, _cx| {
10507                    display_map.replace_blocks(new_styles)
10508                });
10509            }
10510        }
10511    }
10512
10513    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10514        self.dismiss_diagnostics(cx);
10515        let snapshot = self.snapshot(cx);
10516        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10517            let buffer = self.buffer.read(cx).snapshot(cx);
10518
10519            let mut primary_range = None;
10520            let mut primary_message = None;
10521            let mut group_end = Point::zero();
10522            let diagnostic_group = buffer
10523                .diagnostic_group::<MultiBufferPoint>(group_id)
10524                .filter_map(|entry| {
10525                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10526                        && (entry.range.start.row == entry.range.end.row
10527                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10528                    {
10529                        return None;
10530                    }
10531                    if entry.range.end > group_end {
10532                        group_end = entry.range.end;
10533                    }
10534                    if entry.diagnostic.is_primary {
10535                        primary_range = Some(entry.range.clone());
10536                        primary_message = Some(entry.diagnostic.message.clone());
10537                    }
10538                    Some(entry)
10539                })
10540                .collect::<Vec<_>>();
10541            let primary_range = primary_range?;
10542            let primary_message = primary_message?;
10543            let primary_range =
10544                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10545
10546            let blocks = display_map
10547                .insert_blocks(
10548                    diagnostic_group.iter().map(|entry| {
10549                        let diagnostic = entry.diagnostic.clone();
10550                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10551                        BlockProperties {
10552                            style: BlockStyle::Fixed,
10553                            position: buffer.anchor_after(entry.range.start),
10554                            height: message_height,
10555                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10556                            disposition: BlockDisposition::Below,
10557                            priority: 0,
10558                        }
10559                    }),
10560                    cx,
10561                )
10562                .into_iter()
10563                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10564                .collect();
10565
10566            Some(ActiveDiagnosticGroup {
10567                primary_range,
10568                primary_message,
10569                group_id,
10570                blocks,
10571                is_valid: true,
10572            })
10573        });
10574        self.active_diagnostics.is_some()
10575    }
10576
10577    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10578        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10579            self.display_map.update(cx, |display_map, cx| {
10580                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10581            });
10582            cx.notify();
10583        }
10584    }
10585
10586    pub fn set_selections_from_remote(
10587        &mut self,
10588        selections: Vec<Selection<Anchor>>,
10589        pending_selection: Option<Selection<Anchor>>,
10590        cx: &mut ViewContext<Self>,
10591    ) {
10592        let old_cursor_position = self.selections.newest_anchor().head();
10593        self.selections.change_with(cx, |s| {
10594            s.select_anchors(selections);
10595            if let Some(pending_selection) = pending_selection {
10596                s.set_pending(pending_selection, SelectMode::Character);
10597            } else {
10598                s.clear_pending();
10599            }
10600        });
10601        self.selections_did_change(false, &old_cursor_position, true, cx);
10602    }
10603
10604    fn push_to_selection_history(&mut self) {
10605        self.selection_history.push(SelectionHistoryEntry {
10606            selections: self.selections.disjoint_anchors(),
10607            select_next_state: self.select_next_state.clone(),
10608            select_prev_state: self.select_prev_state.clone(),
10609            add_selections_state: self.add_selections_state.clone(),
10610        });
10611    }
10612
10613    pub fn transact(
10614        &mut self,
10615        cx: &mut ViewContext<Self>,
10616        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10617    ) -> Option<TransactionId> {
10618        self.start_transaction_at(Instant::now(), cx);
10619        update(self, cx);
10620        self.end_transaction_at(Instant::now(), cx)
10621    }
10622
10623    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10624        self.end_selection(cx);
10625        if let Some(tx_id) = self
10626            .buffer
10627            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10628        {
10629            self.selection_history
10630                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10631            cx.emit(EditorEvent::TransactionBegun {
10632                transaction_id: tx_id,
10633            })
10634        }
10635    }
10636
10637    fn end_transaction_at(
10638        &mut self,
10639        now: Instant,
10640        cx: &mut ViewContext<Self>,
10641    ) -> Option<TransactionId> {
10642        if let Some(transaction_id) = self
10643            .buffer
10644            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10645        {
10646            if let Some((_, end_selections)) =
10647                self.selection_history.transaction_mut(transaction_id)
10648            {
10649                *end_selections = Some(self.selections.disjoint_anchors());
10650            } else {
10651                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10652            }
10653
10654            cx.emit(EditorEvent::Edited { transaction_id });
10655            Some(transaction_id)
10656        } else {
10657            None
10658        }
10659    }
10660
10661    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10662        let selection = self.selections.newest::<Point>(cx);
10663
10664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10665        let range = if selection.is_empty() {
10666            let point = selection.head().to_display_point(&display_map);
10667            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10668            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10669                .to_point(&display_map);
10670            start..end
10671        } else {
10672            selection.range()
10673        };
10674        if display_map.folds_in_range(range).next().is_some() {
10675            self.unfold_lines(&Default::default(), cx)
10676        } else {
10677            self.fold(&Default::default(), cx)
10678        }
10679    }
10680
10681    pub fn toggle_fold_recursive(
10682        &mut self,
10683        _: &actions::ToggleFoldRecursive,
10684        cx: &mut ViewContext<Self>,
10685    ) {
10686        let selection = self.selections.newest::<Point>(cx);
10687
10688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10689        let range = if selection.is_empty() {
10690            let point = selection.head().to_display_point(&display_map);
10691            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10692            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10693                .to_point(&display_map);
10694            start..end
10695        } else {
10696            selection.range()
10697        };
10698        if display_map.folds_in_range(range).next().is_some() {
10699            self.unfold_recursive(&Default::default(), cx)
10700        } else {
10701            self.fold_recursive(&Default::default(), cx)
10702        }
10703    }
10704
10705    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10706        let mut fold_ranges = Vec::new();
10707        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10708        let selections = self.selections.all_adjusted(cx);
10709
10710        for selection in selections {
10711            let range = selection.range().sorted();
10712            let buffer_start_row = range.start.row;
10713
10714            if range.start.row != range.end.row {
10715                let mut found = false;
10716                let mut row = range.start.row;
10717                while row <= range.end.row {
10718                    if let Some((foldable_range, fold_text)) =
10719                        { display_map.foldable_range(MultiBufferRow(row)) }
10720                    {
10721                        found = true;
10722                        row = foldable_range.end.row + 1;
10723                        fold_ranges.push((foldable_range, fold_text));
10724                    } else {
10725                        row += 1
10726                    }
10727                }
10728                if found {
10729                    continue;
10730                }
10731            }
10732
10733            for row in (0..=range.start.row).rev() {
10734                if let Some((foldable_range, fold_text)) =
10735                    display_map.foldable_range(MultiBufferRow(row))
10736                {
10737                    if foldable_range.end.row >= buffer_start_row {
10738                        fold_ranges.push((foldable_range, fold_text));
10739                        if row <= range.start.row {
10740                            break;
10741                        }
10742                    }
10743                }
10744            }
10745        }
10746
10747        self.fold_ranges(fold_ranges, true, cx);
10748    }
10749
10750    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10751        let mut fold_ranges = Vec::new();
10752        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10753
10754        for row in 0..display_map.max_buffer_row().0 {
10755            if let Some((foldable_range, fold_text)) =
10756                display_map.foldable_range(MultiBufferRow(row))
10757            {
10758                fold_ranges.push((foldable_range, fold_text));
10759            }
10760        }
10761
10762        self.fold_ranges(fold_ranges, true, cx);
10763    }
10764
10765    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10766        let mut fold_ranges = Vec::new();
10767        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10768        let selections = self.selections.all_adjusted(cx);
10769
10770        for selection in selections {
10771            let range = selection.range().sorted();
10772            let buffer_start_row = range.start.row;
10773
10774            if range.start.row != range.end.row {
10775                let mut found = false;
10776                for row in range.start.row..=range.end.row {
10777                    if let Some((foldable_range, fold_text)) =
10778                        { display_map.foldable_range(MultiBufferRow(row)) }
10779                    {
10780                        found = true;
10781                        fold_ranges.push((foldable_range, fold_text));
10782                    }
10783                }
10784                if found {
10785                    continue;
10786                }
10787            }
10788
10789            for row in (0..=range.start.row).rev() {
10790                if let Some((foldable_range, fold_text)) =
10791                    display_map.foldable_range(MultiBufferRow(row))
10792                {
10793                    if foldable_range.end.row >= buffer_start_row {
10794                        fold_ranges.push((foldable_range, fold_text));
10795                    } else {
10796                        break;
10797                    }
10798                }
10799            }
10800        }
10801
10802        self.fold_ranges(fold_ranges, true, cx);
10803    }
10804
10805    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10806        let buffer_row = fold_at.buffer_row;
10807        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10808
10809        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10810            let autoscroll = self
10811                .selections
10812                .all::<Point>(cx)
10813                .iter()
10814                .any(|selection| fold_range.overlaps(&selection.range()));
10815
10816            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10817        }
10818    }
10819
10820    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10821        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10822        let buffer = &display_map.buffer_snapshot;
10823        let selections = self.selections.all::<Point>(cx);
10824        let ranges = selections
10825            .iter()
10826            .map(|s| {
10827                let range = s.display_range(&display_map).sorted();
10828                let mut start = range.start.to_point(&display_map);
10829                let mut end = range.end.to_point(&display_map);
10830                start.column = 0;
10831                end.column = buffer.line_len(MultiBufferRow(end.row));
10832                start..end
10833            })
10834            .collect::<Vec<_>>();
10835
10836        self.unfold_ranges(ranges, true, true, cx);
10837    }
10838
10839    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10840        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10841        let selections = self.selections.all::<Point>(cx);
10842        let ranges = selections
10843            .iter()
10844            .map(|s| {
10845                let mut range = s.display_range(&display_map).sorted();
10846                *range.start.column_mut() = 0;
10847                *range.end.column_mut() = display_map.line_len(range.end.row());
10848                let start = range.start.to_point(&display_map);
10849                let end = range.end.to_point(&display_map);
10850                start..end
10851            })
10852            .collect::<Vec<_>>();
10853
10854        self.unfold_ranges(ranges, true, true, cx);
10855    }
10856
10857    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10859
10860        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10861            ..Point::new(
10862                unfold_at.buffer_row.0,
10863                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10864            );
10865
10866        let autoscroll = self
10867            .selections
10868            .all::<Point>(cx)
10869            .iter()
10870            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10871
10872        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10873    }
10874
10875    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10876        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10877        self.unfold_ranges(
10878            [Point::zero()..display_map.max_point().to_point(&display_map)],
10879            true,
10880            true,
10881            cx,
10882        );
10883    }
10884
10885    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10886        let selections = self.selections.all::<Point>(cx);
10887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10888        let line_mode = self.selections.line_mode;
10889        let ranges = selections.into_iter().map(|s| {
10890            if line_mode {
10891                let start = Point::new(s.start.row, 0);
10892                let end = Point::new(
10893                    s.end.row,
10894                    display_map
10895                        .buffer_snapshot
10896                        .line_len(MultiBufferRow(s.end.row)),
10897                );
10898                (start..end, display_map.fold_placeholder.clone())
10899            } else {
10900                (s.start..s.end, display_map.fold_placeholder.clone())
10901            }
10902        });
10903        self.fold_ranges(ranges, true, cx);
10904    }
10905
10906    pub fn fold_ranges<T: ToOffset + Clone>(
10907        &mut self,
10908        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10909        auto_scroll: bool,
10910        cx: &mut ViewContext<Self>,
10911    ) {
10912        let mut fold_ranges = Vec::new();
10913        let mut buffers_affected = HashMap::default();
10914        let multi_buffer = self.buffer().read(cx);
10915        for (fold_range, fold_text) in ranges {
10916            if let Some((_, buffer, _)) =
10917                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10918            {
10919                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10920            };
10921            fold_ranges.push((fold_range, fold_text));
10922        }
10923
10924        let mut ranges = fold_ranges.into_iter().peekable();
10925        if ranges.peek().is_some() {
10926            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10927
10928            if auto_scroll {
10929                self.request_autoscroll(Autoscroll::fit(), cx);
10930            }
10931
10932            for buffer in buffers_affected.into_values() {
10933                self.sync_expanded_diff_hunks(buffer, cx);
10934            }
10935
10936            cx.notify();
10937
10938            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10939                // Clear diagnostics block when folding a range that contains it.
10940                let snapshot = self.snapshot(cx);
10941                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10942                    drop(snapshot);
10943                    self.active_diagnostics = Some(active_diagnostics);
10944                    self.dismiss_diagnostics(cx);
10945                } else {
10946                    self.active_diagnostics = Some(active_diagnostics);
10947                }
10948            }
10949
10950            self.scrollbar_marker_state.dirty = true;
10951        }
10952    }
10953
10954    pub fn unfold_ranges<T: ToOffset + Clone>(
10955        &mut self,
10956        ranges: impl IntoIterator<Item = Range<T>>,
10957        inclusive: bool,
10958        auto_scroll: bool,
10959        cx: &mut ViewContext<Self>,
10960    ) {
10961        let mut unfold_ranges = Vec::new();
10962        let mut buffers_affected = HashMap::default();
10963        let multi_buffer = self.buffer().read(cx);
10964        for range in ranges {
10965            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10966                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10967            };
10968            unfold_ranges.push(range);
10969        }
10970
10971        let mut ranges = unfold_ranges.into_iter().peekable();
10972        if ranges.peek().is_some() {
10973            self.display_map
10974                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10975            if auto_scroll {
10976                self.request_autoscroll(Autoscroll::fit(), cx);
10977            }
10978
10979            for buffer in buffers_affected.into_values() {
10980                self.sync_expanded_diff_hunks(buffer, cx);
10981            }
10982
10983            cx.notify();
10984            self.scrollbar_marker_state.dirty = true;
10985            self.active_indent_guides_state.dirty = true;
10986        }
10987    }
10988
10989    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10990        self.display_map.read(cx).fold_placeholder.clone()
10991    }
10992
10993    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10994        if hovered != self.gutter_hovered {
10995            self.gutter_hovered = hovered;
10996            cx.notify();
10997        }
10998    }
10999
11000    pub fn insert_blocks(
11001        &mut self,
11002        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11003        autoscroll: Option<Autoscroll>,
11004        cx: &mut ViewContext<Self>,
11005    ) -> Vec<CustomBlockId> {
11006        let blocks = self
11007            .display_map
11008            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11009        if let Some(autoscroll) = autoscroll {
11010            self.request_autoscroll(autoscroll, cx);
11011        }
11012        cx.notify();
11013        blocks
11014    }
11015
11016    pub fn resize_blocks(
11017        &mut self,
11018        heights: HashMap<CustomBlockId, u32>,
11019        autoscroll: Option<Autoscroll>,
11020        cx: &mut ViewContext<Self>,
11021    ) {
11022        self.display_map
11023            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11024        if let Some(autoscroll) = autoscroll {
11025            self.request_autoscroll(autoscroll, cx);
11026        }
11027        cx.notify();
11028    }
11029
11030    pub fn replace_blocks(
11031        &mut self,
11032        renderers: HashMap<CustomBlockId, RenderBlock>,
11033        autoscroll: Option<Autoscroll>,
11034        cx: &mut ViewContext<Self>,
11035    ) {
11036        self.display_map
11037            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11038        if let Some(autoscroll) = autoscroll {
11039            self.request_autoscroll(autoscroll, cx);
11040        }
11041        cx.notify();
11042    }
11043
11044    pub fn remove_blocks(
11045        &mut self,
11046        block_ids: HashSet<CustomBlockId>,
11047        autoscroll: Option<Autoscroll>,
11048        cx: &mut ViewContext<Self>,
11049    ) {
11050        self.display_map.update(cx, |display_map, cx| {
11051            display_map.remove_blocks(block_ids, cx)
11052        });
11053        if let Some(autoscroll) = autoscroll {
11054            self.request_autoscroll(autoscroll, cx);
11055        }
11056        cx.notify();
11057    }
11058
11059    pub fn row_for_block(
11060        &self,
11061        block_id: CustomBlockId,
11062        cx: &mut ViewContext<Self>,
11063    ) -> Option<DisplayRow> {
11064        self.display_map
11065            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11066    }
11067
11068    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11069        self.focused_block = Some(focused_block);
11070    }
11071
11072    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11073        self.focused_block.take()
11074    }
11075
11076    pub fn insert_creases(
11077        &mut self,
11078        creases: impl IntoIterator<Item = Crease>,
11079        cx: &mut ViewContext<Self>,
11080    ) -> Vec<CreaseId> {
11081        self.display_map
11082            .update(cx, |map, cx| map.insert_creases(creases, cx))
11083    }
11084
11085    pub fn remove_creases(
11086        &mut self,
11087        ids: impl IntoIterator<Item = CreaseId>,
11088        cx: &mut ViewContext<Self>,
11089    ) {
11090        self.display_map
11091            .update(cx, |map, cx| map.remove_creases(ids, cx));
11092    }
11093
11094    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11095        self.display_map
11096            .update(cx, |map, cx| map.snapshot(cx))
11097            .longest_row()
11098    }
11099
11100    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11101        self.display_map
11102            .update(cx, |map, cx| map.snapshot(cx))
11103            .max_point()
11104    }
11105
11106    pub fn text(&self, cx: &AppContext) -> String {
11107        self.buffer.read(cx).read(cx).text()
11108    }
11109
11110    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11111        let text = self.text(cx);
11112        let text = text.trim();
11113
11114        if text.is_empty() {
11115            return None;
11116        }
11117
11118        Some(text.to_string())
11119    }
11120
11121    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11122        self.transact(cx, |this, cx| {
11123            this.buffer
11124                .read(cx)
11125                .as_singleton()
11126                .expect("you can only call set_text on editors for singleton buffers")
11127                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11128        });
11129    }
11130
11131    pub fn display_text(&self, cx: &mut AppContext) -> String {
11132        self.display_map
11133            .update(cx, |map, cx| map.snapshot(cx))
11134            .text()
11135    }
11136
11137    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11138        let mut wrap_guides = smallvec::smallvec![];
11139
11140        if self.show_wrap_guides == Some(false) {
11141            return wrap_guides;
11142        }
11143
11144        let settings = self.buffer.read(cx).settings_at(0, cx);
11145        if settings.show_wrap_guides {
11146            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11147                wrap_guides.push((soft_wrap as usize, true));
11148            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11149                wrap_guides.push((soft_wrap as usize, true));
11150            }
11151            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11152        }
11153
11154        wrap_guides
11155    }
11156
11157    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11158        let settings = self.buffer.read(cx).settings_at(0, cx);
11159        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11160        match mode {
11161            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11162                SoftWrap::None
11163            }
11164            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11165            language_settings::SoftWrap::PreferredLineLength => {
11166                SoftWrap::Column(settings.preferred_line_length)
11167            }
11168            language_settings::SoftWrap::Bounded => {
11169                SoftWrap::Bounded(settings.preferred_line_length)
11170            }
11171        }
11172    }
11173
11174    pub fn set_soft_wrap_mode(
11175        &mut self,
11176        mode: language_settings::SoftWrap,
11177        cx: &mut ViewContext<Self>,
11178    ) {
11179        self.soft_wrap_mode_override = Some(mode);
11180        cx.notify();
11181    }
11182
11183    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11184        let rem_size = cx.rem_size();
11185        self.display_map.update(cx, |map, cx| {
11186            map.set_font(
11187                style.text.font(),
11188                style.text.font_size.to_pixels(rem_size),
11189                cx,
11190            )
11191        });
11192        self.style = Some(style);
11193    }
11194
11195    pub fn style(&self) -> Option<&EditorStyle> {
11196        self.style.as_ref()
11197    }
11198
11199    // Called by the element. This method is not designed to be called outside of the editor
11200    // element's layout code because it does not notify when rewrapping is computed synchronously.
11201    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11202        self.display_map
11203            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11204    }
11205
11206    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11207        if self.soft_wrap_mode_override.is_some() {
11208            self.soft_wrap_mode_override.take();
11209        } else {
11210            let soft_wrap = match self.soft_wrap_mode(cx) {
11211                SoftWrap::GitDiff => return,
11212                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11213                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11214                    language_settings::SoftWrap::None
11215                }
11216            };
11217            self.soft_wrap_mode_override = Some(soft_wrap);
11218        }
11219        cx.notify();
11220    }
11221
11222    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11223        let Some(workspace) = self.workspace() else {
11224            return;
11225        };
11226        let fs = workspace.read(cx).app_state().fs.clone();
11227        let current_show = TabBarSettings::get_global(cx).show;
11228        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11229            setting.show = Some(!current_show);
11230        });
11231    }
11232
11233    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11234        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11235            self.buffer
11236                .read(cx)
11237                .settings_at(0, cx)
11238                .indent_guides
11239                .enabled
11240        });
11241        self.show_indent_guides = Some(!currently_enabled);
11242        cx.notify();
11243    }
11244
11245    fn should_show_indent_guides(&self) -> Option<bool> {
11246        self.show_indent_guides
11247    }
11248
11249    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11250        let mut editor_settings = EditorSettings::get_global(cx).clone();
11251        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11252        EditorSettings::override_global(editor_settings, cx);
11253    }
11254
11255    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11256        self.use_relative_line_numbers
11257            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11258    }
11259
11260    pub fn toggle_relative_line_numbers(
11261        &mut self,
11262        _: &ToggleRelativeLineNumbers,
11263        cx: &mut ViewContext<Self>,
11264    ) {
11265        let is_relative = self.should_use_relative_line_numbers(cx);
11266        self.set_relative_line_number(Some(!is_relative), cx)
11267    }
11268
11269    pub fn set_relative_line_number(
11270        &mut self,
11271        is_relative: Option<bool>,
11272        cx: &mut ViewContext<Self>,
11273    ) {
11274        self.use_relative_line_numbers = is_relative;
11275        cx.notify();
11276    }
11277
11278    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11279        self.show_gutter = show_gutter;
11280        cx.notify();
11281    }
11282
11283    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11284        self.show_line_numbers = Some(show_line_numbers);
11285        cx.notify();
11286    }
11287
11288    pub fn set_show_git_diff_gutter(
11289        &mut self,
11290        show_git_diff_gutter: bool,
11291        cx: &mut ViewContext<Self>,
11292    ) {
11293        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11294        cx.notify();
11295    }
11296
11297    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11298        self.show_code_actions = Some(show_code_actions);
11299        cx.notify();
11300    }
11301
11302    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11303        self.show_runnables = Some(show_runnables);
11304        cx.notify();
11305    }
11306
11307    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11308        if self.display_map.read(cx).masked != masked {
11309            self.display_map.update(cx, |map, _| map.masked = masked);
11310        }
11311        cx.notify()
11312    }
11313
11314    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11315        self.show_wrap_guides = Some(show_wrap_guides);
11316        cx.notify();
11317    }
11318
11319    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11320        self.show_indent_guides = Some(show_indent_guides);
11321        cx.notify();
11322    }
11323
11324    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11325        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11326            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11327                if let Some(dir) = file.abs_path(cx).parent() {
11328                    return Some(dir.to_owned());
11329                }
11330            }
11331
11332            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11333                return Some(project_path.path.to_path_buf());
11334            }
11335        }
11336
11337        None
11338    }
11339
11340    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11341        self.active_excerpt(cx)?
11342            .1
11343            .read(cx)
11344            .file()
11345            .and_then(|f| f.as_local())
11346    }
11347
11348    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11349        if let Some(target) = self.target_file(cx) {
11350            cx.reveal_path(&target.abs_path(cx));
11351        }
11352    }
11353
11354    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11355        if let Some(file) = self.target_file(cx) {
11356            if let Some(path) = file.abs_path(cx).to_str() {
11357                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11358            }
11359        }
11360    }
11361
11362    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11363        if let Some(file) = self.target_file(cx) {
11364            if let Some(path) = file.path().to_str() {
11365                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11366            }
11367        }
11368    }
11369
11370    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11371        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11372
11373        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11374            self.start_git_blame(true, cx);
11375        }
11376
11377        cx.notify();
11378    }
11379
11380    pub fn toggle_git_blame_inline(
11381        &mut self,
11382        _: &ToggleGitBlameInline,
11383        cx: &mut ViewContext<Self>,
11384    ) {
11385        self.toggle_git_blame_inline_internal(true, cx);
11386        cx.notify();
11387    }
11388
11389    pub fn git_blame_inline_enabled(&self) -> bool {
11390        self.git_blame_inline_enabled
11391    }
11392
11393    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11394        self.show_selection_menu = self
11395            .show_selection_menu
11396            .map(|show_selections_menu| !show_selections_menu)
11397            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11398
11399        cx.notify();
11400    }
11401
11402    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11403        self.show_selection_menu
11404            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11405    }
11406
11407    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11408        if let Some(project) = self.project.as_ref() {
11409            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11410                return;
11411            };
11412
11413            if buffer.read(cx).file().is_none() {
11414                return;
11415            }
11416
11417            let focused = self.focus_handle(cx).contains_focused(cx);
11418
11419            let project = project.clone();
11420            let blame =
11421                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11422            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11423            self.blame = Some(blame);
11424        }
11425    }
11426
11427    fn toggle_git_blame_inline_internal(
11428        &mut self,
11429        user_triggered: bool,
11430        cx: &mut ViewContext<Self>,
11431    ) {
11432        if self.git_blame_inline_enabled {
11433            self.git_blame_inline_enabled = false;
11434            self.show_git_blame_inline = false;
11435            self.show_git_blame_inline_delay_task.take();
11436        } else {
11437            self.git_blame_inline_enabled = true;
11438            self.start_git_blame_inline(user_triggered, cx);
11439        }
11440
11441        cx.notify();
11442    }
11443
11444    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11445        self.start_git_blame(user_triggered, cx);
11446
11447        if ProjectSettings::get_global(cx)
11448            .git
11449            .inline_blame_delay()
11450            .is_some()
11451        {
11452            self.start_inline_blame_timer(cx);
11453        } else {
11454            self.show_git_blame_inline = true
11455        }
11456    }
11457
11458    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11459        self.blame.as_ref()
11460    }
11461
11462    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11463        self.show_git_blame_gutter && self.has_blame_entries(cx)
11464    }
11465
11466    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11467        self.show_git_blame_inline
11468            && self.focus_handle.is_focused(cx)
11469            && !self.newest_selection_head_on_empty_line(cx)
11470            && self.has_blame_entries(cx)
11471    }
11472
11473    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11474        self.blame()
11475            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11476    }
11477
11478    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11479        let cursor_anchor = self.selections.newest_anchor().head();
11480
11481        let snapshot = self.buffer.read(cx).snapshot(cx);
11482        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11483
11484        snapshot.line_len(buffer_row) == 0
11485    }
11486
11487    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11488        let buffer_and_selection = maybe!({
11489            let selection = self.selections.newest::<Point>(cx);
11490            let selection_range = selection.range();
11491
11492            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11493                (buffer, selection_range.start.row..selection_range.end.row)
11494            } else {
11495                let buffer_ranges = self
11496                    .buffer()
11497                    .read(cx)
11498                    .range_to_buffer_ranges(selection_range, cx);
11499
11500                let (buffer, range, _) = if selection.reversed {
11501                    buffer_ranges.first()
11502                } else {
11503                    buffer_ranges.last()
11504                }?;
11505
11506                let snapshot = buffer.read(cx).snapshot();
11507                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11508                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11509                (buffer.clone(), selection)
11510            };
11511
11512            Some((buffer, selection))
11513        });
11514
11515        let Some((buffer, selection)) = buffer_and_selection else {
11516            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11517        };
11518
11519        let Some(project) = self.project.as_ref() else {
11520            return Task::ready(Err(anyhow!("editor does not have project")));
11521        };
11522
11523        project.update(cx, |project, cx| {
11524            project.get_permalink_to_line(&buffer, selection, cx)
11525        })
11526    }
11527
11528    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11529        let permalink_task = self.get_permalink_to_line(cx);
11530        let workspace = self.workspace();
11531
11532        cx.spawn(|_, mut cx| async move {
11533            match permalink_task.await {
11534                Ok(permalink) => {
11535                    cx.update(|cx| {
11536                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11537                    })
11538                    .ok();
11539                }
11540                Err(err) => {
11541                    let message = format!("Failed to copy permalink: {err}");
11542
11543                    Err::<(), anyhow::Error>(err).log_err();
11544
11545                    if let Some(workspace) = workspace {
11546                        workspace
11547                            .update(&mut cx, |workspace, cx| {
11548                                struct CopyPermalinkToLine;
11549
11550                                workspace.show_toast(
11551                                    Toast::new(
11552                                        NotificationId::unique::<CopyPermalinkToLine>(),
11553                                        message,
11554                                    ),
11555                                    cx,
11556                                )
11557                            })
11558                            .ok();
11559                    }
11560                }
11561            }
11562        })
11563        .detach();
11564    }
11565
11566    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11567        if let Some(file) = self.target_file(cx) {
11568            if let Some(path) = file.path().to_str() {
11569                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11570                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11571            }
11572        }
11573    }
11574
11575    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11576        let permalink_task = self.get_permalink_to_line(cx);
11577        let workspace = self.workspace();
11578
11579        cx.spawn(|_, mut cx| async move {
11580            match permalink_task.await {
11581                Ok(permalink) => {
11582                    cx.update(|cx| {
11583                        cx.open_url(permalink.as_ref());
11584                    })
11585                    .ok();
11586                }
11587                Err(err) => {
11588                    let message = format!("Failed to open permalink: {err}");
11589
11590                    Err::<(), anyhow::Error>(err).log_err();
11591
11592                    if let Some(workspace) = workspace {
11593                        workspace
11594                            .update(&mut cx, |workspace, cx| {
11595                                struct OpenPermalinkToLine;
11596
11597                                workspace.show_toast(
11598                                    Toast::new(
11599                                        NotificationId::unique::<OpenPermalinkToLine>(),
11600                                        message,
11601                                    ),
11602                                    cx,
11603                                )
11604                            })
11605                            .ok();
11606                    }
11607                }
11608            }
11609        })
11610        .detach();
11611    }
11612
11613    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11614    /// last highlight added will be used.
11615    ///
11616    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11617    pub fn highlight_rows<T: 'static>(
11618        &mut self,
11619        range: Range<Anchor>,
11620        color: Hsla,
11621        should_autoscroll: bool,
11622        cx: &mut ViewContext<Self>,
11623    ) {
11624        let snapshot = self.buffer().read(cx).snapshot(cx);
11625        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11626        let ix = row_highlights.binary_search_by(|highlight| {
11627            Ordering::Equal
11628                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11629                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11630        });
11631
11632        if let Err(mut ix) = ix {
11633            let index = post_inc(&mut self.highlight_order);
11634
11635            // If this range intersects with the preceding highlight, then merge it with
11636            // the preceding highlight. Otherwise insert a new highlight.
11637            let mut merged = false;
11638            if ix > 0 {
11639                let prev_highlight = &mut row_highlights[ix - 1];
11640                if prev_highlight
11641                    .range
11642                    .end
11643                    .cmp(&range.start, &snapshot)
11644                    .is_ge()
11645                {
11646                    ix -= 1;
11647                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11648                        prev_highlight.range.end = range.end;
11649                    }
11650                    merged = true;
11651                    prev_highlight.index = index;
11652                    prev_highlight.color = color;
11653                    prev_highlight.should_autoscroll = should_autoscroll;
11654                }
11655            }
11656
11657            if !merged {
11658                row_highlights.insert(
11659                    ix,
11660                    RowHighlight {
11661                        range: range.clone(),
11662                        index,
11663                        color,
11664                        should_autoscroll,
11665                    },
11666                );
11667            }
11668
11669            // If any of the following highlights intersect with this one, merge them.
11670            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11671                let highlight = &row_highlights[ix];
11672                if next_highlight
11673                    .range
11674                    .start
11675                    .cmp(&highlight.range.end, &snapshot)
11676                    .is_le()
11677                {
11678                    if next_highlight
11679                        .range
11680                        .end
11681                        .cmp(&highlight.range.end, &snapshot)
11682                        .is_gt()
11683                    {
11684                        row_highlights[ix].range.end = next_highlight.range.end;
11685                    }
11686                    row_highlights.remove(ix + 1);
11687                } else {
11688                    break;
11689                }
11690            }
11691        }
11692    }
11693
11694    /// Remove any highlighted row ranges of the given type that intersect the
11695    /// given ranges.
11696    pub fn remove_highlighted_rows<T: 'static>(
11697        &mut self,
11698        ranges_to_remove: Vec<Range<Anchor>>,
11699        cx: &mut ViewContext<Self>,
11700    ) {
11701        let snapshot = self.buffer().read(cx).snapshot(cx);
11702        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11703        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11704        row_highlights.retain(|highlight| {
11705            while let Some(range_to_remove) = ranges_to_remove.peek() {
11706                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11707                    Ordering::Less | Ordering::Equal => {
11708                        ranges_to_remove.next();
11709                    }
11710                    Ordering::Greater => {
11711                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11712                            Ordering::Less | Ordering::Equal => {
11713                                return false;
11714                            }
11715                            Ordering::Greater => break,
11716                        }
11717                    }
11718                }
11719            }
11720
11721            true
11722        })
11723    }
11724
11725    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11726    pub fn clear_row_highlights<T: 'static>(&mut self) {
11727        self.highlighted_rows.remove(&TypeId::of::<T>());
11728    }
11729
11730    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11731    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11732        self.highlighted_rows
11733            .get(&TypeId::of::<T>())
11734            .map_or(&[] as &[_], |vec| vec.as_slice())
11735            .iter()
11736            .map(|highlight| (highlight.range.clone(), highlight.color))
11737    }
11738
11739    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11740    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11741    /// Allows to ignore certain kinds of highlights.
11742    pub fn highlighted_display_rows(
11743        &mut self,
11744        cx: &mut WindowContext,
11745    ) -> BTreeMap<DisplayRow, Hsla> {
11746        let snapshot = self.snapshot(cx);
11747        let mut used_highlight_orders = HashMap::default();
11748        self.highlighted_rows
11749            .iter()
11750            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11751            .fold(
11752                BTreeMap::<DisplayRow, Hsla>::new(),
11753                |mut unique_rows, highlight| {
11754                    let start = highlight.range.start.to_display_point(&snapshot);
11755                    let end = highlight.range.end.to_display_point(&snapshot);
11756                    let start_row = start.row().0;
11757                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11758                        && end.column() == 0
11759                    {
11760                        end.row().0.saturating_sub(1)
11761                    } else {
11762                        end.row().0
11763                    };
11764                    for row in start_row..=end_row {
11765                        let used_index =
11766                            used_highlight_orders.entry(row).or_insert(highlight.index);
11767                        if highlight.index >= *used_index {
11768                            *used_index = highlight.index;
11769                            unique_rows.insert(DisplayRow(row), highlight.color);
11770                        }
11771                    }
11772                    unique_rows
11773                },
11774            )
11775    }
11776
11777    pub fn highlighted_display_row_for_autoscroll(
11778        &self,
11779        snapshot: &DisplaySnapshot,
11780    ) -> Option<DisplayRow> {
11781        self.highlighted_rows
11782            .values()
11783            .flat_map(|highlighted_rows| highlighted_rows.iter())
11784            .filter_map(|highlight| {
11785                if highlight.should_autoscroll {
11786                    Some(highlight.range.start.to_display_point(snapshot).row())
11787                } else {
11788                    None
11789                }
11790            })
11791            .min()
11792    }
11793
11794    pub fn set_search_within_ranges(
11795        &mut self,
11796        ranges: &[Range<Anchor>],
11797        cx: &mut ViewContext<Self>,
11798    ) {
11799        self.highlight_background::<SearchWithinRange>(
11800            ranges,
11801            |colors| colors.editor_document_highlight_read_background,
11802            cx,
11803        )
11804    }
11805
11806    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11807        self.breadcrumb_header = Some(new_header);
11808    }
11809
11810    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11811        self.clear_background_highlights::<SearchWithinRange>(cx);
11812    }
11813
11814    pub fn highlight_background<T: 'static>(
11815        &mut self,
11816        ranges: &[Range<Anchor>],
11817        color_fetcher: fn(&ThemeColors) -> Hsla,
11818        cx: &mut ViewContext<Self>,
11819    ) {
11820        self.background_highlights
11821            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11822        self.scrollbar_marker_state.dirty = true;
11823        cx.notify();
11824    }
11825
11826    pub fn clear_background_highlights<T: 'static>(
11827        &mut self,
11828        cx: &mut ViewContext<Self>,
11829    ) -> Option<BackgroundHighlight> {
11830        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11831        if !text_highlights.1.is_empty() {
11832            self.scrollbar_marker_state.dirty = true;
11833            cx.notify();
11834        }
11835        Some(text_highlights)
11836    }
11837
11838    pub fn highlight_gutter<T: 'static>(
11839        &mut self,
11840        ranges: &[Range<Anchor>],
11841        color_fetcher: fn(&AppContext) -> Hsla,
11842        cx: &mut ViewContext<Self>,
11843    ) {
11844        self.gutter_highlights
11845            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11846        cx.notify();
11847    }
11848
11849    pub fn clear_gutter_highlights<T: 'static>(
11850        &mut self,
11851        cx: &mut ViewContext<Self>,
11852    ) -> Option<GutterHighlight> {
11853        cx.notify();
11854        self.gutter_highlights.remove(&TypeId::of::<T>())
11855    }
11856
11857    #[cfg(feature = "test-support")]
11858    pub fn all_text_background_highlights(
11859        &mut self,
11860        cx: &mut ViewContext<Self>,
11861    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11862        let snapshot = self.snapshot(cx);
11863        let buffer = &snapshot.buffer_snapshot;
11864        let start = buffer.anchor_before(0);
11865        let end = buffer.anchor_after(buffer.len());
11866        let theme = cx.theme().colors();
11867        self.background_highlights_in_range(start..end, &snapshot, theme)
11868    }
11869
11870    #[cfg(feature = "test-support")]
11871    pub fn search_background_highlights(
11872        &mut self,
11873        cx: &mut ViewContext<Self>,
11874    ) -> Vec<Range<Point>> {
11875        let snapshot = self.buffer().read(cx).snapshot(cx);
11876
11877        let highlights = self
11878            .background_highlights
11879            .get(&TypeId::of::<items::BufferSearchHighlights>());
11880
11881        if let Some((_color, ranges)) = highlights {
11882            ranges
11883                .iter()
11884                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11885                .collect_vec()
11886        } else {
11887            vec![]
11888        }
11889    }
11890
11891    fn document_highlights_for_position<'a>(
11892        &'a self,
11893        position: Anchor,
11894        buffer: &'a MultiBufferSnapshot,
11895    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11896        let read_highlights = self
11897            .background_highlights
11898            .get(&TypeId::of::<DocumentHighlightRead>())
11899            .map(|h| &h.1);
11900        let write_highlights = self
11901            .background_highlights
11902            .get(&TypeId::of::<DocumentHighlightWrite>())
11903            .map(|h| &h.1);
11904        let left_position = position.bias_left(buffer);
11905        let right_position = position.bias_right(buffer);
11906        read_highlights
11907            .into_iter()
11908            .chain(write_highlights)
11909            .flat_map(move |ranges| {
11910                let start_ix = match ranges.binary_search_by(|probe| {
11911                    let cmp = probe.end.cmp(&left_position, buffer);
11912                    if cmp.is_ge() {
11913                        Ordering::Greater
11914                    } else {
11915                        Ordering::Less
11916                    }
11917                }) {
11918                    Ok(i) | Err(i) => i,
11919                };
11920
11921                ranges[start_ix..]
11922                    .iter()
11923                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11924            })
11925    }
11926
11927    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11928        self.background_highlights
11929            .get(&TypeId::of::<T>())
11930            .map_or(false, |(_, highlights)| !highlights.is_empty())
11931    }
11932
11933    pub fn background_highlights_in_range(
11934        &self,
11935        search_range: Range<Anchor>,
11936        display_snapshot: &DisplaySnapshot,
11937        theme: &ThemeColors,
11938    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11939        let mut results = Vec::new();
11940        for (color_fetcher, ranges) in self.background_highlights.values() {
11941            let color = color_fetcher(theme);
11942            let start_ix = match ranges.binary_search_by(|probe| {
11943                let cmp = probe
11944                    .end
11945                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11946                if cmp.is_gt() {
11947                    Ordering::Greater
11948                } else {
11949                    Ordering::Less
11950                }
11951            }) {
11952                Ok(i) | Err(i) => i,
11953            };
11954            for range in &ranges[start_ix..] {
11955                if range
11956                    .start
11957                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11958                    .is_ge()
11959                {
11960                    break;
11961                }
11962
11963                let start = range.start.to_display_point(display_snapshot);
11964                let end = range.end.to_display_point(display_snapshot);
11965                results.push((start..end, color))
11966            }
11967        }
11968        results
11969    }
11970
11971    pub fn background_highlight_row_ranges<T: 'static>(
11972        &self,
11973        search_range: Range<Anchor>,
11974        display_snapshot: &DisplaySnapshot,
11975        count: usize,
11976    ) -> Vec<RangeInclusive<DisplayPoint>> {
11977        let mut results = Vec::new();
11978        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11979            return vec![];
11980        };
11981
11982        let start_ix = match ranges.binary_search_by(|probe| {
11983            let cmp = probe
11984                .end
11985                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11986            if cmp.is_gt() {
11987                Ordering::Greater
11988            } else {
11989                Ordering::Less
11990            }
11991        }) {
11992            Ok(i) | Err(i) => i,
11993        };
11994        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11995            if let (Some(start_display), Some(end_display)) = (start, end) {
11996                results.push(
11997                    start_display.to_display_point(display_snapshot)
11998                        ..=end_display.to_display_point(display_snapshot),
11999                );
12000            }
12001        };
12002        let mut start_row: Option<Point> = None;
12003        let mut end_row: Option<Point> = None;
12004        if ranges.len() > count {
12005            return Vec::new();
12006        }
12007        for range in &ranges[start_ix..] {
12008            if range
12009                .start
12010                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12011                .is_ge()
12012            {
12013                break;
12014            }
12015            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12016            if let Some(current_row) = &end_row {
12017                if end.row == current_row.row {
12018                    continue;
12019                }
12020            }
12021            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12022            if start_row.is_none() {
12023                assert_eq!(end_row, None);
12024                start_row = Some(start);
12025                end_row = Some(end);
12026                continue;
12027            }
12028            if let Some(current_end) = end_row.as_mut() {
12029                if start.row > current_end.row + 1 {
12030                    push_region(start_row, end_row);
12031                    start_row = Some(start);
12032                    end_row = Some(end);
12033                } else {
12034                    // Merge two hunks.
12035                    *current_end = end;
12036                }
12037            } else {
12038                unreachable!();
12039            }
12040        }
12041        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12042        push_region(start_row, end_row);
12043        results
12044    }
12045
12046    pub fn gutter_highlights_in_range(
12047        &self,
12048        search_range: Range<Anchor>,
12049        display_snapshot: &DisplaySnapshot,
12050        cx: &AppContext,
12051    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12052        let mut results = Vec::new();
12053        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12054            let color = color_fetcher(cx);
12055            let start_ix = match ranges.binary_search_by(|probe| {
12056                let cmp = probe
12057                    .end
12058                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12059                if cmp.is_gt() {
12060                    Ordering::Greater
12061                } else {
12062                    Ordering::Less
12063                }
12064            }) {
12065                Ok(i) | Err(i) => i,
12066            };
12067            for range in &ranges[start_ix..] {
12068                if range
12069                    .start
12070                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12071                    .is_ge()
12072                {
12073                    break;
12074                }
12075
12076                let start = range.start.to_display_point(display_snapshot);
12077                let end = range.end.to_display_point(display_snapshot);
12078                results.push((start..end, color))
12079            }
12080        }
12081        results
12082    }
12083
12084    /// Get the text ranges corresponding to the redaction query
12085    pub fn redacted_ranges(
12086        &self,
12087        search_range: Range<Anchor>,
12088        display_snapshot: &DisplaySnapshot,
12089        cx: &WindowContext,
12090    ) -> Vec<Range<DisplayPoint>> {
12091        display_snapshot
12092            .buffer_snapshot
12093            .redacted_ranges(search_range, |file| {
12094                if let Some(file) = file {
12095                    file.is_private()
12096                        && EditorSettings::get(
12097                            Some(SettingsLocation {
12098                                worktree_id: file.worktree_id(cx),
12099                                path: file.path().as_ref(),
12100                            }),
12101                            cx,
12102                        )
12103                        .redact_private_values
12104                } else {
12105                    false
12106                }
12107            })
12108            .map(|range| {
12109                range.start.to_display_point(display_snapshot)
12110                    ..range.end.to_display_point(display_snapshot)
12111            })
12112            .collect()
12113    }
12114
12115    pub fn highlight_text<T: 'static>(
12116        &mut self,
12117        ranges: Vec<Range<Anchor>>,
12118        style: HighlightStyle,
12119        cx: &mut ViewContext<Self>,
12120    ) {
12121        self.display_map.update(cx, |map, _| {
12122            map.highlight_text(TypeId::of::<T>(), ranges, style)
12123        });
12124        cx.notify();
12125    }
12126
12127    pub(crate) fn highlight_inlays<T: 'static>(
12128        &mut self,
12129        highlights: Vec<InlayHighlight>,
12130        style: HighlightStyle,
12131        cx: &mut ViewContext<Self>,
12132    ) {
12133        self.display_map.update(cx, |map, _| {
12134            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12135        });
12136        cx.notify();
12137    }
12138
12139    pub fn text_highlights<'a, T: 'static>(
12140        &'a self,
12141        cx: &'a AppContext,
12142    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12143        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12144    }
12145
12146    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12147        let cleared = self
12148            .display_map
12149            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12150        if cleared {
12151            cx.notify();
12152        }
12153    }
12154
12155    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12156        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12157            && self.focus_handle.is_focused(cx)
12158    }
12159
12160    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12161        self.show_cursor_when_unfocused = is_enabled;
12162        cx.notify();
12163    }
12164
12165    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12166        cx.notify();
12167    }
12168
12169    fn on_buffer_event(
12170        &mut self,
12171        multibuffer: Model<MultiBuffer>,
12172        event: &multi_buffer::Event,
12173        cx: &mut ViewContext<Self>,
12174    ) {
12175        match event {
12176            multi_buffer::Event::Edited {
12177                singleton_buffer_edited,
12178            } => {
12179                self.scrollbar_marker_state.dirty = true;
12180                self.active_indent_guides_state.dirty = true;
12181                self.refresh_active_diagnostics(cx);
12182                self.refresh_code_actions(cx);
12183                if self.has_active_inline_completion(cx) {
12184                    self.update_visible_inline_completion(cx);
12185                }
12186                cx.emit(EditorEvent::BufferEdited);
12187                cx.emit(SearchEvent::MatchesInvalidated);
12188                if *singleton_buffer_edited {
12189                    if let Some(project) = &self.project {
12190                        let project = project.read(cx);
12191                        #[allow(clippy::mutable_key_type)]
12192                        let languages_affected = multibuffer
12193                            .read(cx)
12194                            .all_buffers()
12195                            .into_iter()
12196                            .filter_map(|buffer| {
12197                                let buffer = buffer.read(cx);
12198                                let language = buffer.language()?;
12199                                if project.is_local()
12200                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12201                                {
12202                                    None
12203                                } else {
12204                                    Some(language)
12205                                }
12206                            })
12207                            .cloned()
12208                            .collect::<HashSet<_>>();
12209                        if !languages_affected.is_empty() {
12210                            self.refresh_inlay_hints(
12211                                InlayHintRefreshReason::BufferEdited(languages_affected),
12212                                cx,
12213                            );
12214                        }
12215                    }
12216                }
12217
12218                let Some(project) = &self.project else { return };
12219                let (telemetry, is_via_ssh) = {
12220                    let project = project.read(cx);
12221                    let telemetry = project.client().telemetry().clone();
12222                    let is_via_ssh = project.is_via_ssh();
12223                    (telemetry, is_via_ssh)
12224                };
12225                refresh_linked_ranges(self, cx);
12226                telemetry.log_edit_event("editor", is_via_ssh);
12227            }
12228            multi_buffer::Event::ExcerptsAdded {
12229                buffer,
12230                predecessor,
12231                excerpts,
12232            } => {
12233                self.tasks_update_task = Some(self.refresh_runnables(cx));
12234                cx.emit(EditorEvent::ExcerptsAdded {
12235                    buffer: buffer.clone(),
12236                    predecessor: *predecessor,
12237                    excerpts: excerpts.clone(),
12238                });
12239                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12240            }
12241            multi_buffer::Event::ExcerptsRemoved { ids } => {
12242                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12243                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12244            }
12245            multi_buffer::Event::ExcerptsEdited { ids } => {
12246                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12247            }
12248            multi_buffer::Event::ExcerptsExpanded { ids } => {
12249                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12250            }
12251            multi_buffer::Event::Reparsed(buffer_id) => {
12252                self.tasks_update_task = Some(self.refresh_runnables(cx));
12253
12254                cx.emit(EditorEvent::Reparsed(*buffer_id));
12255            }
12256            multi_buffer::Event::LanguageChanged(buffer_id) => {
12257                linked_editing_ranges::refresh_linked_ranges(self, cx);
12258                cx.emit(EditorEvent::Reparsed(*buffer_id));
12259                cx.notify();
12260            }
12261            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12262            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12263            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12264                cx.emit(EditorEvent::TitleChanged)
12265            }
12266            multi_buffer::Event::DiffBaseChanged => {
12267                self.scrollbar_marker_state.dirty = true;
12268                cx.emit(EditorEvent::DiffBaseChanged);
12269                cx.notify();
12270            }
12271            multi_buffer::Event::DiffUpdated { buffer } => {
12272                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12273                cx.notify();
12274            }
12275            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12276            multi_buffer::Event::DiagnosticsUpdated => {
12277                self.refresh_active_diagnostics(cx);
12278                self.scrollbar_marker_state.dirty = true;
12279                cx.notify();
12280            }
12281            _ => {}
12282        };
12283    }
12284
12285    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12286        cx.notify();
12287    }
12288
12289    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12290        self.tasks_update_task = Some(self.refresh_runnables(cx));
12291        self.refresh_inline_completion(true, false, cx);
12292        self.refresh_inlay_hints(
12293            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12294                self.selections.newest_anchor().head(),
12295                &self.buffer.read(cx).snapshot(cx),
12296                cx,
12297            )),
12298            cx,
12299        );
12300
12301        let old_cursor_shape = self.cursor_shape;
12302
12303        {
12304            let editor_settings = EditorSettings::get_global(cx);
12305            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12306            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12307            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12308        }
12309
12310        if old_cursor_shape != self.cursor_shape {
12311            cx.emit(EditorEvent::CursorShapeChanged);
12312        }
12313
12314        let project_settings = ProjectSettings::get_global(cx);
12315        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12316
12317        if self.mode == EditorMode::Full {
12318            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12319            if self.git_blame_inline_enabled != inline_blame_enabled {
12320                self.toggle_git_blame_inline_internal(false, cx);
12321            }
12322        }
12323
12324        cx.notify();
12325    }
12326
12327    pub fn set_searchable(&mut self, searchable: bool) {
12328        self.searchable = searchable;
12329    }
12330
12331    pub fn searchable(&self) -> bool {
12332        self.searchable
12333    }
12334
12335    fn open_proposed_changes_editor(
12336        &mut self,
12337        _: &OpenProposedChangesEditor,
12338        cx: &mut ViewContext<Self>,
12339    ) {
12340        let Some(workspace) = self.workspace() else {
12341            cx.propagate();
12342            return;
12343        };
12344
12345        let buffer = self.buffer.read(cx);
12346        let mut new_selections_by_buffer = HashMap::default();
12347        for selection in self.selections.all::<usize>(cx) {
12348            for (buffer, range, _) in
12349                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12350            {
12351                let mut range = range.to_point(buffer.read(cx));
12352                range.start.column = 0;
12353                range.end.column = buffer.read(cx).line_len(range.end.row);
12354                new_selections_by_buffer
12355                    .entry(buffer)
12356                    .or_insert(Vec::new())
12357                    .push(range)
12358            }
12359        }
12360
12361        let proposed_changes_buffers = new_selections_by_buffer
12362            .into_iter()
12363            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12364            .collect::<Vec<_>>();
12365        let proposed_changes_editor = cx.new_view(|cx| {
12366            ProposedChangesEditor::new(
12367                "Proposed changes",
12368                proposed_changes_buffers,
12369                self.project.clone(),
12370                cx,
12371            )
12372        });
12373
12374        cx.window_context().defer(move |cx| {
12375            workspace.update(cx, |workspace, cx| {
12376                workspace.active_pane().update(cx, |pane, cx| {
12377                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12378                });
12379            });
12380        });
12381    }
12382
12383    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12384        self.open_excerpts_common(true, cx)
12385    }
12386
12387    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12388        self.open_excerpts_common(false, cx)
12389    }
12390
12391    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12392        let buffer = self.buffer.read(cx);
12393        if buffer.is_singleton() {
12394            cx.propagate();
12395            return;
12396        }
12397
12398        let Some(workspace) = self.workspace() else {
12399            cx.propagate();
12400            return;
12401        };
12402
12403        let mut new_selections_by_buffer = HashMap::default();
12404        for selection in self.selections.all::<usize>(cx) {
12405            for (mut buffer_handle, mut range, _) in
12406                buffer.range_to_buffer_ranges(selection.range(), cx)
12407            {
12408                // When editing branch buffers, jump to the corresponding location
12409                // in their base buffer.
12410                let buffer = buffer_handle.read(cx);
12411                if let Some(base_buffer) = buffer.diff_base_buffer() {
12412                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12413                    buffer_handle = base_buffer;
12414                }
12415
12416                if selection.reversed {
12417                    mem::swap(&mut range.start, &mut range.end);
12418                }
12419                new_selections_by_buffer
12420                    .entry(buffer_handle)
12421                    .or_insert(Vec::new())
12422                    .push(range)
12423            }
12424        }
12425
12426        // We defer the pane interaction because we ourselves are a workspace item
12427        // and activating a new item causes the pane to call a method on us reentrantly,
12428        // which panics if we're on the stack.
12429        cx.window_context().defer(move |cx| {
12430            workspace.update(cx, |workspace, cx| {
12431                let pane = if split {
12432                    workspace.adjacent_pane(cx)
12433                } else {
12434                    workspace.active_pane().clone()
12435                };
12436
12437                for (buffer, ranges) in new_selections_by_buffer {
12438                    let editor =
12439                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12440                    editor.update(cx, |editor, cx| {
12441                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12442                            s.select_ranges(ranges);
12443                        });
12444                    });
12445                }
12446            })
12447        });
12448    }
12449
12450    fn jump(
12451        &mut self,
12452        path: ProjectPath,
12453        position: Point,
12454        anchor: language::Anchor,
12455        offset_from_top: u32,
12456        cx: &mut ViewContext<Self>,
12457    ) {
12458        let workspace = self.workspace();
12459        cx.spawn(|_, mut cx| async move {
12460            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12461            let editor = workspace.update(&mut cx, |workspace, cx| {
12462                // Reset the preview item id before opening the new item
12463                workspace.active_pane().update(cx, |pane, cx| {
12464                    pane.set_preview_item_id(None, cx);
12465                });
12466                workspace.open_path_preview(path, None, true, true, cx)
12467            })?;
12468            let editor = editor
12469                .await?
12470                .downcast::<Editor>()
12471                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12472                .downgrade();
12473            editor.update(&mut cx, |editor, cx| {
12474                let buffer = editor
12475                    .buffer()
12476                    .read(cx)
12477                    .as_singleton()
12478                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12479                let buffer = buffer.read(cx);
12480                let cursor = if buffer.can_resolve(&anchor) {
12481                    language::ToPoint::to_point(&anchor, buffer)
12482                } else {
12483                    buffer.clip_point(position, Bias::Left)
12484                };
12485
12486                let nav_history = editor.nav_history.take();
12487                editor.change_selections(
12488                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12489                    cx,
12490                    |s| {
12491                        s.select_ranges([cursor..cursor]);
12492                    },
12493                );
12494                editor.nav_history = nav_history;
12495
12496                anyhow::Ok(())
12497            })??;
12498
12499            anyhow::Ok(())
12500        })
12501        .detach_and_log_err(cx);
12502    }
12503
12504    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12505        let snapshot = self.buffer.read(cx).read(cx);
12506        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12507        Some(
12508            ranges
12509                .iter()
12510                .map(move |range| {
12511                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12512                })
12513                .collect(),
12514        )
12515    }
12516
12517    fn selection_replacement_ranges(
12518        &self,
12519        range: Range<OffsetUtf16>,
12520        cx: &AppContext,
12521    ) -> Vec<Range<OffsetUtf16>> {
12522        let selections = self.selections.all::<OffsetUtf16>(cx);
12523        let newest_selection = selections
12524            .iter()
12525            .max_by_key(|selection| selection.id)
12526            .unwrap();
12527        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12528        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12529        let snapshot = self.buffer.read(cx).read(cx);
12530        selections
12531            .into_iter()
12532            .map(|mut selection| {
12533                selection.start.0 =
12534                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12535                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12536                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12537                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12538            })
12539            .collect()
12540    }
12541
12542    fn report_editor_event(
12543        &self,
12544        operation: &'static str,
12545        file_extension: Option<String>,
12546        cx: &AppContext,
12547    ) {
12548        if cfg!(any(test, feature = "test-support")) {
12549            return;
12550        }
12551
12552        let Some(project) = &self.project else { return };
12553
12554        // If None, we are in a file without an extension
12555        let file = self
12556            .buffer
12557            .read(cx)
12558            .as_singleton()
12559            .and_then(|b| b.read(cx).file());
12560        let file_extension = file_extension.or(file
12561            .as_ref()
12562            .and_then(|file| Path::new(file.file_name(cx)).extension())
12563            .and_then(|e| e.to_str())
12564            .map(|a| a.to_string()));
12565
12566        let vim_mode = cx
12567            .global::<SettingsStore>()
12568            .raw_user_settings()
12569            .get("vim_mode")
12570            == Some(&serde_json::Value::Bool(true));
12571
12572        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12573            == language::language_settings::InlineCompletionProvider::Copilot;
12574        let copilot_enabled_for_language = self
12575            .buffer
12576            .read(cx)
12577            .settings_at(0, cx)
12578            .show_inline_completions;
12579
12580        let project = project.read(cx);
12581        let telemetry = project.client().telemetry().clone();
12582        telemetry.report_editor_event(
12583            file_extension,
12584            vim_mode,
12585            operation,
12586            copilot_enabled,
12587            copilot_enabled_for_language,
12588            project.is_via_ssh(),
12589        )
12590    }
12591
12592    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12593    /// with each line being an array of {text, highlight} objects.
12594    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12595        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12596            return;
12597        };
12598
12599        #[derive(Serialize)]
12600        struct Chunk<'a> {
12601            text: String,
12602            highlight: Option<&'a str>,
12603        }
12604
12605        let snapshot = buffer.read(cx).snapshot();
12606        let range = self
12607            .selected_text_range(false, cx)
12608            .and_then(|selection| {
12609                if selection.range.is_empty() {
12610                    None
12611                } else {
12612                    Some(selection.range)
12613                }
12614            })
12615            .unwrap_or_else(|| 0..snapshot.len());
12616
12617        let chunks = snapshot.chunks(range, true);
12618        let mut lines = Vec::new();
12619        let mut line: VecDeque<Chunk> = VecDeque::new();
12620
12621        let Some(style) = self.style.as_ref() else {
12622            return;
12623        };
12624
12625        for chunk in chunks {
12626            let highlight = chunk
12627                .syntax_highlight_id
12628                .and_then(|id| id.name(&style.syntax));
12629            let mut chunk_lines = chunk.text.split('\n').peekable();
12630            while let Some(text) = chunk_lines.next() {
12631                let mut merged_with_last_token = false;
12632                if let Some(last_token) = line.back_mut() {
12633                    if last_token.highlight == highlight {
12634                        last_token.text.push_str(text);
12635                        merged_with_last_token = true;
12636                    }
12637                }
12638
12639                if !merged_with_last_token {
12640                    line.push_back(Chunk {
12641                        text: text.into(),
12642                        highlight,
12643                    });
12644                }
12645
12646                if chunk_lines.peek().is_some() {
12647                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12648                        line.pop_front();
12649                    }
12650                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12651                        line.pop_back();
12652                    }
12653
12654                    lines.push(mem::take(&mut line));
12655                }
12656            }
12657        }
12658
12659        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12660            return;
12661        };
12662        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12663    }
12664
12665    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12666        &self.inlay_hint_cache
12667    }
12668
12669    pub fn replay_insert_event(
12670        &mut self,
12671        text: &str,
12672        relative_utf16_range: Option<Range<isize>>,
12673        cx: &mut ViewContext<Self>,
12674    ) {
12675        if !self.input_enabled {
12676            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12677            return;
12678        }
12679        if let Some(relative_utf16_range) = relative_utf16_range {
12680            let selections = self.selections.all::<OffsetUtf16>(cx);
12681            self.change_selections(None, cx, |s| {
12682                let new_ranges = selections.into_iter().map(|range| {
12683                    let start = OffsetUtf16(
12684                        range
12685                            .head()
12686                            .0
12687                            .saturating_add_signed(relative_utf16_range.start),
12688                    );
12689                    let end = OffsetUtf16(
12690                        range
12691                            .head()
12692                            .0
12693                            .saturating_add_signed(relative_utf16_range.end),
12694                    );
12695                    start..end
12696                });
12697                s.select_ranges(new_ranges);
12698            });
12699        }
12700
12701        self.handle_input(text, cx);
12702    }
12703
12704    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12705        let Some(provider) = self.semantics_provider.as_ref() else {
12706            return false;
12707        };
12708
12709        let mut supports = false;
12710        self.buffer().read(cx).for_each_buffer(|buffer| {
12711            supports |= provider.supports_inlay_hints(buffer, cx);
12712        });
12713        supports
12714    }
12715
12716    pub fn focus(&self, cx: &mut WindowContext) {
12717        cx.focus(&self.focus_handle)
12718    }
12719
12720    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12721        self.focus_handle.is_focused(cx)
12722    }
12723
12724    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12725        cx.emit(EditorEvent::Focused);
12726
12727        if let Some(descendant) = self
12728            .last_focused_descendant
12729            .take()
12730            .and_then(|descendant| descendant.upgrade())
12731        {
12732            cx.focus(&descendant);
12733        } else {
12734            if let Some(blame) = self.blame.as_ref() {
12735                blame.update(cx, GitBlame::focus)
12736            }
12737
12738            self.blink_manager.update(cx, BlinkManager::enable);
12739            self.show_cursor_names(cx);
12740            self.buffer.update(cx, |buffer, cx| {
12741                buffer.finalize_last_transaction(cx);
12742                if self.leader_peer_id.is_none() {
12743                    buffer.set_active_selections(
12744                        &self.selections.disjoint_anchors(),
12745                        self.selections.line_mode,
12746                        self.cursor_shape,
12747                        cx,
12748                    );
12749                }
12750            });
12751        }
12752    }
12753
12754    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12755        cx.emit(EditorEvent::FocusedIn)
12756    }
12757
12758    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12759        if event.blurred != self.focus_handle {
12760            self.last_focused_descendant = Some(event.blurred);
12761        }
12762    }
12763
12764    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12765        self.blink_manager.update(cx, BlinkManager::disable);
12766        self.buffer
12767            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12768
12769        if let Some(blame) = self.blame.as_ref() {
12770            blame.update(cx, GitBlame::blur)
12771        }
12772        if !self.hover_state.focused(cx) {
12773            hide_hover(self, cx);
12774        }
12775
12776        self.hide_context_menu(cx);
12777        cx.emit(EditorEvent::Blurred);
12778        cx.notify();
12779    }
12780
12781    pub fn register_action<A: Action>(
12782        &mut self,
12783        listener: impl Fn(&A, &mut WindowContext) + 'static,
12784    ) -> Subscription {
12785        let id = self.next_editor_action_id.post_inc();
12786        let listener = Arc::new(listener);
12787        self.editor_actions.borrow_mut().insert(
12788            id,
12789            Box::new(move |cx| {
12790                let cx = cx.window_context();
12791                let listener = listener.clone();
12792                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12793                    let action = action.downcast_ref().unwrap();
12794                    if phase == DispatchPhase::Bubble {
12795                        listener(action, cx)
12796                    }
12797                })
12798            }),
12799        );
12800
12801        let editor_actions = self.editor_actions.clone();
12802        Subscription::new(move || {
12803            editor_actions.borrow_mut().remove(&id);
12804        })
12805    }
12806
12807    pub fn file_header_size(&self) -> u32 {
12808        FILE_HEADER_HEIGHT
12809    }
12810
12811    pub fn revert(
12812        &mut self,
12813        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12814        cx: &mut ViewContext<Self>,
12815    ) {
12816        self.buffer().update(cx, |multi_buffer, cx| {
12817            for (buffer_id, changes) in revert_changes {
12818                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12819                    buffer.update(cx, |buffer, cx| {
12820                        buffer.edit(
12821                            changes.into_iter().map(|(range, text)| {
12822                                (range, text.to_string().map(Arc::<str>::from))
12823                            }),
12824                            None,
12825                            cx,
12826                        );
12827                    });
12828                }
12829            }
12830        });
12831        self.change_selections(None, cx, |selections| selections.refresh());
12832    }
12833
12834    pub fn to_pixel_point(
12835        &mut self,
12836        source: multi_buffer::Anchor,
12837        editor_snapshot: &EditorSnapshot,
12838        cx: &mut ViewContext<Self>,
12839    ) -> Option<gpui::Point<Pixels>> {
12840        let source_point = source.to_display_point(editor_snapshot);
12841        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12842    }
12843
12844    pub fn display_to_pixel_point(
12845        &mut self,
12846        source: DisplayPoint,
12847        editor_snapshot: &EditorSnapshot,
12848        cx: &mut ViewContext<Self>,
12849    ) -> Option<gpui::Point<Pixels>> {
12850        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12851        let text_layout_details = self.text_layout_details(cx);
12852        let scroll_top = text_layout_details
12853            .scroll_anchor
12854            .scroll_position(editor_snapshot)
12855            .y;
12856
12857        if source.row().as_f32() < scroll_top.floor() {
12858            return None;
12859        }
12860        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12861        let source_y = line_height * (source.row().as_f32() - scroll_top);
12862        Some(gpui::Point::new(source_x, source_y))
12863    }
12864
12865    pub fn has_active_completions_menu(&self) -> bool {
12866        self.context_menu.read().as_ref().map_or(false, |menu| {
12867            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12868        })
12869    }
12870
12871    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12872        self.addons
12873            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12874    }
12875
12876    pub fn unregister_addon<T: Addon>(&mut self) {
12877        self.addons.remove(&std::any::TypeId::of::<T>());
12878    }
12879
12880    pub fn addon<T: Addon>(&self) -> Option<&T> {
12881        let type_id = std::any::TypeId::of::<T>();
12882        self.addons
12883            .get(&type_id)
12884            .and_then(|item| item.to_any().downcast_ref::<T>())
12885    }
12886}
12887
12888fn hunks_for_selections(
12889    multi_buffer_snapshot: &MultiBufferSnapshot,
12890    selections: &[Selection<Anchor>],
12891) -> Vec<MultiBufferDiffHunk> {
12892    let buffer_rows_for_selections = selections.iter().map(|selection| {
12893        let head = selection.head();
12894        let tail = selection.tail();
12895        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12896        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12897        if start > end {
12898            end..start
12899        } else {
12900            start..end
12901        }
12902    });
12903
12904    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12905}
12906
12907pub fn hunks_for_rows(
12908    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12909    multi_buffer_snapshot: &MultiBufferSnapshot,
12910) -> Vec<MultiBufferDiffHunk> {
12911    let mut hunks = Vec::new();
12912    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12913        HashMap::default();
12914    for selected_multi_buffer_rows in rows {
12915        let query_rows =
12916            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12917        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12918            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12919            // when the caret is just above or just below the deleted hunk.
12920            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12921            let related_to_selection = if allow_adjacent {
12922                hunk.row_range.overlaps(&query_rows)
12923                    || hunk.row_range.start == query_rows.end
12924                    || hunk.row_range.end == query_rows.start
12925            } else {
12926                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12927                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12928                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12929                    || selected_multi_buffer_rows.end == hunk.row_range.start
12930            };
12931            if related_to_selection {
12932                if !processed_buffer_rows
12933                    .entry(hunk.buffer_id)
12934                    .or_default()
12935                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12936                {
12937                    continue;
12938                }
12939                hunks.push(hunk);
12940            }
12941        }
12942    }
12943
12944    hunks
12945}
12946
12947pub trait CollaborationHub {
12948    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12949    fn user_participant_indices<'a>(
12950        &self,
12951        cx: &'a AppContext,
12952    ) -> &'a HashMap<u64, ParticipantIndex>;
12953    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12954}
12955
12956impl CollaborationHub for Model<Project> {
12957    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12958        self.read(cx).collaborators()
12959    }
12960
12961    fn user_participant_indices<'a>(
12962        &self,
12963        cx: &'a AppContext,
12964    ) -> &'a HashMap<u64, ParticipantIndex> {
12965        self.read(cx).user_store().read(cx).participant_indices()
12966    }
12967
12968    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12969        let this = self.read(cx);
12970        let user_ids = this.collaborators().values().map(|c| c.user_id);
12971        this.user_store().read_with(cx, |user_store, cx| {
12972            user_store.participant_names(user_ids, cx)
12973        })
12974    }
12975}
12976
12977pub trait SemanticsProvider {
12978    fn hover(
12979        &self,
12980        buffer: &Model<Buffer>,
12981        position: text::Anchor,
12982        cx: &mut AppContext,
12983    ) -> Option<Task<Vec<project::Hover>>>;
12984
12985    fn inlay_hints(
12986        &self,
12987        buffer_handle: Model<Buffer>,
12988        range: Range<text::Anchor>,
12989        cx: &mut AppContext,
12990    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12991
12992    fn resolve_inlay_hint(
12993        &self,
12994        hint: InlayHint,
12995        buffer_handle: Model<Buffer>,
12996        server_id: LanguageServerId,
12997        cx: &mut AppContext,
12998    ) -> Option<Task<anyhow::Result<InlayHint>>>;
12999
13000    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13001
13002    fn document_highlights(
13003        &self,
13004        buffer: &Model<Buffer>,
13005        position: text::Anchor,
13006        cx: &mut AppContext,
13007    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13008
13009    fn definitions(
13010        &self,
13011        buffer: &Model<Buffer>,
13012        position: text::Anchor,
13013        kind: GotoDefinitionKind,
13014        cx: &mut AppContext,
13015    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13016
13017    fn range_for_rename(
13018        &self,
13019        buffer: &Model<Buffer>,
13020        position: text::Anchor,
13021        cx: &mut AppContext,
13022    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13023
13024    fn perform_rename(
13025        &self,
13026        buffer: &Model<Buffer>,
13027        position: text::Anchor,
13028        new_name: String,
13029        cx: &mut AppContext,
13030    ) -> Option<Task<Result<ProjectTransaction>>>;
13031}
13032
13033pub trait CompletionProvider {
13034    fn completions(
13035        &self,
13036        buffer: &Model<Buffer>,
13037        buffer_position: text::Anchor,
13038        trigger: CompletionContext,
13039        cx: &mut ViewContext<Editor>,
13040    ) -> Task<Result<Vec<Completion>>>;
13041
13042    fn resolve_completions(
13043        &self,
13044        buffer: Model<Buffer>,
13045        completion_indices: Vec<usize>,
13046        completions: Arc<RwLock<Box<[Completion]>>>,
13047        cx: &mut ViewContext<Editor>,
13048    ) -> Task<Result<bool>>;
13049
13050    fn apply_additional_edits_for_completion(
13051        &self,
13052        buffer: Model<Buffer>,
13053        completion: Completion,
13054        push_to_history: bool,
13055        cx: &mut ViewContext<Editor>,
13056    ) -> Task<Result<Option<language::Transaction>>>;
13057
13058    fn is_completion_trigger(
13059        &self,
13060        buffer: &Model<Buffer>,
13061        position: language::Anchor,
13062        text: &str,
13063        trigger_in_words: bool,
13064        cx: &mut ViewContext<Editor>,
13065    ) -> bool;
13066
13067    fn sort_completions(&self) -> bool {
13068        true
13069    }
13070}
13071
13072pub trait CodeActionProvider {
13073    fn code_actions(
13074        &self,
13075        buffer: &Model<Buffer>,
13076        range: Range<text::Anchor>,
13077        cx: &mut WindowContext,
13078    ) -> Task<Result<Vec<CodeAction>>>;
13079
13080    fn apply_code_action(
13081        &self,
13082        buffer_handle: Model<Buffer>,
13083        action: CodeAction,
13084        excerpt_id: ExcerptId,
13085        push_to_history: bool,
13086        cx: &mut WindowContext,
13087    ) -> Task<Result<ProjectTransaction>>;
13088}
13089
13090impl CodeActionProvider for Model<Project> {
13091    fn code_actions(
13092        &self,
13093        buffer: &Model<Buffer>,
13094        range: Range<text::Anchor>,
13095        cx: &mut WindowContext,
13096    ) -> Task<Result<Vec<CodeAction>>> {
13097        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13098    }
13099
13100    fn apply_code_action(
13101        &self,
13102        buffer_handle: Model<Buffer>,
13103        action: CodeAction,
13104        _excerpt_id: ExcerptId,
13105        push_to_history: bool,
13106        cx: &mut WindowContext,
13107    ) -> Task<Result<ProjectTransaction>> {
13108        self.update(cx, |project, cx| {
13109            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13110        })
13111    }
13112}
13113
13114fn snippet_completions(
13115    project: &Project,
13116    buffer: &Model<Buffer>,
13117    buffer_position: text::Anchor,
13118    cx: &mut AppContext,
13119) -> Vec<Completion> {
13120    let language = buffer.read(cx).language_at(buffer_position);
13121    let language_name = language.as_ref().map(|language| language.lsp_id());
13122    let snippet_store = project.snippets().read(cx);
13123    let snippets = snippet_store.snippets_for(language_name, cx);
13124
13125    if snippets.is_empty() {
13126        return vec![];
13127    }
13128    let snapshot = buffer.read(cx).text_snapshot();
13129    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13130
13131    let scope = language.map(|language| language.default_scope());
13132    let classifier = CharClassifier::new(scope).for_completion(true);
13133    let mut last_word = chars
13134        .take_while(|c| classifier.is_word(*c))
13135        .collect::<String>();
13136    last_word = last_word.chars().rev().collect();
13137    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13138    let to_lsp = |point: &text::Anchor| {
13139        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13140        point_to_lsp(end)
13141    };
13142    let lsp_end = to_lsp(&buffer_position);
13143    snippets
13144        .into_iter()
13145        .filter_map(|snippet| {
13146            let matching_prefix = snippet
13147                .prefix
13148                .iter()
13149                .find(|prefix| prefix.starts_with(&last_word))?;
13150            let start = as_offset - last_word.len();
13151            let start = snapshot.anchor_before(start);
13152            let range = start..buffer_position;
13153            let lsp_start = to_lsp(&start);
13154            let lsp_range = lsp::Range {
13155                start: lsp_start,
13156                end: lsp_end,
13157            };
13158            Some(Completion {
13159                old_range: range,
13160                new_text: snippet.body.clone(),
13161                label: CodeLabel {
13162                    text: matching_prefix.clone(),
13163                    runs: vec![],
13164                    filter_range: 0..matching_prefix.len(),
13165                },
13166                server_id: LanguageServerId(usize::MAX),
13167                documentation: snippet.description.clone().map(Documentation::SingleLine),
13168                lsp_completion: lsp::CompletionItem {
13169                    label: snippet.prefix.first().unwrap().clone(),
13170                    kind: Some(CompletionItemKind::SNIPPET),
13171                    label_details: snippet.description.as_ref().map(|description| {
13172                        lsp::CompletionItemLabelDetails {
13173                            detail: Some(description.clone()),
13174                            description: None,
13175                        }
13176                    }),
13177                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13178                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13179                        lsp::InsertReplaceEdit {
13180                            new_text: snippet.body.clone(),
13181                            insert: lsp_range,
13182                            replace: lsp_range,
13183                        },
13184                    )),
13185                    filter_text: Some(snippet.body.clone()),
13186                    sort_text: Some(char::MAX.to_string()),
13187                    ..Default::default()
13188                },
13189                confirm: None,
13190            })
13191        })
13192        .collect()
13193}
13194
13195impl CompletionProvider for Model<Project> {
13196    fn completions(
13197        &self,
13198        buffer: &Model<Buffer>,
13199        buffer_position: text::Anchor,
13200        options: CompletionContext,
13201        cx: &mut ViewContext<Editor>,
13202    ) -> Task<Result<Vec<Completion>>> {
13203        self.update(cx, |project, cx| {
13204            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13205            let project_completions = project.completions(buffer, buffer_position, options, cx);
13206            cx.background_executor().spawn(async move {
13207                let mut completions = project_completions.await?;
13208                //let snippets = snippets.into_iter().;
13209                completions.extend(snippets);
13210                Ok(completions)
13211            })
13212        })
13213    }
13214
13215    fn resolve_completions(
13216        &self,
13217        buffer: Model<Buffer>,
13218        completion_indices: Vec<usize>,
13219        completions: Arc<RwLock<Box<[Completion]>>>,
13220        cx: &mut ViewContext<Editor>,
13221    ) -> Task<Result<bool>> {
13222        self.update(cx, |project, cx| {
13223            project.resolve_completions(buffer, completion_indices, completions, cx)
13224        })
13225    }
13226
13227    fn apply_additional_edits_for_completion(
13228        &self,
13229        buffer: Model<Buffer>,
13230        completion: Completion,
13231        push_to_history: bool,
13232        cx: &mut ViewContext<Editor>,
13233    ) -> Task<Result<Option<language::Transaction>>> {
13234        self.update(cx, |project, cx| {
13235            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13236        })
13237    }
13238
13239    fn is_completion_trigger(
13240        &self,
13241        buffer: &Model<Buffer>,
13242        position: language::Anchor,
13243        text: &str,
13244        trigger_in_words: bool,
13245        cx: &mut ViewContext<Editor>,
13246    ) -> bool {
13247        if !EditorSettings::get_global(cx).show_completions_on_input {
13248            return false;
13249        }
13250
13251        let mut chars = text.chars();
13252        let char = if let Some(char) = chars.next() {
13253            char
13254        } else {
13255            return false;
13256        };
13257        if chars.next().is_some() {
13258            return false;
13259        }
13260
13261        let buffer = buffer.read(cx);
13262        let classifier = buffer
13263            .snapshot()
13264            .char_classifier_at(position)
13265            .for_completion(true);
13266        if trigger_in_words && classifier.is_word(char) {
13267            return true;
13268        }
13269
13270        buffer
13271            .completion_triggers()
13272            .iter()
13273            .any(|string| string == text)
13274    }
13275}
13276
13277impl SemanticsProvider for Model<Project> {
13278    fn hover(
13279        &self,
13280        buffer: &Model<Buffer>,
13281        position: text::Anchor,
13282        cx: &mut AppContext,
13283    ) -> Option<Task<Vec<project::Hover>>> {
13284        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13285    }
13286
13287    fn document_highlights(
13288        &self,
13289        buffer: &Model<Buffer>,
13290        position: text::Anchor,
13291        cx: &mut AppContext,
13292    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13293        Some(self.update(cx, |project, cx| {
13294            project.document_highlights(buffer, position, cx)
13295        }))
13296    }
13297
13298    fn definitions(
13299        &self,
13300        buffer: &Model<Buffer>,
13301        position: text::Anchor,
13302        kind: GotoDefinitionKind,
13303        cx: &mut AppContext,
13304    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13305        Some(self.update(cx, |project, cx| match kind {
13306            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13307            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13308            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13309            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13310        }))
13311    }
13312
13313    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13314        // TODO: make this work for remote projects
13315        self.read(cx)
13316            .language_servers_for_buffer(buffer.read(cx), cx)
13317            .any(
13318                |(_, server)| match server.capabilities().inlay_hint_provider {
13319                    Some(lsp::OneOf::Left(enabled)) => enabled,
13320                    Some(lsp::OneOf::Right(_)) => true,
13321                    None => false,
13322                },
13323            )
13324    }
13325
13326    fn inlay_hints(
13327        &self,
13328        buffer_handle: Model<Buffer>,
13329        range: Range<text::Anchor>,
13330        cx: &mut AppContext,
13331    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13332        Some(self.update(cx, |project, cx| {
13333            project.inlay_hints(buffer_handle, range, cx)
13334        }))
13335    }
13336
13337    fn resolve_inlay_hint(
13338        &self,
13339        hint: InlayHint,
13340        buffer_handle: Model<Buffer>,
13341        server_id: LanguageServerId,
13342        cx: &mut AppContext,
13343    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13344        Some(self.update(cx, |project, cx| {
13345            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13346        }))
13347    }
13348
13349    fn range_for_rename(
13350        &self,
13351        buffer: &Model<Buffer>,
13352        position: text::Anchor,
13353        cx: &mut AppContext,
13354    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13355        Some(self.update(cx, |project, cx| {
13356            project.prepare_rename(buffer.clone(), position, cx)
13357        }))
13358    }
13359
13360    fn perform_rename(
13361        &self,
13362        buffer: &Model<Buffer>,
13363        position: text::Anchor,
13364        new_name: String,
13365        cx: &mut AppContext,
13366    ) -> Option<Task<Result<ProjectTransaction>>> {
13367        Some(self.update(cx, |project, cx| {
13368            project.perform_rename(buffer.clone(), position, new_name, cx)
13369        }))
13370    }
13371}
13372
13373fn inlay_hint_settings(
13374    location: Anchor,
13375    snapshot: &MultiBufferSnapshot,
13376    cx: &mut ViewContext<'_, Editor>,
13377) -> InlayHintSettings {
13378    let file = snapshot.file_at(location);
13379    let language = snapshot.language_at(location);
13380    let settings = all_language_settings(file, cx);
13381    settings
13382        .language(language.map(|l| l.name()).as_ref())
13383        .inlay_hints
13384}
13385
13386fn consume_contiguous_rows(
13387    contiguous_row_selections: &mut Vec<Selection<Point>>,
13388    selection: &Selection<Point>,
13389    display_map: &DisplaySnapshot,
13390    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13391) -> (MultiBufferRow, MultiBufferRow) {
13392    contiguous_row_selections.push(selection.clone());
13393    let start_row = MultiBufferRow(selection.start.row);
13394    let mut end_row = ending_row(selection, display_map);
13395
13396    while let Some(next_selection) = selections.peek() {
13397        if next_selection.start.row <= end_row.0 {
13398            end_row = ending_row(next_selection, display_map);
13399            contiguous_row_selections.push(selections.next().unwrap().clone());
13400        } else {
13401            break;
13402        }
13403    }
13404    (start_row, end_row)
13405}
13406
13407fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13408    if next_selection.end.column > 0 || next_selection.is_empty() {
13409        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13410    } else {
13411        MultiBufferRow(next_selection.end.row)
13412    }
13413}
13414
13415impl EditorSnapshot {
13416    pub fn remote_selections_in_range<'a>(
13417        &'a self,
13418        range: &'a Range<Anchor>,
13419        collaboration_hub: &dyn CollaborationHub,
13420        cx: &'a AppContext,
13421    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13422        let participant_names = collaboration_hub.user_names(cx);
13423        let participant_indices = collaboration_hub.user_participant_indices(cx);
13424        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13425        let collaborators_by_replica_id = collaborators_by_peer_id
13426            .iter()
13427            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13428            .collect::<HashMap<_, _>>();
13429        self.buffer_snapshot
13430            .selections_in_range(range, false)
13431            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13432                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13433                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13434                let user_name = participant_names.get(&collaborator.user_id).cloned();
13435                Some(RemoteSelection {
13436                    replica_id,
13437                    selection,
13438                    cursor_shape,
13439                    line_mode,
13440                    participant_index,
13441                    peer_id: collaborator.peer_id,
13442                    user_name,
13443                })
13444            })
13445    }
13446
13447    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13448        self.display_snapshot.buffer_snapshot.language_at(position)
13449    }
13450
13451    pub fn is_focused(&self) -> bool {
13452        self.is_focused
13453    }
13454
13455    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13456        self.placeholder_text.as_ref()
13457    }
13458
13459    pub fn scroll_position(&self) -> gpui::Point<f32> {
13460        self.scroll_anchor.scroll_position(&self.display_snapshot)
13461    }
13462
13463    fn gutter_dimensions(
13464        &self,
13465        font_id: FontId,
13466        font_size: Pixels,
13467        em_width: Pixels,
13468        em_advance: Pixels,
13469        max_line_number_width: Pixels,
13470        cx: &AppContext,
13471    ) -> GutterDimensions {
13472        if !self.show_gutter {
13473            return GutterDimensions::default();
13474        }
13475        let descent = cx.text_system().descent(font_id, font_size);
13476
13477        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13478            matches!(
13479                ProjectSettings::get_global(cx).git.git_gutter,
13480                Some(GitGutterSetting::TrackedFiles)
13481            )
13482        });
13483        let gutter_settings = EditorSettings::get_global(cx).gutter;
13484        let show_line_numbers = self
13485            .show_line_numbers
13486            .unwrap_or(gutter_settings.line_numbers);
13487        let line_gutter_width = if show_line_numbers {
13488            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13489            let min_width_for_number_on_gutter = em_advance * 4.0;
13490            max_line_number_width.max(min_width_for_number_on_gutter)
13491        } else {
13492            0.0.into()
13493        };
13494
13495        let show_code_actions = self
13496            .show_code_actions
13497            .unwrap_or(gutter_settings.code_actions);
13498
13499        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13500
13501        let git_blame_entries_width =
13502            self.git_blame_gutter_max_author_length
13503                .map(|max_author_length| {
13504                    // Length of the author name, but also space for the commit hash,
13505                    // the spacing and the timestamp.
13506                    let max_char_count = max_author_length
13507                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13508                        + 7 // length of commit sha
13509                        + 14 // length of max relative timestamp ("60 minutes ago")
13510                        + 4; // gaps and margins
13511
13512                    em_advance * max_char_count
13513                });
13514
13515        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13516        left_padding += if show_code_actions || show_runnables {
13517            em_width * 3.0
13518        } else if show_git_gutter && show_line_numbers {
13519            em_width * 2.0
13520        } else if show_git_gutter || show_line_numbers {
13521            em_width
13522        } else {
13523            px(0.)
13524        };
13525
13526        let right_padding = if gutter_settings.folds && show_line_numbers {
13527            em_width * 4.0
13528        } else if gutter_settings.folds {
13529            em_width * 3.0
13530        } else if show_line_numbers {
13531            em_width
13532        } else {
13533            px(0.)
13534        };
13535
13536        GutterDimensions {
13537            left_padding,
13538            right_padding,
13539            width: line_gutter_width + left_padding + right_padding,
13540            margin: -descent,
13541            git_blame_entries_width,
13542        }
13543    }
13544
13545    pub fn render_fold_toggle(
13546        &self,
13547        buffer_row: MultiBufferRow,
13548        row_contains_cursor: bool,
13549        editor: View<Editor>,
13550        cx: &mut WindowContext,
13551    ) -> Option<AnyElement> {
13552        let folded = self.is_line_folded(buffer_row);
13553
13554        if let Some(crease) = self
13555            .crease_snapshot
13556            .query_row(buffer_row, &self.buffer_snapshot)
13557        {
13558            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13559                if folded {
13560                    editor.update(cx, |editor, cx| {
13561                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13562                    });
13563                } else {
13564                    editor.update(cx, |editor, cx| {
13565                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13566                    });
13567                }
13568            });
13569
13570            Some((crease.render_toggle)(
13571                buffer_row,
13572                folded,
13573                toggle_callback,
13574                cx,
13575            ))
13576        } else if folded
13577            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13578        {
13579            Some(
13580                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13581                    .selected(folded)
13582                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13583                        if folded {
13584                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13585                        } else {
13586                            this.fold_at(&FoldAt { buffer_row }, cx);
13587                        }
13588                    }))
13589                    .into_any_element(),
13590            )
13591        } else {
13592            None
13593        }
13594    }
13595
13596    pub fn render_crease_trailer(
13597        &self,
13598        buffer_row: MultiBufferRow,
13599        cx: &mut WindowContext,
13600    ) -> Option<AnyElement> {
13601        let folded = self.is_line_folded(buffer_row);
13602        let crease = self
13603            .crease_snapshot
13604            .query_row(buffer_row, &self.buffer_snapshot)?;
13605        Some((crease.render_trailer)(buffer_row, folded, cx))
13606    }
13607}
13608
13609impl Deref for EditorSnapshot {
13610    type Target = DisplaySnapshot;
13611
13612    fn deref(&self) -> &Self::Target {
13613        &self.display_snapshot
13614    }
13615}
13616
13617#[derive(Clone, Debug, PartialEq, Eq)]
13618pub enum EditorEvent {
13619    InputIgnored {
13620        text: Arc<str>,
13621    },
13622    InputHandled {
13623        utf16_range_to_replace: Option<Range<isize>>,
13624        text: Arc<str>,
13625    },
13626    ExcerptsAdded {
13627        buffer: Model<Buffer>,
13628        predecessor: ExcerptId,
13629        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13630    },
13631    ExcerptsRemoved {
13632        ids: Vec<ExcerptId>,
13633    },
13634    ExcerptsEdited {
13635        ids: Vec<ExcerptId>,
13636    },
13637    ExcerptsExpanded {
13638        ids: Vec<ExcerptId>,
13639    },
13640    BufferEdited,
13641    Edited {
13642        transaction_id: clock::Lamport,
13643    },
13644    Reparsed(BufferId),
13645    Focused,
13646    FocusedIn,
13647    Blurred,
13648    DirtyChanged,
13649    Saved,
13650    TitleChanged,
13651    DiffBaseChanged,
13652    SelectionsChanged {
13653        local: bool,
13654    },
13655    ScrollPositionChanged {
13656        local: bool,
13657        autoscroll: bool,
13658    },
13659    Closed,
13660    TransactionUndone {
13661        transaction_id: clock::Lamport,
13662    },
13663    TransactionBegun {
13664        transaction_id: clock::Lamport,
13665    },
13666    Reloaded,
13667    CursorShapeChanged,
13668}
13669
13670impl EventEmitter<EditorEvent> for Editor {}
13671
13672impl FocusableView for Editor {
13673    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13674        self.focus_handle.clone()
13675    }
13676}
13677
13678impl Render for Editor {
13679    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13680        let settings = ThemeSettings::get_global(cx);
13681
13682        let text_style = match self.mode {
13683            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13684                color: cx.theme().colors().editor_foreground,
13685                font_family: settings.ui_font.family.clone(),
13686                font_features: settings.ui_font.features.clone(),
13687                font_fallbacks: settings.ui_font.fallbacks.clone(),
13688                font_size: rems(0.875).into(),
13689                font_weight: settings.ui_font.weight,
13690                line_height: relative(settings.buffer_line_height.value()),
13691                ..Default::default()
13692            },
13693            EditorMode::Full => TextStyle {
13694                color: cx.theme().colors().editor_foreground,
13695                font_family: settings.buffer_font.family.clone(),
13696                font_features: settings.buffer_font.features.clone(),
13697                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13698                font_size: settings.buffer_font_size(cx).into(),
13699                font_weight: settings.buffer_font.weight,
13700                line_height: relative(settings.buffer_line_height.value()),
13701                ..Default::default()
13702            },
13703        };
13704
13705        let background = match self.mode {
13706            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13707            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13708            EditorMode::Full => cx.theme().colors().editor_background,
13709        };
13710
13711        EditorElement::new(
13712            cx.view(),
13713            EditorStyle {
13714                background,
13715                local_player: cx.theme().players().local(),
13716                text: text_style,
13717                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13718                syntax: cx.theme().syntax().clone(),
13719                status: cx.theme().status().clone(),
13720                inlay_hints_style: make_inlay_hints_style(cx),
13721                suggestions_style: HighlightStyle {
13722                    color: Some(cx.theme().status().predictive),
13723                    ..HighlightStyle::default()
13724                },
13725                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13726            },
13727        )
13728    }
13729}
13730
13731impl ViewInputHandler for Editor {
13732    fn text_for_range(
13733        &mut self,
13734        range_utf16: Range<usize>,
13735        cx: &mut ViewContext<Self>,
13736    ) -> Option<String> {
13737        Some(
13738            self.buffer
13739                .read(cx)
13740                .read(cx)
13741                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13742                .collect(),
13743        )
13744    }
13745
13746    fn selected_text_range(
13747        &mut self,
13748        ignore_disabled_input: bool,
13749        cx: &mut ViewContext<Self>,
13750    ) -> Option<UTF16Selection> {
13751        // Prevent the IME menu from appearing when holding down an alphabetic key
13752        // while input is disabled.
13753        if !ignore_disabled_input && !self.input_enabled {
13754            return None;
13755        }
13756
13757        let selection = self.selections.newest::<OffsetUtf16>(cx);
13758        let range = selection.range();
13759
13760        Some(UTF16Selection {
13761            range: range.start.0..range.end.0,
13762            reversed: selection.reversed,
13763        })
13764    }
13765
13766    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13767        let snapshot = self.buffer.read(cx).read(cx);
13768        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13769        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13770    }
13771
13772    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13773        self.clear_highlights::<InputComposition>(cx);
13774        self.ime_transaction.take();
13775    }
13776
13777    fn replace_text_in_range(
13778        &mut self,
13779        range_utf16: Option<Range<usize>>,
13780        text: &str,
13781        cx: &mut ViewContext<Self>,
13782    ) {
13783        if !self.input_enabled {
13784            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13785            return;
13786        }
13787
13788        self.transact(cx, |this, cx| {
13789            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13790                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13791                Some(this.selection_replacement_ranges(range_utf16, cx))
13792            } else {
13793                this.marked_text_ranges(cx)
13794            };
13795
13796            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13797                let newest_selection_id = this.selections.newest_anchor().id;
13798                this.selections
13799                    .all::<OffsetUtf16>(cx)
13800                    .iter()
13801                    .zip(ranges_to_replace.iter())
13802                    .find_map(|(selection, range)| {
13803                        if selection.id == newest_selection_id {
13804                            Some(
13805                                (range.start.0 as isize - selection.head().0 as isize)
13806                                    ..(range.end.0 as isize - selection.head().0 as isize),
13807                            )
13808                        } else {
13809                            None
13810                        }
13811                    })
13812            });
13813
13814            cx.emit(EditorEvent::InputHandled {
13815                utf16_range_to_replace: range_to_replace,
13816                text: text.into(),
13817            });
13818
13819            if let Some(new_selected_ranges) = new_selected_ranges {
13820                this.change_selections(None, cx, |selections| {
13821                    selections.select_ranges(new_selected_ranges)
13822                });
13823                this.backspace(&Default::default(), cx);
13824            }
13825
13826            this.handle_input(text, cx);
13827        });
13828
13829        if let Some(transaction) = self.ime_transaction {
13830            self.buffer.update(cx, |buffer, cx| {
13831                buffer.group_until_transaction(transaction, cx);
13832            });
13833        }
13834
13835        self.unmark_text(cx);
13836    }
13837
13838    fn replace_and_mark_text_in_range(
13839        &mut self,
13840        range_utf16: Option<Range<usize>>,
13841        text: &str,
13842        new_selected_range_utf16: Option<Range<usize>>,
13843        cx: &mut ViewContext<Self>,
13844    ) {
13845        if !self.input_enabled {
13846            return;
13847        }
13848
13849        let transaction = self.transact(cx, |this, cx| {
13850            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13851                let snapshot = this.buffer.read(cx).read(cx);
13852                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13853                    for marked_range in &mut marked_ranges {
13854                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13855                        marked_range.start.0 += relative_range_utf16.start;
13856                        marked_range.start =
13857                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13858                        marked_range.end =
13859                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13860                    }
13861                }
13862                Some(marked_ranges)
13863            } else if let Some(range_utf16) = range_utf16 {
13864                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13865                Some(this.selection_replacement_ranges(range_utf16, cx))
13866            } else {
13867                None
13868            };
13869
13870            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13871                let newest_selection_id = this.selections.newest_anchor().id;
13872                this.selections
13873                    .all::<OffsetUtf16>(cx)
13874                    .iter()
13875                    .zip(ranges_to_replace.iter())
13876                    .find_map(|(selection, range)| {
13877                        if selection.id == newest_selection_id {
13878                            Some(
13879                                (range.start.0 as isize - selection.head().0 as isize)
13880                                    ..(range.end.0 as isize - selection.head().0 as isize),
13881                            )
13882                        } else {
13883                            None
13884                        }
13885                    })
13886            });
13887
13888            cx.emit(EditorEvent::InputHandled {
13889                utf16_range_to_replace: range_to_replace,
13890                text: text.into(),
13891            });
13892
13893            if let Some(ranges) = ranges_to_replace {
13894                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13895            }
13896
13897            let marked_ranges = {
13898                let snapshot = this.buffer.read(cx).read(cx);
13899                this.selections
13900                    .disjoint_anchors()
13901                    .iter()
13902                    .map(|selection| {
13903                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13904                    })
13905                    .collect::<Vec<_>>()
13906            };
13907
13908            if text.is_empty() {
13909                this.unmark_text(cx);
13910            } else {
13911                this.highlight_text::<InputComposition>(
13912                    marked_ranges.clone(),
13913                    HighlightStyle {
13914                        underline: Some(UnderlineStyle {
13915                            thickness: px(1.),
13916                            color: None,
13917                            wavy: false,
13918                        }),
13919                        ..Default::default()
13920                    },
13921                    cx,
13922                );
13923            }
13924
13925            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13926            let use_autoclose = this.use_autoclose;
13927            let use_auto_surround = this.use_auto_surround;
13928            this.set_use_autoclose(false);
13929            this.set_use_auto_surround(false);
13930            this.handle_input(text, cx);
13931            this.set_use_autoclose(use_autoclose);
13932            this.set_use_auto_surround(use_auto_surround);
13933
13934            if let Some(new_selected_range) = new_selected_range_utf16 {
13935                let snapshot = this.buffer.read(cx).read(cx);
13936                let new_selected_ranges = marked_ranges
13937                    .into_iter()
13938                    .map(|marked_range| {
13939                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13940                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13941                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13942                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13943                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13944                    })
13945                    .collect::<Vec<_>>();
13946
13947                drop(snapshot);
13948                this.change_selections(None, cx, |selections| {
13949                    selections.select_ranges(new_selected_ranges)
13950                });
13951            }
13952        });
13953
13954        self.ime_transaction = self.ime_transaction.or(transaction);
13955        if let Some(transaction) = self.ime_transaction {
13956            self.buffer.update(cx, |buffer, cx| {
13957                buffer.group_until_transaction(transaction, cx);
13958            });
13959        }
13960
13961        if self.text_highlights::<InputComposition>(cx).is_none() {
13962            self.ime_transaction.take();
13963        }
13964    }
13965
13966    fn bounds_for_range(
13967        &mut self,
13968        range_utf16: Range<usize>,
13969        element_bounds: gpui::Bounds<Pixels>,
13970        cx: &mut ViewContext<Self>,
13971    ) -> Option<gpui::Bounds<Pixels>> {
13972        let text_layout_details = self.text_layout_details(cx);
13973        let style = &text_layout_details.editor_style;
13974        let font_id = cx.text_system().resolve_font(&style.text.font());
13975        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13976        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13977
13978        let em_width = cx
13979            .text_system()
13980            .typographic_bounds(font_id, font_size, 'm')
13981            .unwrap()
13982            .size
13983            .width;
13984
13985        let snapshot = self.snapshot(cx);
13986        let scroll_position = snapshot.scroll_position();
13987        let scroll_left = scroll_position.x * em_width;
13988
13989        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13990        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13991            + self.gutter_dimensions.width;
13992        let y = line_height * (start.row().as_f32() - scroll_position.y);
13993
13994        Some(Bounds {
13995            origin: element_bounds.origin + point(x, y),
13996            size: size(em_width, line_height),
13997        })
13998    }
13999}
14000
14001trait SelectionExt {
14002    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14003    fn spanned_rows(
14004        &self,
14005        include_end_if_at_line_start: bool,
14006        map: &DisplaySnapshot,
14007    ) -> Range<MultiBufferRow>;
14008}
14009
14010impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14011    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14012        let start = self
14013            .start
14014            .to_point(&map.buffer_snapshot)
14015            .to_display_point(map);
14016        let end = self
14017            .end
14018            .to_point(&map.buffer_snapshot)
14019            .to_display_point(map);
14020        if self.reversed {
14021            end..start
14022        } else {
14023            start..end
14024        }
14025    }
14026
14027    fn spanned_rows(
14028        &self,
14029        include_end_if_at_line_start: bool,
14030        map: &DisplaySnapshot,
14031    ) -> Range<MultiBufferRow> {
14032        let start = self.start.to_point(&map.buffer_snapshot);
14033        let mut end = self.end.to_point(&map.buffer_snapshot);
14034        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14035            end.row -= 1;
14036        }
14037
14038        let buffer_start = map.prev_line_boundary(start).0;
14039        let buffer_end = map.next_line_boundary(end).0;
14040        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14041    }
14042}
14043
14044impl<T: InvalidationRegion> InvalidationStack<T> {
14045    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14046    where
14047        S: Clone + ToOffset,
14048    {
14049        while let Some(region) = self.last() {
14050            let all_selections_inside_invalidation_ranges =
14051                if selections.len() == region.ranges().len() {
14052                    selections
14053                        .iter()
14054                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14055                        .all(|(selection, invalidation_range)| {
14056                            let head = selection.head().to_offset(buffer);
14057                            invalidation_range.start <= head && invalidation_range.end >= head
14058                        })
14059                } else {
14060                    false
14061                };
14062
14063            if all_selections_inside_invalidation_ranges {
14064                break;
14065            } else {
14066                self.pop();
14067            }
14068        }
14069    }
14070}
14071
14072impl<T> Default for InvalidationStack<T> {
14073    fn default() -> Self {
14074        Self(Default::default())
14075    }
14076}
14077
14078impl<T> Deref for InvalidationStack<T> {
14079    type Target = Vec<T>;
14080
14081    fn deref(&self) -> &Self::Target {
14082        &self.0
14083    }
14084}
14085
14086impl<T> DerefMut for InvalidationStack<T> {
14087    fn deref_mut(&mut self) -> &mut Self::Target {
14088        &mut self.0
14089    }
14090}
14091
14092impl InvalidationRegion for SnippetState {
14093    fn ranges(&self) -> &[Range<Anchor>] {
14094        &self.ranges[self.active_index]
14095    }
14096}
14097
14098pub fn diagnostic_block_renderer(
14099    diagnostic: Diagnostic,
14100    max_message_rows: Option<u8>,
14101    allow_closing: bool,
14102    _is_valid: bool,
14103) -> RenderBlock {
14104    let (text_without_backticks, code_ranges) =
14105        highlight_diagnostic_message(&diagnostic, max_message_rows);
14106
14107    Box::new(move |cx: &mut BlockContext| {
14108        let group_id: SharedString = cx.block_id.to_string().into();
14109
14110        let mut text_style = cx.text_style().clone();
14111        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14112        let theme_settings = ThemeSettings::get_global(cx);
14113        text_style.font_family = theme_settings.buffer_font.family.clone();
14114        text_style.font_style = theme_settings.buffer_font.style;
14115        text_style.font_features = theme_settings.buffer_font.features.clone();
14116        text_style.font_weight = theme_settings.buffer_font.weight;
14117
14118        let multi_line_diagnostic = diagnostic.message.contains('\n');
14119
14120        let buttons = |diagnostic: &Diagnostic| {
14121            if multi_line_diagnostic {
14122                v_flex()
14123            } else {
14124                h_flex()
14125            }
14126            .when(allow_closing, |div| {
14127                div.children(diagnostic.is_primary.then(|| {
14128                    IconButton::new("close-block", IconName::XCircle)
14129                        .icon_color(Color::Muted)
14130                        .size(ButtonSize::Compact)
14131                        .style(ButtonStyle::Transparent)
14132                        .visible_on_hover(group_id.clone())
14133                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14134                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14135                }))
14136            })
14137            .child(
14138                IconButton::new("copy-block", IconName::Copy)
14139                    .icon_color(Color::Muted)
14140                    .size(ButtonSize::Compact)
14141                    .style(ButtonStyle::Transparent)
14142                    .visible_on_hover(group_id.clone())
14143                    .on_click({
14144                        let message = diagnostic.message.clone();
14145                        move |_click, cx| {
14146                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14147                        }
14148                    })
14149                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14150            )
14151        };
14152
14153        let icon_size = buttons(&diagnostic)
14154            .into_any_element()
14155            .layout_as_root(AvailableSpace::min_size(), cx);
14156
14157        h_flex()
14158            .id(cx.block_id)
14159            .group(group_id.clone())
14160            .relative()
14161            .size_full()
14162            .pl(cx.gutter_dimensions.width)
14163            .w(cx.max_width + cx.gutter_dimensions.width)
14164            .child(
14165                div()
14166                    .flex()
14167                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14168                    .flex_shrink(),
14169            )
14170            .child(buttons(&diagnostic))
14171            .child(div().flex().flex_shrink_0().child(
14172                StyledText::new(text_without_backticks.clone()).with_highlights(
14173                    &text_style,
14174                    code_ranges.iter().map(|range| {
14175                        (
14176                            range.clone(),
14177                            HighlightStyle {
14178                                font_weight: Some(FontWeight::BOLD),
14179                                ..Default::default()
14180                            },
14181                        )
14182                    }),
14183                ),
14184            ))
14185            .into_any_element()
14186    })
14187}
14188
14189pub fn highlight_diagnostic_message(
14190    diagnostic: &Diagnostic,
14191    mut max_message_rows: Option<u8>,
14192) -> (SharedString, Vec<Range<usize>>) {
14193    let mut text_without_backticks = String::new();
14194    let mut code_ranges = Vec::new();
14195
14196    if let Some(source) = &diagnostic.source {
14197        text_without_backticks.push_str(source);
14198        code_ranges.push(0..source.len());
14199        text_without_backticks.push_str(": ");
14200    }
14201
14202    let mut prev_offset = 0;
14203    let mut in_code_block = false;
14204    let has_row_limit = max_message_rows.is_some();
14205    let mut newline_indices = diagnostic
14206        .message
14207        .match_indices('\n')
14208        .filter(|_| has_row_limit)
14209        .map(|(ix, _)| ix)
14210        .fuse()
14211        .peekable();
14212
14213    for (quote_ix, _) in diagnostic
14214        .message
14215        .match_indices('`')
14216        .chain([(diagnostic.message.len(), "")])
14217    {
14218        let mut first_newline_ix = None;
14219        let mut last_newline_ix = None;
14220        while let Some(newline_ix) = newline_indices.peek() {
14221            if *newline_ix < quote_ix {
14222                if first_newline_ix.is_none() {
14223                    first_newline_ix = Some(*newline_ix);
14224                }
14225                last_newline_ix = Some(*newline_ix);
14226
14227                if let Some(rows_left) = &mut max_message_rows {
14228                    if *rows_left == 0 {
14229                        break;
14230                    } else {
14231                        *rows_left -= 1;
14232                    }
14233                }
14234                let _ = newline_indices.next();
14235            } else {
14236                break;
14237            }
14238        }
14239        let prev_len = text_without_backticks.len();
14240        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14241        text_without_backticks.push_str(new_text);
14242        if in_code_block {
14243            code_ranges.push(prev_len..text_without_backticks.len());
14244        }
14245        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14246        in_code_block = !in_code_block;
14247        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14248            text_without_backticks.push_str("...");
14249            break;
14250        }
14251    }
14252
14253    (text_without_backticks.into(), code_ranges)
14254}
14255
14256fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14257    match severity {
14258        DiagnosticSeverity::ERROR => colors.error,
14259        DiagnosticSeverity::WARNING => colors.warning,
14260        DiagnosticSeverity::INFORMATION => colors.info,
14261        DiagnosticSeverity::HINT => colors.info,
14262        _ => colors.ignored,
14263    }
14264}
14265
14266pub fn styled_runs_for_code_label<'a>(
14267    label: &'a CodeLabel,
14268    syntax_theme: &'a theme::SyntaxTheme,
14269) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14270    let fade_out = HighlightStyle {
14271        fade_out: Some(0.35),
14272        ..Default::default()
14273    };
14274
14275    let mut prev_end = label.filter_range.end;
14276    label
14277        .runs
14278        .iter()
14279        .enumerate()
14280        .flat_map(move |(ix, (range, highlight_id))| {
14281            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14282                style
14283            } else {
14284                return Default::default();
14285            };
14286            let mut muted_style = style;
14287            muted_style.highlight(fade_out);
14288
14289            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14290            if range.start >= label.filter_range.end {
14291                if range.start > prev_end {
14292                    runs.push((prev_end..range.start, fade_out));
14293                }
14294                runs.push((range.clone(), muted_style));
14295            } else if range.end <= label.filter_range.end {
14296                runs.push((range.clone(), style));
14297            } else {
14298                runs.push((range.start..label.filter_range.end, style));
14299                runs.push((label.filter_range.end..range.end, muted_style));
14300            }
14301            prev_end = cmp::max(prev_end, range.end);
14302
14303            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14304                runs.push((prev_end..label.text.len(), fade_out));
14305            }
14306
14307            runs
14308        })
14309}
14310
14311pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14312    let mut prev_index = 0;
14313    let mut prev_codepoint: Option<char> = None;
14314    text.char_indices()
14315        .chain([(text.len(), '\0')])
14316        .filter_map(move |(index, codepoint)| {
14317            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14318            let is_boundary = index == text.len()
14319                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14320                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14321            if is_boundary {
14322                let chunk = &text[prev_index..index];
14323                prev_index = index;
14324                Some(chunk)
14325            } else {
14326                None
14327            }
14328        })
14329}
14330
14331pub trait RangeToAnchorExt: Sized {
14332    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14333
14334    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14335        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14336        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14337    }
14338}
14339
14340impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14341    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14342        let start_offset = self.start.to_offset(snapshot);
14343        let end_offset = self.end.to_offset(snapshot);
14344        if start_offset == end_offset {
14345            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14346        } else {
14347            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14348        }
14349    }
14350}
14351
14352pub trait RowExt {
14353    fn as_f32(&self) -> f32;
14354
14355    fn next_row(&self) -> Self;
14356
14357    fn previous_row(&self) -> Self;
14358
14359    fn minus(&self, other: Self) -> u32;
14360}
14361
14362impl RowExt for DisplayRow {
14363    fn as_f32(&self) -> f32 {
14364        self.0 as f32
14365    }
14366
14367    fn next_row(&self) -> Self {
14368        Self(self.0 + 1)
14369    }
14370
14371    fn previous_row(&self) -> Self {
14372        Self(self.0.saturating_sub(1))
14373    }
14374
14375    fn minus(&self, other: Self) -> u32 {
14376        self.0 - other.0
14377    }
14378}
14379
14380impl RowExt for MultiBufferRow {
14381    fn as_f32(&self) -> f32 {
14382        self.0 as f32
14383    }
14384
14385    fn next_row(&self) -> Self {
14386        Self(self.0 + 1)
14387    }
14388
14389    fn previous_row(&self) -> Self {
14390        Self(self.0.saturating_sub(1))
14391    }
14392
14393    fn minus(&self, other: Self) -> u32 {
14394        self.0 - other.0
14395    }
14396}
14397
14398trait RowRangeExt {
14399    type Row;
14400
14401    fn len(&self) -> usize;
14402
14403    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14404}
14405
14406impl RowRangeExt for Range<MultiBufferRow> {
14407    type Row = MultiBufferRow;
14408
14409    fn len(&self) -> usize {
14410        (self.end.0 - self.start.0) as usize
14411    }
14412
14413    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14414        (self.start.0..self.end.0).map(MultiBufferRow)
14415    }
14416}
14417
14418impl RowRangeExt for Range<DisplayRow> {
14419    type Row = DisplayRow;
14420
14421    fn len(&self) -> usize {
14422        (self.end.0 - self.start.0) as usize
14423    }
14424
14425    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14426        (self.start.0..self.end.0).map(DisplayRow)
14427    }
14428}
14429
14430fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14431    if hunk.diff_base_byte_range.is_empty() {
14432        DiffHunkStatus::Added
14433    } else if hunk.row_range.is_empty() {
14434        DiffHunkStatus::Removed
14435    } else {
14436        DiffHunkStatus::Modified
14437    }
14438}
14439
14440/// If select range has more than one line, we
14441/// just point the cursor to range.start.
14442fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14443    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14444        range
14445    } else {
14446        range.start..range.start
14447    }
14448}