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, EntityId, EventEmitter, FocusHandle,
   77    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   78    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   80    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   81    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion_provider::*;
   90pub use items::MAX_TAB_TITLE_LEN;
   91use itertools::Itertools;
   92use language::{
   93    language_settings::{self, all_language_settings, 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 = 1;
  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    file_header_size: u32,
  644    breadcrumb_header: Option<String>,
  645    focused_block: Option<FocusedBlock>,
  646    next_scroll_position: NextScrollCursorCenterTopBottom,
  647    addons: HashMap<TypeId, Box<dyn Addon>>,
  648    _scroll_cursor_center_top_bottom_task: Task<()>,
  649}
  650
  651#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  652enum NextScrollCursorCenterTopBottom {
  653    #[default]
  654    Center,
  655    Top,
  656    Bottom,
  657}
  658
  659impl NextScrollCursorCenterTopBottom {
  660    fn next(&self) -> Self {
  661        match self {
  662            Self::Center => Self::Top,
  663            Self::Top => Self::Bottom,
  664            Self::Bottom => Self::Center,
  665        }
  666    }
  667}
  668
  669#[derive(Clone)]
  670pub struct EditorSnapshot {
  671    pub mode: EditorMode,
  672    show_gutter: bool,
  673    show_line_numbers: Option<bool>,
  674    show_git_diff_gutter: Option<bool>,
  675    show_code_actions: Option<bool>,
  676    show_runnables: Option<bool>,
  677    git_blame_gutter_max_author_length: Option<usize>,
  678    pub display_snapshot: DisplaySnapshot,
  679    pub placeholder_text: Option<Arc<str>>,
  680    is_focused: bool,
  681    scroll_anchor: ScrollAnchor,
  682    ongoing_scroll: OngoingScroll,
  683    current_line_highlight: CurrentLineHighlight,
  684    gutter_hovered: bool,
  685}
  686
  687const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  688
  689#[derive(Default, Debug, Clone, Copy)]
  690pub struct GutterDimensions {
  691    pub left_padding: Pixels,
  692    pub right_padding: Pixels,
  693    pub width: Pixels,
  694    pub margin: Pixels,
  695    pub git_blame_entries_width: Option<Pixels>,
  696}
  697
  698impl GutterDimensions {
  699    /// The full width of the space taken up by the gutter.
  700    pub fn full_width(&self) -> Pixels {
  701        self.margin + self.width
  702    }
  703
  704    /// The width of the space reserved for the fold indicators,
  705    /// use alongside 'justify_end' and `gutter_width` to
  706    /// right align content with the line numbers
  707    pub fn fold_area_width(&self) -> Pixels {
  708        self.margin + self.right_padding
  709    }
  710}
  711
  712#[derive(Debug)]
  713pub struct RemoteSelection {
  714    pub replica_id: ReplicaId,
  715    pub selection: Selection<Anchor>,
  716    pub cursor_shape: CursorShape,
  717    pub peer_id: PeerId,
  718    pub line_mode: bool,
  719    pub participant_index: Option<ParticipantIndex>,
  720    pub user_name: Option<SharedString>,
  721}
  722
  723#[derive(Clone, Debug)]
  724struct SelectionHistoryEntry {
  725    selections: Arc<[Selection<Anchor>]>,
  726    select_next_state: Option<SelectNextState>,
  727    select_prev_state: Option<SelectNextState>,
  728    add_selections_state: Option<AddSelectionsState>,
  729}
  730
  731enum SelectionHistoryMode {
  732    Normal,
  733    Undoing,
  734    Redoing,
  735}
  736
  737#[derive(Clone, PartialEq, Eq, Hash)]
  738struct HoveredCursor {
  739    replica_id: u16,
  740    selection_id: usize,
  741}
  742
  743impl Default for SelectionHistoryMode {
  744    fn default() -> Self {
  745        Self::Normal
  746    }
  747}
  748
  749#[derive(Default)]
  750struct SelectionHistory {
  751    #[allow(clippy::type_complexity)]
  752    selections_by_transaction:
  753        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  754    mode: SelectionHistoryMode,
  755    undo_stack: VecDeque<SelectionHistoryEntry>,
  756    redo_stack: VecDeque<SelectionHistoryEntry>,
  757}
  758
  759impl SelectionHistory {
  760    fn insert_transaction(
  761        &mut self,
  762        transaction_id: TransactionId,
  763        selections: Arc<[Selection<Anchor>]>,
  764    ) {
  765        self.selections_by_transaction
  766            .insert(transaction_id, (selections, None));
  767    }
  768
  769    #[allow(clippy::type_complexity)]
  770    fn transaction(
  771        &self,
  772        transaction_id: TransactionId,
  773    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  774        self.selections_by_transaction.get(&transaction_id)
  775    }
  776
  777    #[allow(clippy::type_complexity)]
  778    fn transaction_mut(
  779        &mut self,
  780        transaction_id: TransactionId,
  781    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  782        self.selections_by_transaction.get_mut(&transaction_id)
  783    }
  784
  785    fn push(&mut self, entry: SelectionHistoryEntry) {
  786        if !entry.selections.is_empty() {
  787            match self.mode {
  788                SelectionHistoryMode::Normal => {
  789                    self.push_undo(entry);
  790                    self.redo_stack.clear();
  791                }
  792                SelectionHistoryMode::Undoing => self.push_redo(entry),
  793                SelectionHistoryMode::Redoing => self.push_undo(entry),
  794            }
  795        }
  796    }
  797
  798    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  799        if self
  800            .undo_stack
  801            .back()
  802            .map_or(true, |e| e.selections != entry.selections)
  803        {
  804            self.undo_stack.push_back(entry);
  805            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  806                self.undo_stack.pop_front();
  807            }
  808        }
  809    }
  810
  811    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  812        if self
  813            .redo_stack
  814            .back()
  815            .map_or(true, |e| e.selections != entry.selections)
  816        {
  817            self.redo_stack.push_back(entry);
  818            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  819                self.redo_stack.pop_front();
  820            }
  821        }
  822    }
  823}
  824
  825struct RowHighlight {
  826    index: usize,
  827    range: Range<Anchor>,
  828    color: Hsla,
  829    should_autoscroll: bool,
  830}
  831
  832#[derive(Clone, Debug)]
  833struct AddSelectionsState {
  834    above: bool,
  835    stack: Vec<usize>,
  836}
  837
  838#[derive(Clone)]
  839struct SelectNextState {
  840    query: AhoCorasick,
  841    wordwise: bool,
  842    done: bool,
  843}
  844
  845impl std::fmt::Debug for SelectNextState {
  846    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  847        f.debug_struct(std::any::type_name::<Self>())
  848            .field("wordwise", &self.wordwise)
  849            .field("done", &self.done)
  850            .finish()
  851    }
  852}
  853
  854#[derive(Debug)]
  855struct AutocloseRegion {
  856    selection_id: usize,
  857    range: Range<Anchor>,
  858    pair: BracketPair,
  859}
  860
  861#[derive(Debug)]
  862struct SnippetState {
  863    ranges: Vec<Vec<Range<Anchor>>>,
  864    active_index: usize,
  865}
  866
  867#[doc(hidden)]
  868pub struct RenameState {
  869    pub range: Range<Anchor>,
  870    pub old_name: Arc<str>,
  871    pub editor: View<Editor>,
  872    block_id: CustomBlockId,
  873}
  874
  875struct InvalidationStack<T>(Vec<T>);
  876
  877struct RegisteredInlineCompletionProvider {
  878    provider: Arc<dyn InlineCompletionProviderHandle>,
  879    _subscription: Subscription,
  880}
  881
  882enum ContextMenu {
  883    Completions(CompletionsMenu),
  884    CodeActions(CodeActionsMenu),
  885}
  886
  887impl ContextMenu {
  888    fn select_first(
  889        &mut self,
  890        provider: Option<&dyn CompletionProvider>,
  891        cx: &mut ViewContext<Editor>,
  892    ) -> bool {
  893        if self.visible() {
  894            match self {
  895                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  896                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  897            }
  898            true
  899        } else {
  900            false
  901        }
  902    }
  903
  904    fn select_prev(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_next(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_last(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn visible(&self) -> bool {
  953        match self {
  954            ContextMenu::Completions(menu) => menu.visible(),
  955            ContextMenu::CodeActions(menu) => menu.visible(),
  956        }
  957    }
  958
  959    fn render(
  960        &self,
  961        cursor_position: DisplayPoint,
  962        style: &EditorStyle,
  963        max_height: Pixels,
  964        workspace: Option<WeakView<Workspace>>,
  965        cx: &mut ViewContext<Editor>,
  966    ) -> (ContextMenuOrigin, AnyElement) {
  967        match self {
  968            ContextMenu::Completions(menu) => (
  969                ContextMenuOrigin::EditorPoint(cursor_position),
  970                menu.render(style, max_height, workspace, cx),
  971            ),
  972            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  973        }
  974    }
  975}
  976
  977enum ContextMenuOrigin {
  978    EditorPoint(DisplayPoint),
  979    GutterIndicator(DisplayRow),
  980}
  981
  982#[derive(Clone)]
  983struct CompletionsMenu {
  984    id: CompletionId,
  985    sort_completions: bool,
  986    initial_position: Anchor,
  987    buffer: Model<Buffer>,
  988    completions: Arc<RwLock<Box<[Completion]>>>,
  989    match_candidates: Arc<[StringMatchCandidate]>,
  990    matches: Arc<[StringMatch]>,
  991    selected_item: usize,
  992    scroll_handle: UniformListScrollHandle,
  993    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  994}
  995
  996impl CompletionsMenu {
  997    fn select_first(
  998        &mut self,
  999        provider: Option<&dyn CompletionProvider>,
 1000        cx: &mut ViewContext<Editor>,
 1001    ) {
 1002        self.selected_item = 0;
 1003        self.scroll_handle.scroll_to_item(self.selected_item);
 1004        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1005        cx.notify();
 1006    }
 1007
 1008    fn select_prev(
 1009        &mut self,
 1010        provider: Option<&dyn CompletionProvider>,
 1011        cx: &mut ViewContext<Editor>,
 1012    ) {
 1013        if self.selected_item > 0 {
 1014            self.selected_item -= 1;
 1015        } else {
 1016            self.selected_item = self.matches.len() - 1;
 1017        }
 1018        self.scroll_handle.scroll_to_item(self.selected_item);
 1019        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1020        cx.notify();
 1021    }
 1022
 1023    fn select_next(
 1024        &mut self,
 1025        provider: Option<&dyn CompletionProvider>,
 1026        cx: &mut ViewContext<Editor>,
 1027    ) {
 1028        if self.selected_item + 1 < self.matches.len() {
 1029            self.selected_item += 1;
 1030        } else {
 1031            self.selected_item = 0;
 1032        }
 1033        self.scroll_handle.scroll_to_item(self.selected_item);
 1034        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1035        cx.notify();
 1036    }
 1037
 1038    fn select_last(
 1039        &mut self,
 1040        provider: Option<&dyn CompletionProvider>,
 1041        cx: &mut ViewContext<Editor>,
 1042    ) {
 1043        self.selected_item = self.matches.len() - 1;
 1044        self.scroll_handle.scroll_to_item(self.selected_item);
 1045        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1046        cx.notify();
 1047    }
 1048
 1049    fn pre_resolve_completion_documentation(
 1050        buffer: Model<Buffer>,
 1051        completions: Arc<RwLock<Box<[Completion]>>>,
 1052        matches: Arc<[StringMatch]>,
 1053        editor: &Editor,
 1054        cx: &mut ViewContext<Editor>,
 1055    ) -> Task<()> {
 1056        let settings = EditorSettings::get_global(cx);
 1057        if !settings.show_completion_documentation {
 1058            return Task::ready(());
 1059        }
 1060
 1061        let Some(provider) = editor.completion_provider.as_ref() else {
 1062            return Task::ready(());
 1063        };
 1064
 1065        let resolve_task = provider.resolve_completions(
 1066            buffer,
 1067            matches.iter().map(|m| m.candidate_id).collect(),
 1068            completions.clone(),
 1069            cx,
 1070        );
 1071
 1072        cx.spawn(move |this, mut cx| async move {
 1073            if let Some(true) = resolve_task.await.log_err() {
 1074                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1075            }
 1076        })
 1077    }
 1078
 1079    fn attempt_resolve_selected_completion_documentation(
 1080        &mut self,
 1081        provider: Option<&dyn CompletionProvider>,
 1082        cx: &mut ViewContext<Editor>,
 1083    ) {
 1084        let settings = EditorSettings::get_global(cx);
 1085        if !settings.show_completion_documentation {
 1086            return;
 1087        }
 1088
 1089        let completion_index = self.matches[self.selected_item].candidate_id;
 1090        let Some(provider) = provider else {
 1091            return;
 1092        };
 1093
 1094        let resolve_task = provider.resolve_completions(
 1095            self.buffer.clone(),
 1096            vec![completion_index],
 1097            self.completions.clone(),
 1098            cx,
 1099        );
 1100
 1101        let delay_ms =
 1102            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1103        let delay = Duration::from_millis(delay_ms);
 1104
 1105        self.selected_completion_documentation_resolve_debounce
 1106            .lock()
 1107            .fire_new(delay, cx, |_, cx| {
 1108                cx.spawn(move |this, mut cx| async move {
 1109                    if let Some(true) = resolve_task.await.log_err() {
 1110                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1111                    }
 1112                })
 1113            });
 1114    }
 1115
 1116    fn visible(&self) -> bool {
 1117        !self.matches.is_empty()
 1118    }
 1119
 1120    fn render(
 1121        &self,
 1122        style: &EditorStyle,
 1123        max_height: Pixels,
 1124        workspace: Option<WeakView<Workspace>>,
 1125        cx: &mut ViewContext<Editor>,
 1126    ) -> AnyElement {
 1127        let settings = EditorSettings::get_global(cx);
 1128        let show_completion_documentation = settings.show_completion_documentation;
 1129
 1130        let widest_completion_ix = self
 1131            .matches
 1132            .iter()
 1133            .enumerate()
 1134            .max_by_key(|(_, mat)| {
 1135                let completions = self.completions.read();
 1136                let completion = &completions[mat.candidate_id];
 1137                let documentation = &completion.documentation;
 1138
 1139                let mut len = completion.label.text.chars().count();
 1140                if let Some(Documentation::SingleLine(text)) = documentation {
 1141                    if show_completion_documentation {
 1142                        len += text.chars().count();
 1143                    }
 1144                }
 1145
 1146                len
 1147            })
 1148            .map(|(ix, _)| ix);
 1149
 1150        let completions = self.completions.clone();
 1151        let matches = self.matches.clone();
 1152        let selected_item = self.selected_item;
 1153        let style = style.clone();
 1154
 1155        let multiline_docs = if show_completion_documentation {
 1156            let mat = &self.matches[selected_item];
 1157            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1158                Some(Documentation::MultiLinePlainText(text)) => {
 1159                    Some(div().child(SharedString::from(text.clone())))
 1160                }
 1161                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1162                    Some(div().child(render_parsed_markdown(
 1163                        "completions_markdown",
 1164                        parsed,
 1165                        &style,
 1166                        workspace,
 1167                        cx,
 1168                    )))
 1169                }
 1170                _ => None,
 1171            };
 1172            multiline_docs.map(|div| {
 1173                div.id("multiline_docs")
 1174                    .max_h(max_height)
 1175                    .flex_1()
 1176                    .px_1p5()
 1177                    .py_1()
 1178                    .min_w(px(260.))
 1179                    .max_w(px(640.))
 1180                    .w(px(500.))
 1181                    .overflow_y_scroll()
 1182                    .occlude()
 1183            })
 1184        } else {
 1185            None
 1186        };
 1187
 1188        let list = uniform_list(
 1189            cx.view().clone(),
 1190            "completions",
 1191            matches.len(),
 1192            move |_editor, range, cx| {
 1193                let start_ix = range.start;
 1194                let completions_guard = completions.read();
 1195
 1196                matches[range]
 1197                    .iter()
 1198                    .enumerate()
 1199                    .map(|(ix, mat)| {
 1200                        let item_ix = start_ix + ix;
 1201                        let candidate_id = mat.candidate_id;
 1202                        let completion = &completions_guard[candidate_id];
 1203
 1204                        let documentation = if show_completion_documentation {
 1205                            &completion.documentation
 1206                        } else {
 1207                            &None
 1208                        };
 1209
 1210                        let highlights = gpui::combine_highlights(
 1211                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1212                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1213                                |(range, mut highlight)| {
 1214                                    // Ignore font weight for syntax highlighting, as we'll use it
 1215                                    // for fuzzy matches.
 1216                                    highlight.font_weight = None;
 1217
 1218                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1219                                        highlight.strikethrough = Some(StrikethroughStyle {
 1220                                            thickness: 1.0.into(),
 1221                                            ..Default::default()
 1222                                        });
 1223                                        highlight.color = Some(cx.theme().colors().text_muted);
 1224                                    }
 1225
 1226                                    (range, highlight)
 1227                                },
 1228                            ),
 1229                        );
 1230                        let completion_label = StyledText::new(completion.label.text.clone())
 1231                            .with_highlights(&style.text, highlights);
 1232                        let documentation_label =
 1233                            if let Some(Documentation::SingleLine(text)) = documentation {
 1234                                if text.trim().is_empty() {
 1235                                    None
 1236                                } else {
 1237                                    Some(
 1238                                        Label::new(text.clone())
 1239                                            .ml_4()
 1240                                            .size(LabelSize::Small)
 1241                                            .color(Color::Muted),
 1242                                    )
 1243                                }
 1244                            } else {
 1245                                None
 1246                            };
 1247
 1248                        let color_swatch = completion
 1249                            .color()
 1250                            .map(|color| div().size_4().bg(color).rounded_sm());
 1251
 1252                        div().min_w(px(220.)).max_w(px(540.)).child(
 1253                            ListItem::new(mat.candidate_id)
 1254                                .inset(true)
 1255                                .selected(item_ix == selected_item)
 1256                                .on_click(cx.listener(move |editor, _event, cx| {
 1257                                    cx.stop_propagation();
 1258                                    if let Some(task) = editor.confirm_completion(
 1259                                        &ConfirmCompletion {
 1260                                            item_ix: Some(item_ix),
 1261                                        },
 1262                                        cx,
 1263                                    ) {
 1264                                        task.detach_and_log_err(cx)
 1265                                    }
 1266                                }))
 1267                                .start_slot::<Div>(color_swatch)
 1268                                .child(h_flex().overflow_hidden().child(completion_label))
 1269                                .end_slot::<Label>(documentation_label),
 1270                        )
 1271                    })
 1272                    .collect()
 1273            },
 1274        )
 1275        .occlude()
 1276        .max_h(max_height)
 1277        .track_scroll(self.scroll_handle.clone())
 1278        .with_width_from_item(widest_completion_ix)
 1279        .with_sizing_behavior(ListSizingBehavior::Infer);
 1280
 1281        Popover::new()
 1282            .child(list)
 1283            .when_some(multiline_docs, |popover, multiline_docs| {
 1284                popover.aside(multiline_docs)
 1285            })
 1286            .into_any_element()
 1287    }
 1288
 1289    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1290        let mut matches = if let Some(query) = query {
 1291            fuzzy::match_strings(
 1292                &self.match_candidates,
 1293                query,
 1294                query.chars().any(|c| c.is_uppercase()),
 1295                100,
 1296                &Default::default(),
 1297                executor,
 1298            )
 1299            .await
 1300        } else {
 1301            self.match_candidates
 1302                .iter()
 1303                .enumerate()
 1304                .map(|(candidate_id, candidate)| StringMatch {
 1305                    candidate_id,
 1306                    score: Default::default(),
 1307                    positions: Default::default(),
 1308                    string: candidate.string.clone(),
 1309                })
 1310                .collect()
 1311        };
 1312
 1313        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1314        if let Some(query) = query {
 1315            if let Some(query_start) = query.chars().next() {
 1316                matches.retain(|string_match| {
 1317                    split_words(&string_match.string).any(|word| {
 1318                        // Check that the first codepoint of the word as lowercase matches the first
 1319                        // codepoint of the query as lowercase
 1320                        word.chars()
 1321                            .flat_map(|codepoint| codepoint.to_lowercase())
 1322                            .zip(query_start.to_lowercase())
 1323                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1324                    })
 1325                });
 1326            }
 1327        }
 1328
 1329        let completions = self.completions.read();
 1330        if self.sort_completions {
 1331            matches.sort_unstable_by_key(|mat| {
 1332                // We do want to strike a balance here between what the language server tells us
 1333                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1334                // `Creat` and there is a local variable called `CreateComponent`).
 1335                // So what we do is: we bucket all matches into two buckets
 1336                // - Strong matches
 1337                // - Weak matches
 1338                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1339                // and the Weak matches are the rest.
 1340                //
 1341                // For the strong matches, we sort by the language-servers score first and for the weak
 1342                // matches, we prefer our fuzzy finder first.
 1343                //
 1344                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1345                // us into account when it's obviously a bad match.
 1346
 1347                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1348                enum MatchScore<'a> {
 1349                    Strong {
 1350                        sort_text: Option<&'a str>,
 1351                        score: Reverse<OrderedFloat<f64>>,
 1352                        sort_key: (usize, &'a str),
 1353                    },
 1354                    Weak {
 1355                        score: Reverse<OrderedFloat<f64>>,
 1356                        sort_text: Option<&'a str>,
 1357                        sort_key: (usize, &'a str),
 1358                    },
 1359                }
 1360
 1361                let completion = &completions[mat.candidate_id];
 1362                let sort_key = completion.sort_key();
 1363                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1364                let score = Reverse(OrderedFloat(mat.score));
 1365
 1366                if mat.score >= 0.2 {
 1367                    MatchScore::Strong {
 1368                        sort_text,
 1369                        score,
 1370                        sort_key,
 1371                    }
 1372                } else {
 1373                    MatchScore::Weak {
 1374                        score,
 1375                        sort_text,
 1376                        sort_key,
 1377                    }
 1378                }
 1379            });
 1380        }
 1381
 1382        for mat in &mut matches {
 1383            let completion = &completions[mat.candidate_id];
 1384            mat.string.clone_from(&completion.label.text);
 1385            for position in &mut mat.positions {
 1386                *position += completion.label.filter_range.start;
 1387            }
 1388        }
 1389        drop(completions);
 1390
 1391        self.matches = matches.into();
 1392        self.selected_item = 0;
 1393    }
 1394}
 1395
 1396struct AvailableCodeAction {
 1397    excerpt_id: ExcerptId,
 1398    action: CodeAction,
 1399    provider: Arc<dyn CodeActionProvider>,
 1400}
 1401
 1402#[derive(Clone)]
 1403struct CodeActionContents {
 1404    tasks: Option<Arc<ResolvedTasks>>,
 1405    actions: Option<Arc<[AvailableCodeAction]>>,
 1406}
 1407
 1408impl CodeActionContents {
 1409    fn len(&self) -> usize {
 1410        match (&self.tasks, &self.actions) {
 1411            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1412            (Some(tasks), None) => tasks.templates.len(),
 1413            (None, Some(actions)) => actions.len(),
 1414            (None, None) => 0,
 1415        }
 1416    }
 1417
 1418    fn is_empty(&self) -> bool {
 1419        match (&self.tasks, &self.actions) {
 1420            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1421            (Some(tasks), None) => tasks.templates.is_empty(),
 1422            (None, Some(actions)) => actions.is_empty(),
 1423            (None, None) => true,
 1424        }
 1425    }
 1426
 1427    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1428        self.tasks
 1429            .iter()
 1430            .flat_map(|tasks| {
 1431                tasks
 1432                    .templates
 1433                    .iter()
 1434                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1435            })
 1436            .chain(self.actions.iter().flat_map(|actions| {
 1437                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1438                    excerpt_id: available.excerpt_id,
 1439                    action: available.action.clone(),
 1440                    provider: available.provider.clone(),
 1441                })
 1442            }))
 1443    }
 1444    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1445        match (&self.tasks, &self.actions) {
 1446            (Some(tasks), Some(actions)) => {
 1447                if index < tasks.templates.len() {
 1448                    tasks
 1449                        .templates
 1450                        .get(index)
 1451                        .cloned()
 1452                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1453                } else {
 1454                    actions.get(index - tasks.templates.len()).map(|available| {
 1455                        CodeActionsItem::CodeAction {
 1456                            excerpt_id: available.excerpt_id,
 1457                            action: available.action.clone(),
 1458                            provider: available.provider.clone(),
 1459                        }
 1460                    })
 1461                }
 1462            }
 1463            (Some(tasks), None) => tasks
 1464                .templates
 1465                .get(index)
 1466                .cloned()
 1467                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1468            (None, Some(actions)) => {
 1469                actions
 1470                    .get(index)
 1471                    .map(|available| CodeActionsItem::CodeAction {
 1472                        excerpt_id: available.excerpt_id,
 1473                        action: available.action.clone(),
 1474                        provider: available.provider.clone(),
 1475                    })
 1476            }
 1477            (None, None) => None,
 1478        }
 1479    }
 1480}
 1481
 1482#[allow(clippy::large_enum_variant)]
 1483#[derive(Clone)]
 1484enum CodeActionsItem {
 1485    Task(TaskSourceKind, ResolvedTask),
 1486    CodeAction {
 1487        excerpt_id: ExcerptId,
 1488        action: CodeAction,
 1489        provider: Arc<dyn CodeActionProvider>,
 1490    },
 1491}
 1492
 1493impl CodeActionsItem {
 1494    fn as_task(&self) -> Option<&ResolvedTask> {
 1495        let Self::Task(_, task) = self else {
 1496            return None;
 1497        };
 1498        Some(task)
 1499    }
 1500    fn as_code_action(&self) -> Option<&CodeAction> {
 1501        let Self::CodeAction { action, .. } = self else {
 1502            return None;
 1503        };
 1504        Some(action)
 1505    }
 1506    fn label(&self) -> String {
 1507        match self {
 1508            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1509            Self::Task(_, task) => task.resolved_label.clone(),
 1510        }
 1511    }
 1512}
 1513
 1514struct CodeActionsMenu {
 1515    actions: CodeActionContents,
 1516    buffer: Model<Buffer>,
 1517    selected_item: usize,
 1518    scroll_handle: UniformListScrollHandle,
 1519    deployed_from_indicator: Option<DisplayRow>,
 1520}
 1521
 1522impl CodeActionsMenu {
 1523    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1524        self.selected_item = 0;
 1525        self.scroll_handle.scroll_to_item(self.selected_item);
 1526        cx.notify()
 1527    }
 1528
 1529    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1530        if self.selected_item > 0 {
 1531            self.selected_item -= 1;
 1532        } else {
 1533            self.selected_item = self.actions.len() - 1;
 1534        }
 1535        self.scroll_handle.scroll_to_item(self.selected_item);
 1536        cx.notify();
 1537    }
 1538
 1539    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1540        if self.selected_item + 1 < self.actions.len() {
 1541            self.selected_item += 1;
 1542        } else {
 1543            self.selected_item = 0;
 1544        }
 1545        self.scroll_handle.scroll_to_item(self.selected_item);
 1546        cx.notify();
 1547    }
 1548
 1549    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1550        self.selected_item = self.actions.len() - 1;
 1551        self.scroll_handle.scroll_to_item(self.selected_item);
 1552        cx.notify()
 1553    }
 1554
 1555    fn visible(&self) -> bool {
 1556        !self.actions.is_empty()
 1557    }
 1558
 1559    fn render(
 1560        &self,
 1561        cursor_position: DisplayPoint,
 1562        _style: &EditorStyle,
 1563        max_height: Pixels,
 1564        cx: &mut ViewContext<Editor>,
 1565    ) -> (ContextMenuOrigin, AnyElement) {
 1566        let actions = self.actions.clone();
 1567        let selected_item = self.selected_item;
 1568        let element = uniform_list(
 1569            cx.view().clone(),
 1570            "code_actions_menu",
 1571            self.actions.len(),
 1572            move |_this, range, cx| {
 1573                actions
 1574                    .iter()
 1575                    .skip(range.start)
 1576                    .take(range.end - range.start)
 1577                    .enumerate()
 1578                    .map(|(ix, action)| {
 1579                        let item_ix = range.start + ix;
 1580                        let selected = selected_item == item_ix;
 1581                        let colors = cx.theme().colors();
 1582                        div()
 1583                            .px_1()
 1584                            .rounded_md()
 1585                            .text_color(colors.text)
 1586                            .when(selected, |style| {
 1587                                style
 1588                                    .bg(colors.element_active)
 1589                                    .text_color(colors.text_accent)
 1590                            })
 1591                            .hover(|style| {
 1592                                style
 1593                                    .bg(colors.element_hover)
 1594                                    .text_color(colors.text_accent)
 1595                            })
 1596                            .whitespace_nowrap()
 1597                            .when_some(action.as_code_action(), |this, action| {
 1598                                this.on_mouse_down(
 1599                                    MouseButton::Left,
 1600                                    cx.listener(move |editor, _, cx| {
 1601                                        cx.stop_propagation();
 1602                                        if let Some(task) = editor.confirm_code_action(
 1603                                            &ConfirmCodeAction {
 1604                                                item_ix: Some(item_ix),
 1605                                            },
 1606                                            cx,
 1607                                        ) {
 1608                                            task.detach_and_log_err(cx)
 1609                                        }
 1610                                    }),
 1611                                )
 1612                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1613                                .child(SharedString::from(action.lsp_action.title.clone()))
 1614                            })
 1615                            .when_some(action.as_task(), |this, task| {
 1616                                this.on_mouse_down(
 1617                                    MouseButton::Left,
 1618                                    cx.listener(move |editor, _, cx| {
 1619                                        cx.stop_propagation();
 1620                                        if let Some(task) = editor.confirm_code_action(
 1621                                            &ConfirmCodeAction {
 1622                                                item_ix: Some(item_ix),
 1623                                            },
 1624                                            cx,
 1625                                        ) {
 1626                                            task.detach_and_log_err(cx)
 1627                                        }
 1628                                    }),
 1629                                )
 1630                                .child(SharedString::from(task.resolved_label.clone()))
 1631                            })
 1632                    })
 1633                    .collect()
 1634            },
 1635        )
 1636        .elevation_1(cx)
 1637        .p_1()
 1638        .max_h(max_height)
 1639        .occlude()
 1640        .track_scroll(self.scroll_handle.clone())
 1641        .with_width_from_item(
 1642            self.actions
 1643                .iter()
 1644                .enumerate()
 1645                .max_by_key(|(_, action)| match action {
 1646                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1647                    CodeActionsItem::CodeAction { action, .. } => {
 1648                        action.lsp_action.title.chars().count()
 1649                    }
 1650                })
 1651                .map(|(ix, _)| ix),
 1652        )
 1653        .with_sizing_behavior(ListSizingBehavior::Infer)
 1654        .into_any_element();
 1655
 1656        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1657            ContextMenuOrigin::GutterIndicator(row)
 1658        } else {
 1659            ContextMenuOrigin::EditorPoint(cursor_position)
 1660        };
 1661
 1662        (cursor_position, element)
 1663    }
 1664}
 1665
 1666#[derive(Debug)]
 1667struct ActiveDiagnosticGroup {
 1668    primary_range: Range<Anchor>,
 1669    primary_message: String,
 1670    group_id: usize,
 1671    blocks: HashMap<CustomBlockId, Diagnostic>,
 1672    is_valid: bool,
 1673}
 1674
 1675#[derive(Serialize, Deserialize, Clone, Debug)]
 1676pub struct ClipboardSelection {
 1677    pub len: usize,
 1678    pub is_entire_line: bool,
 1679    pub first_line_indent: u32,
 1680}
 1681
 1682#[derive(Debug)]
 1683pub(crate) struct NavigationData {
 1684    cursor_anchor: Anchor,
 1685    cursor_position: Point,
 1686    scroll_anchor: ScrollAnchor,
 1687    scroll_top_row: u32,
 1688}
 1689
 1690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1691pub enum GotoDefinitionKind {
 1692    Symbol,
 1693    Declaration,
 1694    Type,
 1695    Implementation,
 1696}
 1697
 1698#[derive(Debug, Clone)]
 1699enum InlayHintRefreshReason {
 1700    Toggle(bool),
 1701    SettingsChange(InlayHintSettings),
 1702    NewLinesShown,
 1703    BufferEdited(HashSet<Arc<Language>>),
 1704    RefreshRequested,
 1705    ExcerptsRemoved(Vec<ExcerptId>),
 1706}
 1707
 1708impl InlayHintRefreshReason {
 1709    fn description(&self) -> &'static str {
 1710        match self {
 1711            Self::Toggle(_) => "toggle",
 1712            Self::SettingsChange(_) => "settings change",
 1713            Self::NewLinesShown => "new lines shown",
 1714            Self::BufferEdited(_) => "buffer edited",
 1715            Self::RefreshRequested => "refresh requested",
 1716            Self::ExcerptsRemoved(_) => "excerpts removed",
 1717        }
 1718    }
 1719}
 1720
 1721pub(crate) struct FocusedBlock {
 1722    id: BlockId,
 1723    focus_handle: WeakFocusHandle,
 1724}
 1725
 1726impl Editor {
 1727    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1728        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1729        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1730        Self::new(
 1731            EditorMode::SingleLine { auto_width: false },
 1732            buffer,
 1733            None,
 1734            false,
 1735            cx,
 1736        )
 1737    }
 1738
 1739    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1740        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1741        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1742        Self::new(EditorMode::Full, buffer, None, false, cx)
 1743    }
 1744
 1745    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1746        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1747        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1748        Self::new(
 1749            EditorMode::SingleLine { auto_width: true },
 1750            buffer,
 1751            None,
 1752            false,
 1753            cx,
 1754        )
 1755    }
 1756
 1757    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1758        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1759        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1760        Self::new(
 1761            EditorMode::AutoHeight { max_lines },
 1762            buffer,
 1763            None,
 1764            false,
 1765            cx,
 1766        )
 1767    }
 1768
 1769    pub fn for_buffer(
 1770        buffer: Model<Buffer>,
 1771        project: Option<Model<Project>>,
 1772        cx: &mut ViewContext<Self>,
 1773    ) -> Self {
 1774        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1775        Self::new(EditorMode::Full, buffer, project, false, cx)
 1776    }
 1777
 1778    pub fn for_multibuffer(
 1779        buffer: Model<MultiBuffer>,
 1780        project: Option<Model<Project>>,
 1781        show_excerpt_controls: bool,
 1782        cx: &mut ViewContext<Self>,
 1783    ) -> Self {
 1784        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1785    }
 1786
 1787    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1788        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1789        let mut clone = Self::new(
 1790            self.mode,
 1791            self.buffer.clone(),
 1792            self.project.clone(),
 1793            show_excerpt_controls,
 1794            cx,
 1795        );
 1796        self.display_map.update(cx, |display_map, cx| {
 1797            let snapshot = display_map.snapshot(cx);
 1798            clone.display_map.update(cx, |display_map, cx| {
 1799                display_map.set_state(&snapshot, cx);
 1800            });
 1801        });
 1802        clone.selections.clone_state(&self.selections);
 1803        clone.scroll_manager.clone_state(&self.scroll_manager);
 1804        clone.searchable = self.searchable;
 1805        clone
 1806    }
 1807
 1808    pub fn new(
 1809        mode: EditorMode,
 1810        buffer: Model<MultiBuffer>,
 1811        project: Option<Model<Project>>,
 1812        show_excerpt_controls: bool,
 1813        cx: &mut ViewContext<Self>,
 1814    ) -> Self {
 1815        let style = cx.text_style();
 1816        let font_size = style.font_size.to_pixels(cx.rem_size());
 1817        let editor = cx.view().downgrade();
 1818        let fold_placeholder = FoldPlaceholder {
 1819            constrain_width: true,
 1820            render: Arc::new(move |fold_id, fold_range, cx| {
 1821                let editor = editor.clone();
 1822                div()
 1823                    .id(fold_id)
 1824                    .bg(cx.theme().colors().ghost_element_background)
 1825                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1826                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1827                    .rounded_sm()
 1828                    .size_full()
 1829                    .cursor_pointer()
 1830                    .child("")
 1831                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1832                    .on_click(move |_, cx| {
 1833                        editor
 1834                            .update(cx, |editor, cx| {
 1835                                editor.unfold_ranges(
 1836                                    [fold_range.start..fold_range.end],
 1837                                    true,
 1838                                    false,
 1839                                    cx,
 1840                                );
 1841                                cx.stop_propagation();
 1842                            })
 1843                            .ok();
 1844                    })
 1845                    .into_any()
 1846            }),
 1847            merge_adjacent: true,
 1848        };
 1849        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1850        let display_map = cx.new_model(|cx| {
 1851            DisplayMap::new(
 1852                buffer.clone(),
 1853                style.font(),
 1854                font_size,
 1855                None,
 1856                show_excerpt_controls,
 1857                file_header_size,
 1858                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1859                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1860                fold_placeholder,
 1861                cx,
 1862            )
 1863        });
 1864
 1865        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1866
 1867        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1868
 1869        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1870            .then(|| language_settings::SoftWrap::None);
 1871
 1872        let mut project_subscriptions = Vec::new();
 1873        if mode == EditorMode::Full {
 1874            if let Some(project) = project.as_ref() {
 1875                if buffer.read(cx).is_singleton() {
 1876                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1877                        cx.emit(EditorEvent::TitleChanged);
 1878                    }));
 1879                }
 1880                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1881                    if let project::Event::RefreshInlayHints = event {
 1882                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1883                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1884                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1885                            let focus_handle = editor.focus_handle(cx);
 1886                            if focus_handle.is_focused(cx) {
 1887                                let snapshot = buffer.read(cx).snapshot();
 1888                                for (range, snippet) in snippet_edits {
 1889                                    let editor_range =
 1890                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1891                                    editor
 1892                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1893                                        .ok();
 1894                                }
 1895                            }
 1896                        }
 1897                    }
 1898                }));
 1899                if let Some(task_inventory) = project
 1900                    .read(cx)
 1901                    .task_store()
 1902                    .read(cx)
 1903                    .task_inventory()
 1904                    .cloned()
 1905                {
 1906                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1907                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1908                    }));
 1909                }
 1910            }
 1911        }
 1912
 1913        let inlay_hint_settings = inlay_hint_settings(
 1914            selections.newest_anchor().head(),
 1915            &buffer.read(cx).snapshot(cx),
 1916            cx,
 1917        );
 1918        let focus_handle = cx.focus_handle();
 1919        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1920        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1921            .detach();
 1922        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1923            .detach();
 1924        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1925
 1926        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1927            Some(false)
 1928        } else {
 1929            None
 1930        };
 1931
 1932        let mut code_action_providers = Vec::new();
 1933        if let Some(project) = project.clone() {
 1934            code_action_providers.push(Arc::new(project) as Arc<_>);
 1935        }
 1936
 1937        let mut this = Self {
 1938            focus_handle,
 1939            show_cursor_when_unfocused: false,
 1940            last_focused_descendant: None,
 1941            buffer: buffer.clone(),
 1942            display_map: display_map.clone(),
 1943            selections,
 1944            scroll_manager: ScrollManager::new(cx),
 1945            columnar_selection_tail: None,
 1946            add_selections_state: None,
 1947            select_next_state: None,
 1948            select_prev_state: None,
 1949            selection_history: Default::default(),
 1950            autoclose_regions: Default::default(),
 1951            snippet_stack: Default::default(),
 1952            select_larger_syntax_node_stack: Vec::new(),
 1953            ime_transaction: Default::default(),
 1954            active_diagnostics: None,
 1955            soft_wrap_mode_override,
 1956            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1957            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1958            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1959            project,
 1960            blink_manager: blink_manager.clone(),
 1961            show_local_selections: true,
 1962            mode,
 1963            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1964            show_gutter: mode == EditorMode::Full,
 1965            show_line_numbers: None,
 1966            use_relative_line_numbers: None,
 1967            show_git_diff_gutter: None,
 1968            show_code_actions: None,
 1969            show_runnables: None,
 1970            show_wrap_guides: None,
 1971            show_indent_guides,
 1972            placeholder_text: None,
 1973            highlight_order: 0,
 1974            highlighted_rows: HashMap::default(),
 1975            background_highlights: Default::default(),
 1976            gutter_highlights: TreeMap::default(),
 1977            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1978            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1979            nav_history: None,
 1980            context_menu: RwLock::new(None),
 1981            mouse_context_menu: None,
 1982            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1983            completion_tasks: Default::default(),
 1984            signature_help_state: SignatureHelpState::default(),
 1985            auto_signature_help: None,
 1986            find_all_references_task_sources: Vec::new(),
 1987            next_completion_id: 0,
 1988            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1989            next_inlay_id: 0,
 1990            code_action_providers,
 1991            available_code_actions: Default::default(),
 1992            code_actions_task: Default::default(),
 1993            document_highlights_task: Default::default(),
 1994            linked_editing_range_task: Default::default(),
 1995            pending_rename: Default::default(),
 1996            searchable: true,
 1997            cursor_shape: EditorSettings::get_global(cx)
 1998                .cursor_shape
 1999                .unwrap_or_default(),
 2000            current_line_highlight: None,
 2001            autoindent_mode: Some(AutoindentMode::EachLine),
 2002            collapse_matches: false,
 2003            workspace: None,
 2004            input_enabled: true,
 2005            use_modal_editing: mode == EditorMode::Full,
 2006            read_only: false,
 2007            use_autoclose: true,
 2008            use_auto_surround: true,
 2009            auto_replace_emoji_shortcode: false,
 2010            leader_peer_id: None,
 2011            remote_id: None,
 2012            hover_state: Default::default(),
 2013            hovered_link_state: Default::default(),
 2014            inline_completion_provider: None,
 2015            active_inline_completion: None,
 2016            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2017            expanded_hunks: ExpandedHunks::default(),
 2018            gutter_hovered: false,
 2019            pixel_position_of_newest_cursor: None,
 2020            last_bounds: None,
 2021            expect_bounds_change: None,
 2022            gutter_dimensions: GutterDimensions::default(),
 2023            style: None,
 2024            show_cursor_names: false,
 2025            hovered_cursors: Default::default(),
 2026            next_editor_action_id: EditorActionId::default(),
 2027            editor_actions: Rc::default(),
 2028            show_inline_completions_override: None,
 2029            enable_inline_completions: true,
 2030            custom_context_menu: None,
 2031            show_git_blame_gutter: false,
 2032            show_git_blame_inline: false,
 2033            show_selection_menu: None,
 2034            show_git_blame_inline_delay_task: None,
 2035            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2036            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2037                .session
 2038                .restore_unsaved_buffers,
 2039            blame: None,
 2040            blame_subscription: None,
 2041            file_header_size,
 2042            tasks: Default::default(),
 2043            _subscriptions: vec![
 2044                cx.observe(&buffer, Self::on_buffer_changed),
 2045                cx.subscribe(&buffer, Self::on_buffer_event),
 2046                cx.observe(&display_map, Self::on_display_map_changed),
 2047                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2048                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2049                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2050                cx.observe_window_activation(|editor, cx| {
 2051                    let active = cx.is_window_active();
 2052                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2053                        if active {
 2054                            blink_manager.enable(cx);
 2055                        } else {
 2056                            blink_manager.disable(cx);
 2057                        }
 2058                    });
 2059                }),
 2060            ],
 2061            tasks_update_task: None,
 2062            linked_edit_ranges: Default::default(),
 2063            previous_search_ranges: None,
 2064            breadcrumb_header: None,
 2065            focused_block: None,
 2066            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2067            addons: HashMap::default(),
 2068            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2069        };
 2070        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2071        this._subscriptions.extend(project_subscriptions);
 2072
 2073        this.end_selection(cx);
 2074        this.scroll_manager.show_scrollbar(cx);
 2075
 2076        if mode == EditorMode::Full {
 2077            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2078            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2079
 2080            if this.git_blame_inline_enabled {
 2081                this.git_blame_inline_enabled = true;
 2082                this.start_git_blame_inline(false, cx);
 2083            }
 2084        }
 2085
 2086        this.report_editor_event("open", None, cx);
 2087        this
 2088    }
 2089
 2090    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2091        self.mouse_context_menu
 2092            .as_ref()
 2093            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2094    }
 2095
 2096    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2097        let mut key_context = KeyContext::new_with_defaults();
 2098        key_context.add("Editor");
 2099        let mode = match self.mode {
 2100            EditorMode::SingleLine { .. } => "single_line",
 2101            EditorMode::AutoHeight { .. } => "auto_height",
 2102            EditorMode::Full => "full",
 2103        };
 2104
 2105        if EditorSettings::jupyter_enabled(cx) {
 2106            key_context.add("jupyter");
 2107        }
 2108
 2109        key_context.set("mode", mode);
 2110        if self.pending_rename.is_some() {
 2111            key_context.add("renaming");
 2112        }
 2113        if self.context_menu_visible() {
 2114            match self.context_menu.read().as_ref() {
 2115                Some(ContextMenu::Completions(_)) => {
 2116                    key_context.add("menu");
 2117                    key_context.add("showing_completions")
 2118                }
 2119                Some(ContextMenu::CodeActions(_)) => {
 2120                    key_context.add("menu");
 2121                    key_context.add("showing_code_actions")
 2122                }
 2123                None => {}
 2124            }
 2125        }
 2126
 2127        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2128        if !self.focus_handle(cx).contains_focused(cx)
 2129            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2130        {
 2131            for addon in self.addons.values() {
 2132                addon.extend_key_context(&mut key_context, cx)
 2133            }
 2134        }
 2135
 2136        if let Some(extension) = self
 2137            .buffer
 2138            .read(cx)
 2139            .as_singleton()
 2140            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2141        {
 2142            key_context.set("extension", extension.to_string());
 2143        }
 2144
 2145        if self.has_active_inline_completion(cx) {
 2146            key_context.add("copilot_suggestion");
 2147            key_context.add("inline_completion");
 2148        }
 2149
 2150        key_context
 2151    }
 2152
 2153    pub fn new_file(
 2154        workspace: &mut Workspace,
 2155        _: &workspace::NewFile,
 2156        cx: &mut ViewContext<Workspace>,
 2157    ) {
 2158        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2159            "Failed to create buffer",
 2160            cx,
 2161            |e, _| match e.error_code() {
 2162                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2163                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2164                e.error_tag("required").unwrap_or("the latest version")
 2165            )),
 2166                _ => None,
 2167            },
 2168        );
 2169    }
 2170
 2171    pub fn new_in_workspace(
 2172        workspace: &mut Workspace,
 2173        cx: &mut ViewContext<Workspace>,
 2174    ) -> Task<Result<View<Editor>>> {
 2175        let project = workspace.project().clone();
 2176        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2177
 2178        cx.spawn(|workspace, mut cx| async move {
 2179            let buffer = create.await?;
 2180            workspace.update(&mut cx, |workspace, cx| {
 2181                let editor =
 2182                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2183                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2184                editor
 2185            })
 2186        })
 2187    }
 2188
 2189    fn new_file_vertical(
 2190        workspace: &mut Workspace,
 2191        _: &workspace::NewFileSplitVertical,
 2192        cx: &mut ViewContext<Workspace>,
 2193    ) {
 2194        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2195    }
 2196
 2197    fn new_file_horizontal(
 2198        workspace: &mut Workspace,
 2199        _: &workspace::NewFileSplitHorizontal,
 2200        cx: &mut ViewContext<Workspace>,
 2201    ) {
 2202        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2203    }
 2204
 2205    fn new_file_in_direction(
 2206        workspace: &mut Workspace,
 2207        direction: SplitDirection,
 2208        cx: &mut ViewContext<Workspace>,
 2209    ) {
 2210        let project = workspace.project().clone();
 2211        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2212
 2213        cx.spawn(|workspace, mut cx| async move {
 2214            let buffer = create.await?;
 2215            workspace.update(&mut cx, move |workspace, cx| {
 2216                workspace.split_item(
 2217                    direction,
 2218                    Box::new(
 2219                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2220                    ),
 2221                    cx,
 2222                )
 2223            })?;
 2224            anyhow::Ok(())
 2225        })
 2226        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2227            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2228                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2229                e.error_tag("required").unwrap_or("the latest version")
 2230            )),
 2231            _ => None,
 2232        });
 2233    }
 2234
 2235    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2236        self.leader_peer_id
 2237    }
 2238
 2239    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2240        &self.buffer
 2241    }
 2242
 2243    pub fn workspace(&self) -> Option<View<Workspace>> {
 2244        self.workspace.as_ref()?.0.upgrade()
 2245    }
 2246
 2247    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2248        self.buffer().read(cx).title(cx)
 2249    }
 2250
 2251    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2252        let git_blame_gutter_max_author_length = self
 2253            .render_git_blame_gutter(cx)
 2254            .then(|| {
 2255                if let Some(blame) = self.blame.as_ref() {
 2256                    let max_author_length =
 2257                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2258                    Some(max_author_length)
 2259                } else {
 2260                    None
 2261                }
 2262            })
 2263            .flatten();
 2264
 2265        EditorSnapshot {
 2266            mode: self.mode,
 2267            show_gutter: self.show_gutter,
 2268            show_line_numbers: self.show_line_numbers,
 2269            show_git_diff_gutter: self.show_git_diff_gutter,
 2270            show_code_actions: self.show_code_actions,
 2271            show_runnables: self.show_runnables,
 2272            git_blame_gutter_max_author_length,
 2273            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2274            scroll_anchor: self.scroll_manager.anchor(),
 2275            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2276            placeholder_text: self.placeholder_text.clone(),
 2277            is_focused: self.focus_handle.is_focused(cx),
 2278            current_line_highlight: self
 2279                .current_line_highlight
 2280                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2281            gutter_hovered: self.gutter_hovered,
 2282        }
 2283    }
 2284
 2285    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2286        self.buffer.read(cx).language_at(point, cx)
 2287    }
 2288
 2289    pub fn file_at<T: ToOffset>(
 2290        &self,
 2291        point: T,
 2292        cx: &AppContext,
 2293    ) -> Option<Arc<dyn language::File>> {
 2294        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2295    }
 2296
 2297    pub fn active_excerpt(
 2298        &self,
 2299        cx: &AppContext,
 2300    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2301        self.buffer
 2302            .read(cx)
 2303            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2304    }
 2305
 2306    pub fn mode(&self) -> EditorMode {
 2307        self.mode
 2308    }
 2309
 2310    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2311        self.collaboration_hub.as_deref()
 2312    }
 2313
 2314    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2315        self.collaboration_hub = Some(hub);
 2316    }
 2317
 2318    pub fn set_custom_context_menu(
 2319        &mut self,
 2320        f: impl 'static
 2321            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2322    ) {
 2323        self.custom_context_menu = Some(Box::new(f))
 2324    }
 2325
 2326    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2327        self.completion_provider = provider;
 2328    }
 2329
 2330    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2331        self.semantics_provider.clone()
 2332    }
 2333
 2334    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2335        self.semantics_provider = provider;
 2336    }
 2337
 2338    pub fn set_inline_completion_provider<T>(
 2339        &mut self,
 2340        provider: Option<Model<T>>,
 2341        cx: &mut ViewContext<Self>,
 2342    ) where
 2343        T: InlineCompletionProvider,
 2344    {
 2345        self.inline_completion_provider =
 2346            provider.map(|provider| RegisteredInlineCompletionProvider {
 2347                _subscription: cx.observe(&provider, |this, _, cx| {
 2348                    if this.focus_handle.is_focused(cx) {
 2349                        this.update_visible_inline_completion(cx);
 2350                    }
 2351                }),
 2352                provider: Arc::new(provider),
 2353            });
 2354        self.refresh_inline_completion(false, false, cx);
 2355    }
 2356
 2357    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2358        self.placeholder_text.as_deref()
 2359    }
 2360
 2361    pub fn set_placeholder_text(
 2362        &mut self,
 2363        placeholder_text: impl Into<Arc<str>>,
 2364        cx: &mut ViewContext<Self>,
 2365    ) {
 2366        let placeholder_text = Some(placeholder_text.into());
 2367        if self.placeholder_text != placeholder_text {
 2368            self.placeholder_text = placeholder_text;
 2369            cx.notify();
 2370        }
 2371    }
 2372
 2373    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2374        self.cursor_shape = cursor_shape;
 2375
 2376        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2377        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2378
 2379        cx.notify();
 2380    }
 2381
 2382    pub fn set_current_line_highlight(
 2383        &mut self,
 2384        current_line_highlight: Option<CurrentLineHighlight>,
 2385    ) {
 2386        self.current_line_highlight = current_line_highlight;
 2387    }
 2388
 2389    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2390        self.collapse_matches = collapse_matches;
 2391    }
 2392
 2393    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2394        if self.collapse_matches {
 2395            return range.start..range.start;
 2396        }
 2397        range.clone()
 2398    }
 2399
 2400    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2401        if self.display_map.read(cx).clip_at_line_ends != clip {
 2402            self.display_map
 2403                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2404        }
 2405    }
 2406
 2407    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2408        self.input_enabled = input_enabled;
 2409    }
 2410
 2411    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2412        self.enable_inline_completions = enabled;
 2413    }
 2414
 2415    pub fn set_autoindent(&mut self, autoindent: bool) {
 2416        if autoindent {
 2417            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2418        } else {
 2419            self.autoindent_mode = None;
 2420        }
 2421    }
 2422
 2423    pub fn read_only(&self, cx: &AppContext) -> bool {
 2424        self.read_only || self.buffer.read(cx).read_only()
 2425    }
 2426
 2427    pub fn set_read_only(&mut self, read_only: bool) {
 2428        self.read_only = read_only;
 2429    }
 2430
 2431    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2432        self.use_autoclose = autoclose;
 2433    }
 2434
 2435    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2436        self.use_auto_surround = auto_surround;
 2437    }
 2438
 2439    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2440        self.auto_replace_emoji_shortcode = auto_replace;
 2441    }
 2442
 2443    pub fn toggle_inline_completions(
 2444        &mut self,
 2445        _: &ToggleInlineCompletions,
 2446        cx: &mut ViewContext<Self>,
 2447    ) {
 2448        if self.show_inline_completions_override.is_some() {
 2449            self.set_show_inline_completions(None, cx);
 2450        } else {
 2451            let cursor = self.selections.newest_anchor().head();
 2452            if let Some((buffer, cursor_buffer_position)) =
 2453                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2454            {
 2455                let show_inline_completions =
 2456                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2457                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2458            }
 2459        }
 2460    }
 2461
 2462    pub fn set_show_inline_completions(
 2463        &mut self,
 2464        show_inline_completions: Option<bool>,
 2465        cx: &mut ViewContext<Self>,
 2466    ) {
 2467        self.show_inline_completions_override = show_inline_completions;
 2468        self.refresh_inline_completion(false, true, cx);
 2469    }
 2470
 2471    fn should_show_inline_completions(
 2472        &self,
 2473        buffer: &Model<Buffer>,
 2474        buffer_position: language::Anchor,
 2475        cx: &AppContext,
 2476    ) -> bool {
 2477        if let Some(provider) = self.inline_completion_provider() {
 2478            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2479                show_inline_completions
 2480            } else {
 2481                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2482            }
 2483        } else {
 2484            false
 2485        }
 2486    }
 2487
 2488    pub fn set_use_modal_editing(&mut self, to: bool) {
 2489        self.use_modal_editing = to;
 2490    }
 2491
 2492    pub fn use_modal_editing(&self) -> bool {
 2493        self.use_modal_editing
 2494    }
 2495
 2496    fn selections_did_change(
 2497        &mut self,
 2498        local: bool,
 2499        old_cursor_position: &Anchor,
 2500        show_completions: bool,
 2501        cx: &mut ViewContext<Self>,
 2502    ) {
 2503        cx.invalidate_character_coordinates();
 2504
 2505        // Copy selections to primary selection buffer
 2506        #[cfg(target_os = "linux")]
 2507        if local {
 2508            let selections = self.selections.all::<usize>(cx);
 2509            let buffer_handle = self.buffer.read(cx).read(cx);
 2510
 2511            let mut text = String::new();
 2512            for (index, selection) in selections.iter().enumerate() {
 2513                let text_for_selection = buffer_handle
 2514                    .text_for_range(selection.start..selection.end)
 2515                    .collect::<String>();
 2516
 2517                text.push_str(&text_for_selection);
 2518                if index != selections.len() - 1 {
 2519                    text.push('\n');
 2520                }
 2521            }
 2522
 2523            if !text.is_empty() {
 2524                cx.write_to_primary(ClipboardItem::new_string(text));
 2525            }
 2526        }
 2527
 2528        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2529            self.buffer.update(cx, |buffer, cx| {
 2530                buffer.set_active_selections(
 2531                    &self.selections.disjoint_anchors(),
 2532                    self.selections.line_mode,
 2533                    self.cursor_shape,
 2534                    cx,
 2535                )
 2536            });
 2537        }
 2538        let display_map = self
 2539            .display_map
 2540            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2541        let buffer = &display_map.buffer_snapshot;
 2542        self.add_selections_state = None;
 2543        self.select_next_state = None;
 2544        self.select_prev_state = None;
 2545        self.select_larger_syntax_node_stack.clear();
 2546        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2547        self.snippet_stack
 2548            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2549        self.take_rename(false, cx);
 2550
 2551        let new_cursor_position = self.selections.newest_anchor().head();
 2552
 2553        self.push_to_nav_history(
 2554            *old_cursor_position,
 2555            Some(new_cursor_position.to_point(buffer)),
 2556            cx,
 2557        );
 2558
 2559        if local {
 2560            let new_cursor_position = self.selections.newest_anchor().head();
 2561            let mut context_menu = self.context_menu.write();
 2562            let completion_menu = match context_menu.as_ref() {
 2563                Some(ContextMenu::Completions(menu)) => Some(menu),
 2564
 2565                _ => {
 2566                    *context_menu = None;
 2567                    None
 2568                }
 2569            };
 2570
 2571            if let Some(completion_menu) = completion_menu {
 2572                let cursor_position = new_cursor_position.to_offset(buffer);
 2573                let (word_range, kind) =
 2574                    buffer.surrounding_word(completion_menu.initial_position, true);
 2575                if kind == Some(CharKind::Word)
 2576                    && word_range.to_inclusive().contains(&cursor_position)
 2577                {
 2578                    let mut completion_menu = completion_menu.clone();
 2579                    drop(context_menu);
 2580
 2581                    let query = Self::completion_query(buffer, cursor_position);
 2582                    cx.spawn(move |this, mut cx| async move {
 2583                        completion_menu
 2584                            .filter(query.as_deref(), cx.background_executor().clone())
 2585                            .await;
 2586
 2587                        this.update(&mut cx, |this, cx| {
 2588                            let mut context_menu = this.context_menu.write();
 2589                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2590                                return;
 2591                            };
 2592
 2593                            if menu.id > completion_menu.id {
 2594                                return;
 2595                            }
 2596
 2597                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2598                            drop(context_menu);
 2599                            cx.notify();
 2600                        })
 2601                    })
 2602                    .detach();
 2603
 2604                    if show_completions {
 2605                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2606                    }
 2607                } else {
 2608                    drop(context_menu);
 2609                    self.hide_context_menu(cx);
 2610                }
 2611            } else {
 2612                drop(context_menu);
 2613            }
 2614
 2615            hide_hover(self, cx);
 2616
 2617            if old_cursor_position.to_display_point(&display_map).row()
 2618                != new_cursor_position.to_display_point(&display_map).row()
 2619            {
 2620                self.available_code_actions.take();
 2621            }
 2622            self.refresh_code_actions(cx);
 2623            self.refresh_document_highlights(cx);
 2624            refresh_matching_bracket_highlights(self, cx);
 2625            self.discard_inline_completion(false, cx);
 2626            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2627            if self.git_blame_inline_enabled {
 2628                self.start_inline_blame_timer(cx);
 2629            }
 2630        }
 2631
 2632        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2633        cx.emit(EditorEvent::SelectionsChanged { local });
 2634
 2635        if self.selections.disjoint_anchors().len() == 1 {
 2636            cx.emit(SearchEvent::ActiveMatchChanged)
 2637        }
 2638        cx.notify();
 2639    }
 2640
 2641    pub fn change_selections<R>(
 2642        &mut self,
 2643        autoscroll: Option<Autoscroll>,
 2644        cx: &mut ViewContext<Self>,
 2645        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2646    ) -> R {
 2647        self.change_selections_inner(autoscroll, true, cx, change)
 2648    }
 2649
 2650    pub fn change_selections_inner<R>(
 2651        &mut self,
 2652        autoscroll: Option<Autoscroll>,
 2653        request_completions: bool,
 2654        cx: &mut ViewContext<Self>,
 2655        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2656    ) -> R {
 2657        let old_cursor_position = self.selections.newest_anchor().head();
 2658        self.push_to_selection_history();
 2659
 2660        let (changed, result) = self.selections.change_with(cx, change);
 2661
 2662        if changed {
 2663            if let Some(autoscroll) = autoscroll {
 2664                self.request_autoscroll(autoscroll, cx);
 2665            }
 2666            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2667
 2668            if self.should_open_signature_help_automatically(
 2669                &old_cursor_position,
 2670                self.signature_help_state.backspace_pressed(),
 2671                cx,
 2672            ) {
 2673                self.show_signature_help(&ShowSignatureHelp, cx);
 2674            }
 2675            self.signature_help_state.set_backspace_pressed(false);
 2676        }
 2677
 2678        result
 2679    }
 2680
 2681    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2682    where
 2683        I: IntoIterator<Item = (Range<S>, T)>,
 2684        S: ToOffset,
 2685        T: Into<Arc<str>>,
 2686    {
 2687        if self.read_only(cx) {
 2688            return;
 2689        }
 2690
 2691        self.buffer
 2692            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2693    }
 2694
 2695    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2696    where
 2697        I: IntoIterator<Item = (Range<S>, T)>,
 2698        S: ToOffset,
 2699        T: Into<Arc<str>>,
 2700    {
 2701        if self.read_only(cx) {
 2702            return;
 2703        }
 2704
 2705        self.buffer.update(cx, |buffer, cx| {
 2706            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2707        });
 2708    }
 2709
 2710    pub fn edit_with_block_indent<I, S, T>(
 2711        &mut self,
 2712        edits: I,
 2713        original_indent_columns: Vec<u32>,
 2714        cx: &mut ViewContext<Self>,
 2715    ) where
 2716        I: IntoIterator<Item = (Range<S>, T)>,
 2717        S: ToOffset,
 2718        T: Into<Arc<str>>,
 2719    {
 2720        if self.read_only(cx) {
 2721            return;
 2722        }
 2723
 2724        self.buffer.update(cx, |buffer, cx| {
 2725            buffer.edit(
 2726                edits,
 2727                Some(AutoindentMode::Block {
 2728                    original_indent_columns,
 2729                }),
 2730                cx,
 2731            )
 2732        });
 2733    }
 2734
 2735    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2736        self.hide_context_menu(cx);
 2737
 2738        match phase {
 2739            SelectPhase::Begin {
 2740                position,
 2741                add,
 2742                click_count,
 2743            } => self.begin_selection(position, add, click_count, cx),
 2744            SelectPhase::BeginColumnar {
 2745                position,
 2746                goal_column,
 2747                reset,
 2748            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2749            SelectPhase::Extend {
 2750                position,
 2751                click_count,
 2752            } => self.extend_selection(position, click_count, cx),
 2753            SelectPhase::Update {
 2754                position,
 2755                goal_column,
 2756                scroll_delta,
 2757            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2758            SelectPhase::End => self.end_selection(cx),
 2759        }
 2760    }
 2761
 2762    fn extend_selection(
 2763        &mut self,
 2764        position: DisplayPoint,
 2765        click_count: usize,
 2766        cx: &mut ViewContext<Self>,
 2767    ) {
 2768        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2769        let tail = self.selections.newest::<usize>(cx).tail();
 2770        self.begin_selection(position, false, click_count, cx);
 2771
 2772        let position = position.to_offset(&display_map, Bias::Left);
 2773        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2774
 2775        let mut pending_selection = self
 2776            .selections
 2777            .pending_anchor()
 2778            .expect("extend_selection not called with pending selection");
 2779        if position >= tail {
 2780            pending_selection.start = tail_anchor;
 2781        } else {
 2782            pending_selection.end = tail_anchor;
 2783            pending_selection.reversed = true;
 2784        }
 2785
 2786        let mut pending_mode = self.selections.pending_mode().unwrap();
 2787        match &mut pending_mode {
 2788            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2789            _ => {}
 2790        }
 2791
 2792        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2793            s.set_pending(pending_selection, pending_mode)
 2794        });
 2795    }
 2796
 2797    fn begin_selection(
 2798        &mut self,
 2799        position: DisplayPoint,
 2800        add: bool,
 2801        click_count: usize,
 2802        cx: &mut ViewContext<Self>,
 2803    ) {
 2804        if !self.focus_handle.is_focused(cx) {
 2805            self.last_focused_descendant = None;
 2806            cx.focus(&self.focus_handle);
 2807        }
 2808
 2809        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2810        let buffer = &display_map.buffer_snapshot;
 2811        let newest_selection = self.selections.newest_anchor().clone();
 2812        let position = display_map.clip_point(position, Bias::Left);
 2813
 2814        let start;
 2815        let end;
 2816        let mode;
 2817        let auto_scroll;
 2818        match click_count {
 2819            1 => {
 2820                start = buffer.anchor_before(position.to_point(&display_map));
 2821                end = start;
 2822                mode = SelectMode::Character;
 2823                auto_scroll = true;
 2824            }
 2825            2 => {
 2826                let range = movement::surrounding_word(&display_map, position);
 2827                start = buffer.anchor_before(range.start.to_point(&display_map));
 2828                end = buffer.anchor_before(range.end.to_point(&display_map));
 2829                mode = SelectMode::Word(start..end);
 2830                auto_scroll = true;
 2831            }
 2832            3 => {
 2833                let position = display_map
 2834                    .clip_point(position, Bias::Left)
 2835                    .to_point(&display_map);
 2836                let line_start = display_map.prev_line_boundary(position).0;
 2837                let next_line_start = buffer.clip_point(
 2838                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2839                    Bias::Left,
 2840                );
 2841                start = buffer.anchor_before(line_start);
 2842                end = buffer.anchor_before(next_line_start);
 2843                mode = SelectMode::Line(start..end);
 2844                auto_scroll = true;
 2845            }
 2846            _ => {
 2847                start = buffer.anchor_before(0);
 2848                end = buffer.anchor_before(buffer.len());
 2849                mode = SelectMode::All;
 2850                auto_scroll = false;
 2851            }
 2852        }
 2853
 2854        let point_to_delete: Option<usize> = {
 2855            let selected_points: Vec<Selection<Point>> =
 2856                self.selections.disjoint_in_range(start..end, cx);
 2857
 2858            if !add || click_count > 1 {
 2859                None
 2860            } else if !selected_points.is_empty() {
 2861                Some(selected_points[0].id)
 2862            } else {
 2863                let clicked_point_already_selected =
 2864                    self.selections.disjoint.iter().find(|selection| {
 2865                        selection.start.to_point(buffer) == start.to_point(buffer)
 2866                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2867                    });
 2868
 2869                clicked_point_already_selected.map(|selection| selection.id)
 2870            }
 2871        };
 2872
 2873        let selections_count = self.selections.count();
 2874
 2875        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2876            if let Some(point_to_delete) = point_to_delete {
 2877                s.delete(point_to_delete);
 2878
 2879                if selections_count == 1 {
 2880                    s.set_pending_anchor_range(start..end, mode);
 2881                }
 2882            } else {
 2883                if !add {
 2884                    s.clear_disjoint();
 2885                } else if click_count > 1 {
 2886                    s.delete(newest_selection.id)
 2887                }
 2888
 2889                s.set_pending_anchor_range(start..end, mode);
 2890            }
 2891        });
 2892    }
 2893
 2894    fn begin_columnar_selection(
 2895        &mut self,
 2896        position: DisplayPoint,
 2897        goal_column: u32,
 2898        reset: bool,
 2899        cx: &mut ViewContext<Self>,
 2900    ) {
 2901        if !self.focus_handle.is_focused(cx) {
 2902            self.last_focused_descendant = None;
 2903            cx.focus(&self.focus_handle);
 2904        }
 2905
 2906        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2907
 2908        if reset {
 2909            let pointer_position = display_map
 2910                .buffer_snapshot
 2911                .anchor_before(position.to_point(&display_map));
 2912
 2913            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2914                s.clear_disjoint();
 2915                s.set_pending_anchor_range(
 2916                    pointer_position..pointer_position,
 2917                    SelectMode::Character,
 2918                );
 2919            });
 2920        }
 2921
 2922        let tail = self.selections.newest::<Point>(cx).tail();
 2923        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2924
 2925        if !reset {
 2926            self.select_columns(
 2927                tail.to_display_point(&display_map),
 2928                position,
 2929                goal_column,
 2930                &display_map,
 2931                cx,
 2932            );
 2933        }
 2934    }
 2935
 2936    fn update_selection(
 2937        &mut self,
 2938        position: DisplayPoint,
 2939        goal_column: u32,
 2940        scroll_delta: gpui::Point<f32>,
 2941        cx: &mut ViewContext<Self>,
 2942    ) {
 2943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2944
 2945        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2946            let tail = tail.to_display_point(&display_map);
 2947            self.select_columns(tail, position, goal_column, &display_map, cx);
 2948        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2949            let buffer = self.buffer.read(cx).snapshot(cx);
 2950            let head;
 2951            let tail;
 2952            let mode = self.selections.pending_mode().unwrap();
 2953            match &mode {
 2954                SelectMode::Character => {
 2955                    head = position.to_point(&display_map);
 2956                    tail = pending.tail().to_point(&buffer);
 2957                }
 2958                SelectMode::Word(original_range) => {
 2959                    let original_display_range = original_range.start.to_display_point(&display_map)
 2960                        ..original_range.end.to_display_point(&display_map);
 2961                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2962                        ..original_display_range.end.to_point(&display_map);
 2963                    if movement::is_inside_word(&display_map, position)
 2964                        || original_display_range.contains(&position)
 2965                    {
 2966                        let word_range = movement::surrounding_word(&display_map, position);
 2967                        if word_range.start < original_display_range.start {
 2968                            head = word_range.start.to_point(&display_map);
 2969                        } else {
 2970                            head = word_range.end.to_point(&display_map);
 2971                        }
 2972                    } else {
 2973                        head = position.to_point(&display_map);
 2974                    }
 2975
 2976                    if head <= original_buffer_range.start {
 2977                        tail = original_buffer_range.end;
 2978                    } else {
 2979                        tail = original_buffer_range.start;
 2980                    }
 2981                }
 2982                SelectMode::Line(original_range) => {
 2983                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2984
 2985                    let position = display_map
 2986                        .clip_point(position, Bias::Left)
 2987                        .to_point(&display_map);
 2988                    let line_start = display_map.prev_line_boundary(position).0;
 2989                    let next_line_start = buffer.clip_point(
 2990                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2991                        Bias::Left,
 2992                    );
 2993
 2994                    if line_start < original_range.start {
 2995                        head = line_start
 2996                    } else {
 2997                        head = next_line_start
 2998                    }
 2999
 3000                    if head <= original_range.start {
 3001                        tail = original_range.end;
 3002                    } else {
 3003                        tail = original_range.start;
 3004                    }
 3005                }
 3006                SelectMode::All => {
 3007                    return;
 3008                }
 3009            };
 3010
 3011            if head < tail {
 3012                pending.start = buffer.anchor_before(head);
 3013                pending.end = buffer.anchor_before(tail);
 3014                pending.reversed = true;
 3015            } else {
 3016                pending.start = buffer.anchor_before(tail);
 3017                pending.end = buffer.anchor_before(head);
 3018                pending.reversed = false;
 3019            }
 3020
 3021            self.change_selections(None, cx, |s| {
 3022                s.set_pending(pending, mode);
 3023            });
 3024        } else {
 3025            log::error!("update_selection dispatched with no pending selection");
 3026            return;
 3027        }
 3028
 3029        self.apply_scroll_delta(scroll_delta, cx);
 3030        cx.notify();
 3031    }
 3032
 3033    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3034        self.columnar_selection_tail.take();
 3035        if self.selections.pending_anchor().is_some() {
 3036            let selections = self.selections.all::<usize>(cx);
 3037            self.change_selections(None, cx, |s| {
 3038                s.select(selections);
 3039                s.clear_pending();
 3040            });
 3041        }
 3042    }
 3043
 3044    fn select_columns(
 3045        &mut self,
 3046        tail: DisplayPoint,
 3047        head: DisplayPoint,
 3048        goal_column: u32,
 3049        display_map: &DisplaySnapshot,
 3050        cx: &mut ViewContext<Self>,
 3051    ) {
 3052        let start_row = cmp::min(tail.row(), head.row());
 3053        let end_row = cmp::max(tail.row(), head.row());
 3054        let start_column = cmp::min(tail.column(), goal_column);
 3055        let end_column = cmp::max(tail.column(), goal_column);
 3056        let reversed = start_column < tail.column();
 3057
 3058        let selection_ranges = (start_row.0..=end_row.0)
 3059            .map(DisplayRow)
 3060            .filter_map(|row| {
 3061                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3062                    let start = display_map
 3063                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3064                        .to_point(display_map);
 3065                    let end = display_map
 3066                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3067                        .to_point(display_map);
 3068                    if reversed {
 3069                        Some(end..start)
 3070                    } else {
 3071                        Some(start..end)
 3072                    }
 3073                } else {
 3074                    None
 3075                }
 3076            })
 3077            .collect::<Vec<_>>();
 3078
 3079        self.change_selections(None, cx, |s| {
 3080            s.select_ranges(selection_ranges);
 3081        });
 3082        cx.notify();
 3083    }
 3084
 3085    pub fn has_pending_nonempty_selection(&self) -> bool {
 3086        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3087            Some(Selection { start, end, .. }) => start != end,
 3088            None => false,
 3089        };
 3090
 3091        pending_nonempty_selection
 3092            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3093    }
 3094
 3095    pub fn has_pending_selection(&self) -> bool {
 3096        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3097    }
 3098
 3099    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3100        if self.clear_expanded_diff_hunks(cx) {
 3101            cx.notify();
 3102            return;
 3103        }
 3104        if self.dismiss_menus_and_popups(true, cx) {
 3105            return;
 3106        }
 3107
 3108        if self.mode == EditorMode::Full
 3109            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3110        {
 3111            return;
 3112        }
 3113
 3114        cx.propagate();
 3115    }
 3116
 3117    pub fn dismiss_menus_and_popups(
 3118        &mut self,
 3119        should_report_inline_completion_event: bool,
 3120        cx: &mut ViewContext<Self>,
 3121    ) -> bool {
 3122        if self.take_rename(false, cx).is_some() {
 3123            return true;
 3124        }
 3125
 3126        if hide_hover(self, cx) {
 3127            return true;
 3128        }
 3129
 3130        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3131            return true;
 3132        }
 3133
 3134        if self.hide_context_menu(cx).is_some() {
 3135            return true;
 3136        }
 3137
 3138        if self.mouse_context_menu.take().is_some() {
 3139            return true;
 3140        }
 3141
 3142        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3143            return true;
 3144        }
 3145
 3146        if self.snippet_stack.pop().is_some() {
 3147            return true;
 3148        }
 3149
 3150        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3151            self.dismiss_diagnostics(cx);
 3152            return true;
 3153        }
 3154
 3155        false
 3156    }
 3157
 3158    fn linked_editing_ranges_for(
 3159        &self,
 3160        selection: Range<text::Anchor>,
 3161        cx: &AppContext,
 3162    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3163        if self.linked_edit_ranges.is_empty() {
 3164            return None;
 3165        }
 3166        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3167            selection.end.buffer_id.and_then(|end_buffer_id| {
 3168                if selection.start.buffer_id != Some(end_buffer_id) {
 3169                    return None;
 3170                }
 3171                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3172                let snapshot = buffer.read(cx).snapshot();
 3173                self.linked_edit_ranges
 3174                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3175                    .map(|ranges| (ranges, snapshot, buffer))
 3176            })?;
 3177        use text::ToOffset as TO;
 3178        // find offset from the start of current range to current cursor position
 3179        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3180
 3181        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3182        let start_difference = start_offset - start_byte_offset;
 3183        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3184        let end_difference = end_offset - start_byte_offset;
 3185        // Current range has associated linked ranges.
 3186        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3187        for range in linked_ranges.iter() {
 3188            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3189            let end_offset = start_offset + end_difference;
 3190            let start_offset = start_offset + start_difference;
 3191            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3192                continue;
 3193            }
 3194            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3195                if s.start.buffer_id != selection.start.buffer_id
 3196                    || s.end.buffer_id != selection.end.buffer_id
 3197                {
 3198                    return false;
 3199                }
 3200                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3201                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3202            }) {
 3203                continue;
 3204            }
 3205            let start = buffer_snapshot.anchor_after(start_offset);
 3206            let end = buffer_snapshot.anchor_after(end_offset);
 3207            linked_edits
 3208                .entry(buffer.clone())
 3209                .or_default()
 3210                .push(start..end);
 3211        }
 3212        Some(linked_edits)
 3213    }
 3214
 3215    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3216        let text: Arc<str> = text.into();
 3217
 3218        if self.read_only(cx) {
 3219            return;
 3220        }
 3221
 3222        let selections = self.selections.all_adjusted(cx);
 3223        let mut bracket_inserted = false;
 3224        let mut edits = Vec::new();
 3225        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3226        let mut new_selections = Vec::with_capacity(selections.len());
 3227        let mut new_autoclose_regions = Vec::new();
 3228        let snapshot = self.buffer.read(cx).read(cx);
 3229
 3230        for (selection, autoclose_region) in
 3231            self.selections_with_autoclose_regions(selections, &snapshot)
 3232        {
 3233            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3234                // Determine if the inserted text matches the opening or closing
 3235                // bracket of any of this language's bracket pairs.
 3236                let mut bracket_pair = None;
 3237                let mut is_bracket_pair_start = false;
 3238                let mut is_bracket_pair_end = false;
 3239                if !text.is_empty() {
 3240                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3241                    //  and they are removing the character that triggered IME popup.
 3242                    for (pair, enabled) in scope.brackets() {
 3243                        if !pair.close && !pair.surround {
 3244                            continue;
 3245                        }
 3246
 3247                        if enabled && pair.start.ends_with(text.as_ref()) {
 3248                            bracket_pair = Some(pair.clone());
 3249                            is_bracket_pair_start = true;
 3250                            break;
 3251                        }
 3252                        if pair.end.as_str() == text.as_ref() {
 3253                            bracket_pair = Some(pair.clone());
 3254                            is_bracket_pair_end = true;
 3255                            break;
 3256                        }
 3257                    }
 3258                }
 3259
 3260                if let Some(bracket_pair) = bracket_pair {
 3261                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3262                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3263                    let auto_surround =
 3264                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3265                    if selection.is_empty() {
 3266                        if is_bracket_pair_start {
 3267                            let prefix_len = bracket_pair.start.len() - text.len();
 3268
 3269                            // If the inserted text is a suffix of an opening bracket and the
 3270                            // selection is preceded by the rest of the opening bracket, then
 3271                            // insert the closing bracket.
 3272                            let following_text_allows_autoclose = snapshot
 3273                                .chars_at(selection.start)
 3274                                .next()
 3275                                .map_or(true, |c| scope.should_autoclose_before(c));
 3276                            let preceding_text_matches_prefix = prefix_len == 0
 3277                                || (selection.start.column >= (prefix_len as u32)
 3278                                    && snapshot.contains_str_at(
 3279                                        Point::new(
 3280                                            selection.start.row,
 3281                                            selection.start.column - (prefix_len as u32),
 3282                                        ),
 3283                                        &bracket_pair.start[..prefix_len],
 3284                                    ));
 3285
 3286                            if autoclose
 3287                                && bracket_pair.close
 3288                                && following_text_allows_autoclose
 3289                                && preceding_text_matches_prefix
 3290                            {
 3291                                let anchor = snapshot.anchor_before(selection.end);
 3292                                new_selections.push((selection.map(|_| anchor), text.len()));
 3293                                new_autoclose_regions.push((
 3294                                    anchor,
 3295                                    text.len(),
 3296                                    selection.id,
 3297                                    bracket_pair.clone(),
 3298                                ));
 3299                                edits.push((
 3300                                    selection.range(),
 3301                                    format!("{}{}", text, bracket_pair.end).into(),
 3302                                ));
 3303                                bracket_inserted = true;
 3304                                continue;
 3305                            }
 3306                        }
 3307
 3308                        if let Some(region) = autoclose_region {
 3309                            // If the selection is followed by an auto-inserted closing bracket,
 3310                            // then don't insert that closing bracket again; just move the selection
 3311                            // past the closing bracket.
 3312                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3313                                && text.as_ref() == region.pair.end.as_str();
 3314                            if should_skip {
 3315                                let anchor = snapshot.anchor_after(selection.end);
 3316                                new_selections
 3317                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3318                                continue;
 3319                            }
 3320                        }
 3321
 3322                        let always_treat_brackets_as_autoclosed = snapshot
 3323                            .settings_at(selection.start, cx)
 3324                            .always_treat_brackets_as_autoclosed;
 3325                        if always_treat_brackets_as_autoclosed
 3326                            && is_bracket_pair_end
 3327                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3328                        {
 3329                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3330                            // and the inserted text is a closing bracket and the selection is followed
 3331                            // by the closing bracket then move the selection past the closing bracket.
 3332                            let anchor = snapshot.anchor_after(selection.end);
 3333                            new_selections.push((selection.map(|_| anchor), text.len()));
 3334                            continue;
 3335                        }
 3336                    }
 3337                    // If an opening bracket is 1 character long and is typed while
 3338                    // text is selected, then surround that text with the bracket pair.
 3339                    else if auto_surround
 3340                        && bracket_pair.surround
 3341                        && is_bracket_pair_start
 3342                        && bracket_pair.start.chars().count() == 1
 3343                    {
 3344                        edits.push((selection.start..selection.start, text.clone()));
 3345                        edits.push((
 3346                            selection.end..selection.end,
 3347                            bracket_pair.end.as_str().into(),
 3348                        ));
 3349                        bracket_inserted = true;
 3350                        new_selections.push((
 3351                            Selection {
 3352                                id: selection.id,
 3353                                start: snapshot.anchor_after(selection.start),
 3354                                end: snapshot.anchor_before(selection.end),
 3355                                reversed: selection.reversed,
 3356                                goal: selection.goal,
 3357                            },
 3358                            0,
 3359                        ));
 3360                        continue;
 3361                    }
 3362                }
 3363            }
 3364
 3365            if self.auto_replace_emoji_shortcode
 3366                && selection.is_empty()
 3367                && text.as_ref().ends_with(':')
 3368            {
 3369                if let Some(possible_emoji_short_code) =
 3370                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3371                {
 3372                    if !possible_emoji_short_code.is_empty() {
 3373                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3374                            let emoji_shortcode_start = Point::new(
 3375                                selection.start.row,
 3376                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3377                            );
 3378
 3379                            // Remove shortcode from buffer
 3380                            edits.push((
 3381                                emoji_shortcode_start..selection.start,
 3382                                "".to_string().into(),
 3383                            ));
 3384                            new_selections.push((
 3385                                Selection {
 3386                                    id: selection.id,
 3387                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3388                                    end: snapshot.anchor_before(selection.start),
 3389                                    reversed: selection.reversed,
 3390                                    goal: selection.goal,
 3391                                },
 3392                                0,
 3393                            ));
 3394
 3395                            // Insert emoji
 3396                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3397                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3398                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3399
 3400                            continue;
 3401                        }
 3402                    }
 3403                }
 3404            }
 3405
 3406            // If not handling any auto-close operation, then just replace the selected
 3407            // text with the given input and move the selection to the end of the
 3408            // newly inserted text.
 3409            let anchor = snapshot.anchor_after(selection.end);
 3410            if !self.linked_edit_ranges.is_empty() {
 3411                let start_anchor = snapshot.anchor_before(selection.start);
 3412
 3413                let is_word_char = text.chars().next().map_or(true, |char| {
 3414                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3415                    classifier.is_word(char)
 3416                });
 3417
 3418                if is_word_char {
 3419                    if let Some(ranges) = self
 3420                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3421                    {
 3422                        for (buffer, edits) in ranges {
 3423                            linked_edits
 3424                                .entry(buffer.clone())
 3425                                .or_default()
 3426                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3427                        }
 3428                    }
 3429                }
 3430            }
 3431
 3432            new_selections.push((selection.map(|_| anchor), 0));
 3433            edits.push((selection.start..selection.end, text.clone()));
 3434        }
 3435
 3436        drop(snapshot);
 3437
 3438        self.transact(cx, |this, cx| {
 3439            this.buffer.update(cx, |buffer, cx| {
 3440                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3441            });
 3442            for (buffer, edits) in linked_edits {
 3443                buffer.update(cx, |buffer, cx| {
 3444                    let snapshot = buffer.snapshot();
 3445                    let edits = edits
 3446                        .into_iter()
 3447                        .map(|(range, text)| {
 3448                            use text::ToPoint as TP;
 3449                            let end_point = TP::to_point(&range.end, &snapshot);
 3450                            let start_point = TP::to_point(&range.start, &snapshot);
 3451                            (start_point..end_point, text)
 3452                        })
 3453                        .sorted_by_key(|(range, _)| range.start)
 3454                        .collect::<Vec<_>>();
 3455                    buffer.edit(edits, None, cx);
 3456                })
 3457            }
 3458            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3459            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3460            let snapshot = this.buffer.read(cx).read(cx);
 3461            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3462                .zip(new_selection_deltas)
 3463                .map(|(selection, delta)| Selection {
 3464                    id: selection.id,
 3465                    start: selection.start + delta,
 3466                    end: selection.end + delta,
 3467                    reversed: selection.reversed,
 3468                    goal: SelectionGoal::None,
 3469                })
 3470                .collect::<Vec<_>>();
 3471
 3472            let mut i = 0;
 3473            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3474                let position = position.to_offset(&snapshot) + delta;
 3475                let start = snapshot.anchor_before(position);
 3476                let end = snapshot.anchor_after(position);
 3477                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3478                    match existing_state.range.start.cmp(&start, &snapshot) {
 3479                        Ordering::Less => i += 1,
 3480                        Ordering::Greater => break,
 3481                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3482                            Ordering::Less => i += 1,
 3483                            Ordering::Equal => break,
 3484                            Ordering::Greater => break,
 3485                        },
 3486                    }
 3487                }
 3488                this.autoclose_regions.insert(
 3489                    i,
 3490                    AutocloseRegion {
 3491                        selection_id,
 3492                        range: start..end,
 3493                        pair,
 3494                    },
 3495                );
 3496            }
 3497
 3498            drop(snapshot);
 3499            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3500            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3501                s.select(new_selections)
 3502            });
 3503
 3504            if !bracket_inserted {
 3505                if let Some(on_type_format_task) =
 3506                    this.trigger_on_type_formatting(text.to_string(), cx)
 3507                {
 3508                    on_type_format_task.detach_and_log_err(cx);
 3509                }
 3510            }
 3511
 3512            let editor_settings = EditorSettings::get_global(cx);
 3513            if bracket_inserted
 3514                && (editor_settings.auto_signature_help
 3515                    || editor_settings.show_signature_help_after_edits)
 3516            {
 3517                this.show_signature_help(&ShowSignatureHelp, cx);
 3518            }
 3519
 3520            let trigger_in_words = !had_active_inline_completion;
 3521            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3522            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3523            this.refresh_inline_completion(true, false, cx);
 3524        });
 3525    }
 3526
 3527    fn find_possible_emoji_shortcode_at_position(
 3528        snapshot: &MultiBufferSnapshot,
 3529        position: Point,
 3530    ) -> Option<String> {
 3531        let mut chars = Vec::new();
 3532        let mut found_colon = false;
 3533        for char in snapshot.reversed_chars_at(position).take(100) {
 3534            // Found a possible emoji shortcode in the middle of the buffer
 3535            if found_colon {
 3536                if char.is_whitespace() {
 3537                    chars.reverse();
 3538                    return Some(chars.iter().collect());
 3539                }
 3540                // If the previous character is not a whitespace, we are in the middle of a word
 3541                // and we only want to complete the shortcode if the word is made up of other emojis
 3542                let mut containing_word = String::new();
 3543                for ch in snapshot
 3544                    .reversed_chars_at(position)
 3545                    .skip(chars.len() + 1)
 3546                    .take(100)
 3547                {
 3548                    if ch.is_whitespace() {
 3549                        break;
 3550                    }
 3551                    containing_word.push(ch);
 3552                }
 3553                let containing_word = containing_word.chars().rev().collect::<String>();
 3554                if util::word_consists_of_emojis(containing_word.as_str()) {
 3555                    chars.reverse();
 3556                    return Some(chars.iter().collect());
 3557                }
 3558            }
 3559
 3560            if char.is_whitespace() || !char.is_ascii() {
 3561                return None;
 3562            }
 3563            if char == ':' {
 3564                found_colon = true;
 3565            } else {
 3566                chars.push(char);
 3567            }
 3568        }
 3569        // Found a possible emoji shortcode at the beginning of the buffer
 3570        chars.reverse();
 3571        Some(chars.iter().collect())
 3572    }
 3573
 3574    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3575        self.transact(cx, |this, cx| {
 3576            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3577                let selections = this.selections.all::<usize>(cx);
 3578                let multi_buffer = this.buffer.read(cx);
 3579                let buffer = multi_buffer.snapshot(cx);
 3580                selections
 3581                    .iter()
 3582                    .map(|selection| {
 3583                        let start_point = selection.start.to_point(&buffer);
 3584                        let mut indent =
 3585                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3586                        indent.len = cmp::min(indent.len, start_point.column);
 3587                        let start = selection.start;
 3588                        let end = selection.end;
 3589                        let selection_is_empty = start == end;
 3590                        let language_scope = buffer.language_scope_at(start);
 3591                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3592                            &language_scope
 3593                        {
 3594                            let leading_whitespace_len = buffer
 3595                                .reversed_chars_at(start)
 3596                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3597                                .map(|c| c.len_utf8())
 3598                                .sum::<usize>();
 3599
 3600                            let trailing_whitespace_len = buffer
 3601                                .chars_at(end)
 3602                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3603                                .map(|c| c.len_utf8())
 3604                                .sum::<usize>();
 3605
 3606                            let insert_extra_newline =
 3607                                language.brackets().any(|(pair, enabled)| {
 3608                                    let pair_start = pair.start.trim_end();
 3609                                    let pair_end = pair.end.trim_start();
 3610
 3611                                    enabled
 3612                                        && pair.newline
 3613                                        && buffer.contains_str_at(
 3614                                            end + trailing_whitespace_len,
 3615                                            pair_end,
 3616                                        )
 3617                                        && buffer.contains_str_at(
 3618                                            (start - leading_whitespace_len)
 3619                                                .saturating_sub(pair_start.len()),
 3620                                            pair_start,
 3621                                        )
 3622                                });
 3623
 3624                            // Comment extension on newline is allowed only for cursor selections
 3625                            let comment_delimiter = maybe!({
 3626                                if !selection_is_empty {
 3627                                    return None;
 3628                                }
 3629
 3630                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3631                                    return None;
 3632                                }
 3633
 3634                                let delimiters = language.line_comment_prefixes();
 3635                                let max_len_of_delimiter =
 3636                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3637                                let (snapshot, range) =
 3638                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3639
 3640                                let mut index_of_first_non_whitespace = 0;
 3641                                let comment_candidate = snapshot
 3642                                    .chars_for_range(range)
 3643                                    .skip_while(|c| {
 3644                                        let should_skip = c.is_whitespace();
 3645                                        if should_skip {
 3646                                            index_of_first_non_whitespace += 1;
 3647                                        }
 3648                                        should_skip
 3649                                    })
 3650                                    .take(max_len_of_delimiter)
 3651                                    .collect::<String>();
 3652                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3653                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3654                                })?;
 3655                                let cursor_is_placed_after_comment_marker =
 3656                                    index_of_first_non_whitespace + comment_prefix.len()
 3657                                        <= start_point.column as usize;
 3658                                if cursor_is_placed_after_comment_marker {
 3659                                    Some(comment_prefix.clone())
 3660                                } else {
 3661                                    None
 3662                                }
 3663                            });
 3664                            (comment_delimiter, insert_extra_newline)
 3665                        } else {
 3666                            (None, false)
 3667                        };
 3668
 3669                        let capacity_for_delimiter = comment_delimiter
 3670                            .as_deref()
 3671                            .map(str::len)
 3672                            .unwrap_or_default();
 3673                        let mut new_text =
 3674                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3675                        new_text.push('\n');
 3676                        new_text.extend(indent.chars());
 3677                        if let Some(delimiter) = &comment_delimiter {
 3678                            new_text.push_str(delimiter);
 3679                        }
 3680                        if insert_extra_newline {
 3681                            new_text = new_text.repeat(2);
 3682                        }
 3683
 3684                        let anchor = buffer.anchor_after(end);
 3685                        let new_selection = selection.map(|_| anchor);
 3686                        (
 3687                            (start..end, new_text),
 3688                            (insert_extra_newline, new_selection),
 3689                        )
 3690                    })
 3691                    .unzip()
 3692            };
 3693
 3694            this.edit_with_autoindent(edits, cx);
 3695            let buffer = this.buffer.read(cx).snapshot(cx);
 3696            let new_selections = selection_fixup_info
 3697                .into_iter()
 3698                .map(|(extra_newline_inserted, new_selection)| {
 3699                    let mut cursor = new_selection.end.to_point(&buffer);
 3700                    if extra_newline_inserted {
 3701                        cursor.row -= 1;
 3702                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3703                    }
 3704                    new_selection.map(|_| cursor)
 3705                })
 3706                .collect();
 3707
 3708            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3709            this.refresh_inline_completion(true, false, cx);
 3710        });
 3711    }
 3712
 3713    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3714        let buffer = self.buffer.read(cx);
 3715        let snapshot = buffer.snapshot(cx);
 3716
 3717        let mut edits = Vec::new();
 3718        let mut rows = Vec::new();
 3719
 3720        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3721            let cursor = selection.head();
 3722            let row = cursor.row;
 3723
 3724            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3725
 3726            let newline = "\n".to_string();
 3727            edits.push((start_of_line..start_of_line, newline));
 3728
 3729            rows.push(row + rows_inserted as u32);
 3730        }
 3731
 3732        self.transact(cx, |editor, cx| {
 3733            editor.edit(edits, cx);
 3734
 3735            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3736                let mut index = 0;
 3737                s.move_cursors_with(|map, _, _| {
 3738                    let row = rows[index];
 3739                    index += 1;
 3740
 3741                    let point = Point::new(row, 0);
 3742                    let boundary = map.next_line_boundary(point).1;
 3743                    let clipped = map.clip_point(boundary, Bias::Left);
 3744
 3745                    (clipped, SelectionGoal::None)
 3746                });
 3747            });
 3748
 3749            let mut indent_edits = Vec::new();
 3750            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3751            for row in rows {
 3752                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3753                for (row, indent) in indents {
 3754                    if indent.len == 0 {
 3755                        continue;
 3756                    }
 3757
 3758                    let text = match indent.kind {
 3759                        IndentKind::Space => " ".repeat(indent.len as usize),
 3760                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3761                    };
 3762                    let point = Point::new(row.0, 0);
 3763                    indent_edits.push((point..point, text));
 3764                }
 3765            }
 3766            editor.edit(indent_edits, cx);
 3767        });
 3768    }
 3769
 3770    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3771        let buffer = self.buffer.read(cx);
 3772        let snapshot = buffer.snapshot(cx);
 3773
 3774        let mut edits = Vec::new();
 3775        let mut rows = Vec::new();
 3776        let mut rows_inserted = 0;
 3777
 3778        for selection in self.selections.all_adjusted(cx) {
 3779            let cursor = selection.head();
 3780            let row = cursor.row;
 3781
 3782            let point = Point::new(row + 1, 0);
 3783            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3784
 3785            let newline = "\n".to_string();
 3786            edits.push((start_of_line..start_of_line, newline));
 3787
 3788            rows_inserted += 1;
 3789            rows.push(row + rows_inserted);
 3790        }
 3791
 3792        self.transact(cx, |editor, cx| {
 3793            editor.edit(edits, cx);
 3794
 3795            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3796                let mut index = 0;
 3797                s.move_cursors_with(|map, _, _| {
 3798                    let row = rows[index];
 3799                    index += 1;
 3800
 3801                    let point = Point::new(row, 0);
 3802                    let boundary = map.next_line_boundary(point).1;
 3803                    let clipped = map.clip_point(boundary, Bias::Left);
 3804
 3805                    (clipped, SelectionGoal::None)
 3806                });
 3807            });
 3808
 3809            let mut indent_edits = Vec::new();
 3810            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3811            for row in rows {
 3812                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3813                for (row, indent) in indents {
 3814                    if indent.len == 0 {
 3815                        continue;
 3816                    }
 3817
 3818                    let text = match indent.kind {
 3819                        IndentKind::Space => " ".repeat(indent.len as usize),
 3820                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3821                    };
 3822                    let point = Point::new(row.0, 0);
 3823                    indent_edits.push((point..point, text));
 3824                }
 3825            }
 3826            editor.edit(indent_edits, cx);
 3827        });
 3828    }
 3829
 3830    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3831        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3832            original_indent_columns: Vec::new(),
 3833        });
 3834        self.insert_with_autoindent_mode(text, autoindent, cx);
 3835    }
 3836
 3837    fn insert_with_autoindent_mode(
 3838        &mut self,
 3839        text: &str,
 3840        autoindent_mode: Option<AutoindentMode>,
 3841        cx: &mut ViewContext<Self>,
 3842    ) {
 3843        if self.read_only(cx) {
 3844            return;
 3845        }
 3846
 3847        let text: Arc<str> = text.into();
 3848        self.transact(cx, |this, cx| {
 3849            let old_selections = this.selections.all_adjusted(cx);
 3850            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3851                let anchors = {
 3852                    let snapshot = buffer.read(cx);
 3853                    old_selections
 3854                        .iter()
 3855                        .map(|s| {
 3856                            let anchor = snapshot.anchor_after(s.head());
 3857                            s.map(|_| anchor)
 3858                        })
 3859                        .collect::<Vec<_>>()
 3860                };
 3861                buffer.edit(
 3862                    old_selections
 3863                        .iter()
 3864                        .map(|s| (s.start..s.end, text.clone())),
 3865                    autoindent_mode,
 3866                    cx,
 3867                );
 3868                anchors
 3869            });
 3870
 3871            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3872                s.select_anchors(selection_anchors);
 3873            })
 3874        });
 3875    }
 3876
 3877    fn trigger_completion_on_input(
 3878        &mut self,
 3879        text: &str,
 3880        trigger_in_words: bool,
 3881        cx: &mut ViewContext<Self>,
 3882    ) {
 3883        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3884            self.show_completions(
 3885                &ShowCompletions {
 3886                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3887                },
 3888                cx,
 3889            );
 3890        } else {
 3891            self.hide_context_menu(cx);
 3892        }
 3893    }
 3894
 3895    fn is_completion_trigger(
 3896        &self,
 3897        text: &str,
 3898        trigger_in_words: bool,
 3899        cx: &mut ViewContext<Self>,
 3900    ) -> bool {
 3901        let position = self.selections.newest_anchor().head();
 3902        let multibuffer = self.buffer.read(cx);
 3903        let Some(buffer) = position
 3904            .buffer_id
 3905            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3906        else {
 3907            return false;
 3908        };
 3909
 3910        if let Some(completion_provider) = &self.completion_provider {
 3911            completion_provider.is_completion_trigger(
 3912                &buffer,
 3913                position.text_anchor,
 3914                text,
 3915                trigger_in_words,
 3916                cx,
 3917            )
 3918        } else {
 3919            false
 3920        }
 3921    }
 3922
 3923    /// If any empty selections is touching the start of its innermost containing autoclose
 3924    /// region, expand it to select the brackets.
 3925    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3926        let selections = self.selections.all::<usize>(cx);
 3927        let buffer = self.buffer.read(cx).read(cx);
 3928        let new_selections = self
 3929            .selections_with_autoclose_regions(selections, &buffer)
 3930            .map(|(mut selection, region)| {
 3931                if !selection.is_empty() {
 3932                    return selection;
 3933                }
 3934
 3935                if let Some(region) = region {
 3936                    let mut range = region.range.to_offset(&buffer);
 3937                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3938                        range.start -= region.pair.start.len();
 3939                        if buffer.contains_str_at(range.start, &region.pair.start)
 3940                            && buffer.contains_str_at(range.end, &region.pair.end)
 3941                        {
 3942                            range.end += region.pair.end.len();
 3943                            selection.start = range.start;
 3944                            selection.end = range.end;
 3945
 3946                            return selection;
 3947                        }
 3948                    }
 3949                }
 3950
 3951                let always_treat_brackets_as_autoclosed = buffer
 3952                    .settings_at(selection.start, cx)
 3953                    .always_treat_brackets_as_autoclosed;
 3954
 3955                if !always_treat_brackets_as_autoclosed {
 3956                    return selection;
 3957                }
 3958
 3959                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3960                    for (pair, enabled) in scope.brackets() {
 3961                        if !enabled || !pair.close {
 3962                            continue;
 3963                        }
 3964
 3965                        if buffer.contains_str_at(selection.start, &pair.end) {
 3966                            let pair_start_len = pair.start.len();
 3967                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3968                            {
 3969                                selection.start -= pair_start_len;
 3970                                selection.end += pair.end.len();
 3971
 3972                                return selection;
 3973                            }
 3974                        }
 3975                    }
 3976                }
 3977
 3978                selection
 3979            })
 3980            .collect();
 3981
 3982        drop(buffer);
 3983        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3984    }
 3985
 3986    /// Iterate the given selections, and for each one, find the smallest surrounding
 3987    /// autoclose region. This uses the ordering of the selections and the autoclose
 3988    /// regions to avoid repeated comparisons.
 3989    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3990        &'a self,
 3991        selections: impl IntoIterator<Item = Selection<D>>,
 3992        buffer: &'a MultiBufferSnapshot,
 3993    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3994        let mut i = 0;
 3995        let mut regions = self.autoclose_regions.as_slice();
 3996        selections.into_iter().map(move |selection| {
 3997            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3998
 3999            let mut enclosing = None;
 4000            while let Some(pair_state) = regions.get(i) {
 4001                if pair_state.range.end.to_offset(buffer) < range.start {
 4002                    regions = &regions[i + 1..];
 4003                    i = 0;
 4004                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4005                    break;
 4006                } else {
 4007                    if pair_state.selection_id == selection.id {
 4008                        enclosing = Some(pair_state);
 4009                    }
 4010                    i += 1;
 4011                }
 4012            }
 4013
 4014            (selection.clone(), enclosing)
 4015        })
 4016    }
 4017
 4018    /// Remove any autoclose regions that no longer contain their selection.
 4019    fn invalidate_autoclose_regions(
 4020        &mut self,
 4021        mut selections: &[Selection<Anchor>],
 4022        buffer: &MultiBufferSnapshot,
 4023    ) {
 4024        self.autoclose_regions.retain(|state| {
 4025            let mut i = 0;
 4026            while let Some(selection) = selections.get(i) {
 4027                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4028                    selections = &selections[1..];
 4029                    continue;
 4030                }
 4031                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4032                    break;
 4033                }
 4034                if selection.id == state.selection_id {
 4035                    return true;
 4036                } else {
 4037                    i += 1;
 4038                }
 4039            }
 4040            false
 4041        });
 4042    }
 4043
 4044    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4045        let offset = position.to_offset(buffer);
 4046        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4047        if offset > word_range.start && kind == Some(CharKind::Word) {
 4048            Some(
 4049                buffer
 4050                    .text_for_range(word_range.start..offset)
 4051                    .collect::<String>(),
 4052            )
 4053        } else {
 4054            None
 4055        }
 4056    }
 4057
 4058    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4059        self.refresh_inlay_hints(
 4060            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4061            cx,
 4062        );
 4063    }
 4064
 4065    pub fn inlay_hints_enabled(&self) -> bool {
 4066        self.inlay_hint_cache.enabled
 4067    }
 4068
 4069    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4070        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4071            return;
 4072        }
 4073
 4074        let reason_description = reason.description();
 4075        let ignore_debounce = matches!(
 4076            reason,
 4077            InlayHintRefreshReason::SettingsChange(_)
 4078                | InlayHintRefreshReason::Toggle(_)
 4079                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4080        );
 4081        let (invalidate_cache, required_languages) = match reason {
 4082            InlayHintRefreshReason::Toggle(enabled) => {
 4083                self.inlay_hint_cache.enabled = enabled;
 4084                if enabled {
 4085                    (InvalidationStrategy::RefreshRequested, None)
 4086                } else {
 4087                    self.inlay_hint_cache.clear();
 4088                    self.splice_inlays(
 4089                        self.visible_inlay_hints(cx)
 4090                            .iter()
 4091                            .map(|inlay| inlay.id)
 4092                            .collect(),
 4093                        Vec::new(),
 4094                        cx,
 4095                    );
 4096                    return;
 4097                }
 4098            }
 4099            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4100                match self.inlay_hint_cache.update_settings(
 4101                    &self.buffer,
 4102                    new_settings,
 4103                    self.visible_inlay_hints(cx),
 4104                    cx,
 4105                ) {
 4106                    ControlFlow::Break(Some(InlaySplice {
 4107                        to_remove,
 4108                        to_insert,
 4109                    })) => {
 4110                        self.splice_inlays(to_remove, to_insert, cx);
 4111                        return;
 4112                    }
 4113                    ControlFlow::Break(None) => return,
 4114                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4115                }
 4116            }
 4117            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4118                if let Some(InlaySplice {
 4119                    to_remove,
 4120                    to_insert,
 4121                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4122                {
 4123                    self.splice_inlays(to_remove, to_insert, cx);
 4124                }
 4125                return;
 4126            }
 4127            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4128            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4129                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4130            }
 4131            InlayHintRefreshReason::RefreshRequested => {
 4132                (InvalidationStrategy::RefreshRequested, None)
 4133            }
 4134        };
 4135
 4136        if let Some(InlaySplice {
 4137            to_remove,
 4138            to_insert,
 4139        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4140            reason_description,
 4141            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4142            invalidate_cache,
 4143            ignore_debounce,
 4144            cx,
 4145        ) {
 4146            self.splice_inlays(to_remove, to_insert, cx);
 4147        }
 4148    }
 4149
 4150    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4151        self.display_map
 4152            .read(cx)
 4153            .current_inlays()
 4154            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4155            .cloned()
 4156            .collect()
 4157    }
 4158
 4159    pub fn excerpts_for_inlay_hints_query(
 4160        &self,
 4161        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4162        cx: &mut ViewContext<Editor>,
 4163    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4164        let Some(project) = self.project.as_ref() else {
 4165            return HashMap::default();
 4166        };
 4167        let project = project.read(cx);
 4168        let multi_buffer = self.buffer().read(cx);
 4169        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4170        let multi_buffer_visible_start = self
 4171            .scroll_manager
 4172            .anchor()
 4173            .anchor
 4174            .to_point(&multi_buffer_snapshot);
 4175        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4176            multi_buffer_visible_start
 4177                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4178            Bias::Left,
 4179        );
 4180        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4181        multi_buffer
 4182            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4183            .into_iter()
 4184            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4185            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4186                let buffer = buffer_handle.read(cx);
 4187                let buffer_file = project::File::from_dyn(buffer.file())?;
 4188                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4189                let worktree_entry = buffer_worktree
 4190                    .read(cx)
 4191                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4192                if worktree_entry.is_ignored {
 4193                    return None;
 4194                }
 4195
 4196                let language = buffer.language()?;
 4197                if let Some(restrict_to_languages) = restrict_to_languages {
 4198                    if !restrict_to_languages.contains(language) {
 4199                        return None;
 4200                    }
 4201                }
 4202                Some((
 4203                    excerpt_id,
 4204                    (
 4205                        buffer_handle,
 4206                        buffer.version().clone(),
 4207                        excerpt_visible_range,
 4208                    ),
 4209                ))
 4210            })
 4211            .collect()
 4212    }
 4213
 4214    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4215        TextLayoutDetails {
 4216            text_system: cx.text_system().clone(),
 4217            editor_style: self.style.clone().unwrap(),
 4218            rem_size: cx.rem_size(),
 4219            scroll_anchor: self.scroll_manager.anchor(),
 4220            visible_rows: self.visible_line_count(),
 4221            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4222        }
 4223    }
 4224
 4225    fn splice_inlays(
 4226        &self,
 4227        to_remove: Vec<InlayId>,
 4228        to_insert: Vec<Inlay>,
 4229        cx: &mut ViewContext<Self>,
 4230    ) {
 4231        self.display_map.update(cx, |display_map, cx| {
 4232            display_map.splice_inlays(to_remove, to_insert, cx);
 4233        });
 4234        cx.notify();
 4235    }
 4236
 4237    fn trigger_on_type_formatting(
 4238        &self,
 4239        input: String,
 4240        cx: &mut ViewContext<Self>,
 4241    ) -> Option<Task<Result<()>>> {
 4242        if input.len() != 1 {
 4243            return None;
 4244        }
 4245
 4246        let project = self.project.as_ref()?;
 4247        let position = self.selections.newest_anchor().head();
 4248        let (buffer, buffer_position) = self
 4249            .buffer
 4250            .read(cx)
 4251            .text_anchor_for_position(position, cx)?;
 4252
 4253        let settings = language_settings::language_settings(
 4254            buffer.read(cx).language_at(buffer_position).as_ref(),
 4255            buffer.read(cx).file(),
 4256            cx,
 4257        );
 4258        if !settings.use_on_type_format {
 4259            return None;
 4260        }
 4261
 4262        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4263        // hence we do LSP request & edit on host side only — add formats to host's history.
 4264        let push_to_lsp_host_history = true;
 4265        // If this is not the host, append its history with new edits.
 4266        let push_to_client_history = project.read(cx).is_via_collab();
 4267
 4268        let on_type_formatting = project.update(cx, |project, cx| {
 4269            project.on_type_format(
 4270                buffer.clone(),
 4271                buffer_position,
 4272                input,
 4273                push_to_lsp_host_history,
 4274                cx,
 4275            )
 4276        });
 4277        Some(cx.spawn(|editor, mut cx| async move {
 4278            if let Some(transaction) = on_type_formatting.await? {
 4279                if push_to_client_history {
 4280                    buffer
 4281                        .update(&mut cx, |buffer, _| {
 4282                            buffer.push_transaction(transaction, Instant::now());
 4283                        })
 4284                        .ok();
 4285                }
 4286                editor.update(&mut cx, |editor, cx| {
 4287                    editor.refresh_document_highlights(cx);
 4288                })?;
 4289            }
 4290            Ok(())
 4291        }))
 4292    }
 4293
 4294    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4295        if self.pending_rename.is_some() {
 4296            return;
 4297        }
 4298
 4299        let Some(provider) = self.completion_provider.as_ref() else {
 4300            return;
 4301        };
 4302
 4303        let position = self.selections.newest_anchor().head();
 4304        let (buffer, buffer_position) =
 4305            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4306                output
 4307            } else {
 4308                return;
 4309            };
 4310
 4311        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4312        let is_followup_invoke = {
 4313            let context_menu_state = self.context_menu.read();
 4314            matches!(
 4315                context_menu_state.deref(),
 4316                Some(ContextMenu::Completions(_))
 4317            )
 4318        };
 4319        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4320            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4321            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4322                CompletionTriggerKind::TRIGGER_CHARACTER
 4323            }
 4324
 4325            _ => CompletionTriggerKind::INVOKED,
 4326        };
 4327        let completion_context = CompletionContext {
 4328            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4329                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4330                    Some(String::from(trigger))
 4331                } else {
 4332                    None
 4333                }
 4334            }),
 4335            trigger_kind,
 4336        };
 4337        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4338        let sort_completions = provider.sort_completions();
 4339
 4340        let id = post_inc(&mut self.next_completion_id);
 4341        let task = cx.spawn(|this, mut cx| {
 4342            async move {
 4343                this.update(&mut cx, |this, _| {
 4344                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4345                })?;
 4346                let completions = completions.await.log_err();
 4347                let menu = if let Some(completions) = completions {
 4348                    let mut menu = CompletionsMenu {
 4349                        id,
 4350                        sort_completions,
 4351                        initial_position: position,
 4352                        match_candidates: completions
 4353                            .iter()
 4354                            .enumerate()
 4355                            .map(|(id, completion)| {
 4356                                StringMatchCandidate::new(
 4357                                    id,
 4358                                    completion.label.text[completion.label.filter_range.clone()]
 4359                                        .into(),
 4360                                )
 4361                            })
 4362                            .collect(),
 4363                        buffer: buffer.clone(),
 4364                        completions: Arc::new(RwLock::new(completions.into())),
 4365                        matches: Vec::new().into(),
 4366                        selected_item: 0,
 4367                        scroll_handle: UniformListScrollHandle::new(),
 4368                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4369                            DebouncedDelay::new(),
 4370                        )),
 4371                    };
 4372                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4373                        .await;
 4374
 4375                    if menu.matches.is_empty() {
 4376                        None
 4377                    } else {
 4378                        this.update(&mut cx, |editor, cx| {
 4379                            let completions = menu.completions.clone();
 4380                            let matches = menu.matches.clone();
 4381
 4382                            let delay_ms = EditorSettings::get_global(cx)
 4383                                .completion_documentation_secondary_query_debounce;
 4384                            let delay = Duration::from_millis(delay_ms);
 4385                            editor
 4386                                .completion_documentation_pre_resolve_debounce
 4387                                .fire_new(delay, cx, |editor, cx| {
 4388                                    CompletionsMenu::pre_resolve_completion_documentation(
 4389                                        buffer,
 4390                                        completions,
 4391                                        matches,
 4392                                        editor,
 4393                                        cx,
 4394                                    )
 4395                                });
 4396                        })
 4397                        .ok();
 4398                        Some(menu)
 4399                    }
 4400                } else {
 4401                    None
 4402                };
 4403
 4404                this.update(&mut cx, |this, cx| {
 4405                    let mut context_menu = this.context_menu.write();
 4406                    match context_menu.as_ref() {
 4407                        None => {}
 4408
 4409                        Some(ContextMenu::Completions(prev_menu)) => {
 4410                            if prev_menu.id > id {
 4411                                return;
 4412                            }
 4413                        }
 4414
 4415                        _ => return,
 4416                    }
 4417
 4418                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4419                        let menu = menu.unwrap();
 4420                        *context_menu = Some(ContextMenu::Completions(menu));
 4421                        drop(context_menu);
 4422                        this.discard_inline_completion(false, cx);
 4423                        cx.notify();
 4424                    } else if this.completion_tasks.len() <= 1 {
 4425                        // If there are no more completion tasks and the last menu was
 4426                        // empty, we should hide it. If it was already hidden, we should
 4427                        // also show the copilot completion when available.
 4428                        drop(context_menu);
 4429                        if this.hide_context_menu(cx).is_none() {
 4430                            this.update_visible_inline_completion(cx);
 4431                        }
 4432                    }
 4433                })?;
 4434
 4435                Ok::<_, anyhow::Error>(())
 4436            }
 4437            .log_err()
 4438        });
 4439
 4440        self.completion_tasks.push((id, task));
 4441    }
 4442
 4443    pub fn confirm_completion(
 4444        &mut self,
 4445        action: &ConfirmCompletion,
 4446        cx: &mut ViewContext<Self>,
 4447    ) -> Option<Task<Result<()>>> {
 4448        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4449    }
 4450
 4451    pub fn compose_completion(
 4452        &mut self,
 4453        action: &ComposeCompletion,
 4454        cx: &mut ViewContext<Self>,
 4455    ) -> Option<Task<Result<()>>> {
 4456        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4457    }
 4458
 4459    fn do_completion(
 4460        &mut self,
 4461        item_ix: Option<usize>,
 4462        intent: CompletionIntent,
 4463        cx: &mut ViewContext<Editor>,
 4464    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4465        use language::ToOffset as _;
 4466
 4467        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4468            menu
 4469        } else {
 4470            return None;
 4471        };
 4472
 4473        let mat = completions_menu
 4474            .matches
 4475            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4476        let buffer_handle = completions_menu.buffer;
 4477        let completions = completions_menu.completions.read();
 4478        let completion = completions.get(mat.candidate_id)?;
 4479        cx.stop_propagation();
 4480
 4481        let snippet;
 4482        let text;
 4483
 4484        if completion.is_snippet() {
 4485            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4486            text = snippet.as_ref().unwrap().text.clone();
 4487        } else {
 4488            snippet = None;
 4489            text = completion.new_text.clone();
 4490        };
 4491        let selections = self.selections.all::<usize>(cx);
 4492        let buffer = buffer_handle.read(cx);
 4493        let old_range = completion.old_range.to_offset(buffer);
 4494        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4495
 4496        let newest_selection = self.selections.newest_anchor();
 4497        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4498            return None;
 4499        }
 4500
 4501        let lookbehind = newest_selection
 4502            .start
 4503            .text_anchor
 4504            .to_offset(buffer)
 4505            .saturating_sub(old_range.start);
 4506        let lookahead = old_range
 4507            .end
 4508            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4509        let mut common_prefix_len = old_text
 4510            .bytes()
 4511            .zip(text.bytes())
 4512            .take_while(|(a, b)| a == b)
 4513            .count();
 4514
 4515        let snapshot = self.buffer.read(cx).snapshot(cx);
 4516        let mut range_to_replace: Option<Range<isize>> = None;
 4517        let mut ranges = Vec::new();
 4518        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4519        for selection in &selections {
 4520            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4521                let start = selection.start.saturating_sub(lookbehind);
 4522                let end = selection.end + lookahead;
 4523                if selection.id == newest_selection.id {
 4524                    range_to_replace = Some(
 4525                        ((start + common_prefix_len) as isize - selection.start as isize)
 4526                            ..(end as isize - selection.start as isize),
 4527                    );
 4528                }
 4529                ranges.push(start + common_prefix_len..end);
 4530            } else {
 4531                common_prefix_len = 0;
 4532                ranges.clear();
 4533                ranges.extend(selections.iter().map(|s| {
 4534                    if s.id == newest_selection.id {
 4535                        range_to_replace = Some(
 4536                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4537                                - selection.start as isize
 4538                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4539                                    - selection.start as isize,
 4540                        );
 4541                        old_range.clone()
 4542                    } else {
 4543                        s.start..s.end
 4544                    }
 4545                }));
 4546                break;
 4547            }
 4548            if !self.linked_edit_ranges.is_empty() {
 4549                let start_anchor = snapshot.anchor_before(selection.head());
 4550                let end_anchor = snapshot.anchor_after(selection.tail());
 4551                if let Some(ranges) = self
 4552                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4553                {
 4554                    for (buffer, edits) in ranges {
 4555                        linked_edits.entry(buffer.clone()).or_default().extend(
 4556                            edits
 4557                                .into_iter()
 4558                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4559                        );
 4560                    }
 4561                }
 4562            }
 4563        }
 4564        let text = &text[common_prefix_len..];
 4565
 4566        cx.emit(EditorEvent::InputHandled {
 4567            utf16_range_to_replace: range_to_replace,
 4568            text: text.into(),
 4569        });
 4570
 4571        self.transact(cx, |this, cx| {
 4572            if let Some(mut snippet) = snippet {
 4573                snippet.text = text.to_string();
 4574                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4575                    tabstop.start -= common_prefix_len as isize;
 4576                    tabstop.end -= common_prefix_len as isize;
 4577                }
 4578
 4579                this.insert_snippet(&ranges, snippet, cx).log_err();
 4580            } else {
 4581                this.buffer.update(cx, |buffer, cx| {
 4582                    buffer.edit(
 4583                        ranges.iter().map(|range| (range.clone(), text)),
 4584                        this.autoindent_mode.clone(),
 4585                        cx,
 4586                    );
 4587                });
 4588            }
 4589            for (buffer, edits) in linked_edits {
 4590                buffer.update(cx, |buffer, cx| {
 4591                    let snapshot = buffer.snapshot();
 4592                    let edits = edits
 4593                        .into_iter()
 4594                        .map(|(range, text)| {
 4595                            use text::ToPoint as TP;
 4596                            let end_point = TP::to_point(&range.end, &snapshot);
 4597                            let start_point = TP::to_point(&range.start, &snapshot);
 4598                            (start_point..end_point, text)
 4599                        })
 4600                        .sorted_by_key(|(range, _)| range.start)
 4601                        .collect::<Vec<_>>();
 4602                    buffer.edit(edits, None, cx);
 4603                })
 4604            }
 4605
 4606            this.refresh_inline_completion(true, false, cx);
 4607        });
 4608
 4609        let show_new_completions_on_confirm = completion
 4610            .confirm
 4611            .as_ref()
 4612            .map_or(false, |confirm| confirm(intent, cx));
 4613        if show_new_completions_on_confirm {
 4614            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4615        }
 4616
 4617        let provider = self.completion_provider.as_ref()?;
 4618        let apply_edits = provider.apply_additional_edits_for_completion(
 4619            buffer_handle,
 4620            completion.clone(),
 4621            true,
 4622            cx,
 4623        );
 4624
 4625        let editor_settings = EditorSettings::get_global(cx);
 4626        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4627            // After the code completion is finished, users often want to know what signatures are needed.
 4628            // so we should automatically call signature_help
 4629            self.show_signature_help(&ShowSignatureHelp, cx);
 4630        }
 4631
 4632        Some(cx.foreground_executor().spawn(async move {
 4633            apply_edits.await?;
 4634            Ok(())
 4635        }))
 4636    }
 4637
 4638    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4639        let mut context_menu = self.context_menu.write();
 4640        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4641            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4642                // Toggle if we're selecting the same one
 4643                *context_menu = None;
 4644                cx.notify();
 4645                return;
 4646            } else {
 4647                // Otherwise, clear it and start a new one
 4648                *context_menu = None;
 4649                cx.notify();
 4650            }
 4651        }
 4652        drop(context_menu);
 4653        let snapshot = self.snapshot(cx);
 4654        let deployed_from_indicator = action.deployed_from_indicator;
 4655        let mut task = self.code_actions_task.take();
 4656        let action = action.clone();
 4657        cx.spawn(|editor, mut cx| async move {
 4658            while let Some(prev_task) = task {
 4659                prev_task.await.log_err();
 4660                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4661            }
 4662
 4663            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4664                if editor.focus_handle.is_focused(cx) {
 4665                    let multibuffer_point = action
 4666                        .deployed_from_indicator
 4667                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4668                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4669                    let (buffer, buffer_row) = snapshot
 4670                        .buffer_snapshot
 4671                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4672                        .and_then(|(buffer_snapshot, range)| {
 4673                            editor
 4674                                .buffer
 4675                                .read(cx)
 4676                                .buffer(buffer_snapshot.remote_id())
 4677                                .map(|buffer| (buffer, range.start.row))
 4678                        })?;
 4679                    let (_, code_actions) = editor
 4680                        .available_code_actions
 4681                        .clone()
 4682                        .and_then(|(location, code_actions)| {
 4683                            let snapshot = location.buffer.read(cx).snapshot();
 4684                            let point_range = location.range.to_point(&snapshot);
 4685                            let point_range = point_range.start.row..=point_range.end.row;
 4686                            if point_range.contains(&buffer_row) {
 4687                                Some((location, code_actions))
 4688                            } else {
 4689                                None
 4690                            }
 4691                        })
 4692                        .unzip();
 4693                    let buffer_id = buffer.read(cx).remote_id();
 4694                    let tasks = editor
 4695                        .tasks
 4696                        .get(&(buffer_id, buffer_row))
 4697                        .map(|t| Arc::new(t.to_owned()));
 4698                    if tasks.is_none() && code_actions.is_none() {
 4699                        return None;
 4700                    }
 4701
 4702                    editor.completion_tasks.clear();
 4703                    editor.discard_inline_completion(false, cx);
 4704                    let task_context =
 4705                        tasks
 4706                            .as_ref()
 4707                            .zip(editor.project.clone())
 4708                            .map(|(tasks, project)| {
 4709                                let position = Point::new(buffer_row, tasks.column);
 4710                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4711                                let location = Location {
 4712                                    buffer: buffer.clone(),
 4713                                    range: range_start..range_start,
 4714                                };
 4715                                // Fill in the environmental variables from the tree-sitter captures
 4716                                let mut captured_task_variables = TaskVariables::default();
 4717                                for (capture_name, value) in tasks.extra_variables.clone() {
 4718                                    captured_task_variables.insert(
 4719                                        task::VariableName::Custom(capture_name.into()),
 4720                                        value.clone(),
 4721                                    );
 4722                                }
 4723                                project.update(cx, |project, cx| {
 4724                                    project.task_store().update(cx, |task_store, cx| {
 4725                                        task_store.task_context_for_location(
 4726                                            captured_task_variables,
 4727                                            location,
 4728                                            cx,
 4729                                        )
 4730                                    })
 4731                                })
 4732                            });
 4733
 4734                    Some(cx.spawn(|editor, mut cx| async move {
 4735                        let task_context = match task_context {
 4736                            Some(task_context) => task_context.await,
 4737                            None => None,
 4738                        };
 4739                        let resolved_tasks =
 4740                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4741                                Arc::new(ResolvedTasks {
 4742                                    templates: tasks
 4743                                        .templates
 4744                                        .iter()
 4745                                        .filter_map(|(kind, template)| {
 4746                                            template
 4747                                                .resolve_task(&kind.to_id_base(), &task_context)
 4748                                                .map(|task| (kind.clone(), task))
 4749                                        })
 4750                                        .collect(),
 4751                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4752                                        multibuffer_point.row,
 4753                                        tasks.column,
 4754                                    )),
 4755                                })
 4756                            });
 4757                        let spawn_straight_away = resolved_tasks
 4758                            .as_ref()
 4759                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4760                            && code_actions
 4761                                .as_ref()
 4762                                .map_or(true, |actions| actions.is_empty());
 4763                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4764                            *editor.context_menu.write() =
 4765                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4766                                    buffer,
 4767                                    actions: CodeActionContents {
 4768                                        tasks: resolved_tasks,
 4769                                        actions: code_actions,
 4770                                    },
 4771                                    selected_item: Default::default(),
 4772                                    scroll_handle: UniformListScrollHandle::default(),
 4773                                    deployed_from_indicator,
 4774                                }));
 4775                            if spawn_straight_away {
 4776                                if let Some(task) = editor.confirm_code_action(
 4777                                    &ConfirmCodeAction { item_ix: Some(0) },
 4778                                    cx,
 4779                                ) {
 4780                                    cx.notify();
 4781                                    return task;
 4782                                }
 4783                            }
 4784                            cx.notify();
 4785                            Task::ready(Ok(()))
 4786                        }) {
 4787                            task.await
 4788                        } else {
 4789                            Ok(())
 4790                        }
 4791                    }))
 4792                } else {
 4793                    Some(Task::ready(Ok(())))
 4794                }
 4795            })?;
 4796            if let Some(task) = spawned_test_task {
 4797                task.await?;
 4798            }
 4799
 4800            Ok::<_, anyhow::Error>(())
 4801        })
 4802        .detach_and_log_err(cx);
 4803    }
 4804
 4805    pub fn confirm_code_action(
 4806        &mut self,
 4807        action: &ConfirmCodeAction,
 4808        cx: &mut ViewContext<Self>,
 4809    ) -> Option<Task<Result<()>>> {
 4810        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4811            menu
 4812        } else {
 4813            return None;
 4814        };
 4815        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4816        let action = actions_menu.actions.get(action_ix)?;
 4817        let title = action.label();
 4818        let buffer = actions_menu.buffer;
 4819        let workspace = self.workspace()?;
 4820
 4821        match action {
 4822            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4823                workspace.update(cx, |workspace, cx| {
 4824                    workspace::tasks::schedule_resolved_task(
 4825                        workspace,
 4826                        task_source_kind,
 4827                        resolved_task,
 4828                        false,
 4829                        cx,
 4830                    );
 4831
 4832                    Some(Task::ready(Ok(())))
 4833                })
 4834            }
 4835            CodeActionsItem::CodeAction {
 4836                excerpt_id,
 4837                action,
 4838                provider,
 4839            } => {
 4840                let apply_code_action =
 4841                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4842                let workspace = workspace.downgrade();
 4843                Some(cx.spawn(|editor, cx| async move {
 4844                    let project_transaction = apply_code_action.await?;
 4845                    Self::open_project_transaction(
 4846                        &editor,
 4847                        workspace,
 4848                        project_transaction,
 4849                        title,
 4850                        cx,
 4851                    )
 4852                    .await
 4853                }))
 4854            }
 4855        }
 4856    }
 4857
 4858    pub async fn open_project_transaction(
 4859        this: &WeakView<Editor>,
 4860        workspace: WeakView<Workspace>,
 4861        transaction: ProjectTransaction,
 4862        title: String,
 4863        mut cx: AsyncWindowContext,
 4864    ) -> Result<()> {
 4865        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4866        cx.update(|cx| {
 4867            entries.sort_unstable_by_key(|(buffer, _)| {
 4868                buffer.read(cx).file().map(|f| f.path().clone())
 4869            });
 4870        })?;
 4871
 4872        // If the project transaction's edits are all contained within this editor, then
 4873        // avoid opening a new editor to display them.
 4874
 4875        if let Some((buffer, transaction)) = entries.first() {
 4876            if entries.len() == 1 {
 4877                let excerpt = this.update(&mut cx, |editor, cx| {
 4878                    editor
 4879                        .buffer()
 4880                        .read(cx)
 4881                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4882                })?;
 4883                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4884                    if excerpted_buffer == *buffer {
 4885                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4886                            let excerpt_range = excerpt_range.to_offset(buffer);
 4887                            buffer
 4888                                .edited_ranges_for_transaction::<usize>(transaction)
 4889                                .all(|range| {
 4890                                    excerpt_range.start <= range.start
 4891                                        && excerpt_range.end >= range.end
 4892                                })
 4893                        })?;
 4894
 4895                        if all_edits_within_excerpt {
 4896                            return Ok(());
 4897                        }
 4898                    }
 4899                }
 4900            }
 4901        } else {
 4902            return Ok(());
 4903        }
 4904
 4905        let mut ranges_to_highlight = Vec::new();
 4906        let excerpt_buffer = cx.new_model(|cx| {
 4907            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4908            for (buffer_handle, transaction) in &entries {
 4909                let buffer = buffer_handle.read(cx);
 4910                ranges_to_highlight.extend(
 4911                    multibuffer.push_excerpts_with_context_lines(
 4912                        buffer_handle.clone(),
 4913                        buffer
 4914                            .edited_ranges_for_transaction::<usize>(transaction)
 4915                            .collect(),
 4916                        DEFAULT_MULTIBUFFER_CONTEXT,
 4917                        cx,
 4918                    ),
 4919                );
 4920            }
 4921            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4922            multibuffer
 4923        })?;
 4924
 4925        workspace.update(&mut cx, |workspace, cx| {
 4926            let project = workspace.project().clone();
 4927            let editor =
 4928                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4929            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4930            editor.update(cx, |editor, cx| {
 4931                editor.highlight_background::<Self>(
 4932                    &ranges_to_highlight,
 4933                    |theme| theme.editor_highlighted_line_background,
 4934                    cx,
 4935                );
 4936            });
 4937        })?;
 4938
 4939        Ok(())
 4940    }
 4941
 4942    pub fn clear_code_action_providers(&mut self) {
 4943        self.code_action_providers.clear();
 4944        self.available_code_actions.take();
 4945    }
 4946
 4947    pub fn push_code_action_provider(
 4948        &mut self,
 4949        provider: Arc<dyn CodeActionProvider>,
 4950        cx: &mut ViewContext<Self>,
 4951    ) {
 4952        self.code_action_providers.push(provider);
 4953        self.refresh_code_actions(cx);
 4954    }
 4955
 4956    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4957        let buffer = self.buffer.read(cx);
 4958        let newest_selection = self.selections.newest_anchor().clone();
 4959        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4960        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4961        if start_buffer != end_buffer {
 4962            return None;
 4963        }
 4964
 4965        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4966            cx.background_executor()
 4967                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4968                .await;
 4969
 4970            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4971                let providers = this.code_action_providers.clone();
 4972                let tasks = this
 4973                    .code_action_providers
 4974                    .iter()
 4975                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4976                    .collect::<Vec<_>>();
 4977                (providers, tasks)
 4978            })?;
 4979
 4980            let mut actions = Vec::new();
 4981            for (provider, provider_actions) in
 4982                providers.into_iter().zip(future::join_all(tasks).await)
 4983            {
 4984                if let Some(provider_actions) = provider_actions.log_err() {
 4985                    actions.extend(provider_actions.into_iter().map(|action| {
 4986                        AvailableCodeAction {
 4987                            excerpt_id: newest_selection.start.excerpt_id,
 4988                            action,
 4989                            provider: provider.clone(),
 4990                        }
 4991                    }));
 4992                }
 4993            }
 4994
 4995            this.update(&mut cx, |this, cx| {
 4996                this.available_code_actions = if actions.is_empty() {
 4997                    None
 4998                } else {
 4999                    Some((
 5000                        Location {
 5001                            buffer: start_buffer,
 5002                            range: start..end,
 5003                        },
 5004                        actions.into(),
 5005                    ))
 5006                };
 5007                cx.notify();
 5008            })
 5009        }));
 5010        None
 5011    }
 5012
 5013    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5014        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5015            self.show_git_blame_inline = false;
 5016
 5017            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5018                cx.background_executor().timer(delay).await;
 5019
 5020                this.update(&mut cx, |this, cx| {
 5021                    this.show_git_blame_inline = true;
 5022                    cx.notify();
 5023                })
 5024                .log_err();
 5025            }));
 5026        }
 5027    }
 5028
 5029    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5030        if self.pending_rename.is_some() {
 5031            return None;
 5032        }
 5033
 5034        let provider = self.semantics_provider.clone()?;
 5035        let buffer = self.buffer.read(cx);
 5036        let newest_selection = self.selections.newest_anchor().clone();
 5037        let cursor_position = newest_selection.head();
 5038        let (cursor_buffer, cursor_buffer_position) =
 5039            buffer.text_anchor_for_position(cursor_position, cx)?;
 5040        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5041        if cursor_buffer != tail_buffer {
 5042            return None;
 5043        }
 5044
 5045        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5046            cx.background_executor()
 5047                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5048                .await;
 5049
 5050            let highlights = if let Some(highlights) = cx
 5051                .update(|cx| {
 5052                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5053                })
 5054                .ok()
 5055                .flatten()
 5056            {
 5057                highlights.await.log_err()
 5058            } else {
 5059                None
 5060            };
 5061
 5062            if let Some(highlights) = highlights {
 5063                this.update(&mut cx, |this, cx| {
 5064                    if this.pending_rename.is_some() {
 5065                        return;
 5066                    }
 5067
 5068                    let buffer_id = cursor_position.buffer_id;
 5069                    let buffer = this.buffer.read(cx);
 5070                    if !buffer
 5071                        .text_anchor_for_position(cursor_position, cx)
 5072                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5073                    {
 5074                        return;
 5075                    }
 5076
 5077                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5078                    let mut write_ranges = Vec::new();
 5079                    let mut read_ranges = Vec::new();
 5080                    for highlight in highlights {
 5081                        for (excerpt_id, excerpt_range) in
 5082                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5083                        {
 5084                            let start = highlight
 5085                                .range
 5086                                .start
 5087                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5088                            let end = highlight
 5089                                .range
 5090                                .end
 5091                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5092                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5093                                continue;
 5094                            }
 5095
 5096                            let range = Anchor {
 5097                                buffer_id,
 5098                                excerpt_id,
 5099                                text_anchor: start,
 5100                            }..Anchor {
 5101                                buffer_id,
 5102                                excerpt_id,
 5103                                text_anchor: end,
 5104                            };
 5105                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5106                                write_ranges.push(range);
 5107                            } else {
 5108                                read_ranges.push(range);
 5109                            }
 5110                        }
 5111                    }
 5112
 5113                    this.highlight_background::<DocumentHighlightRead>(
 5114                        &read_ranges,
 5115                        |theme| theme.editor_document_highlight_read_background,
 5116                        cx,
 5117                    );
 5118                    this.highlight_background::<DocumentHighlightWrite>(
 5119                        &write_ranges,
 5120                        |theme| theme.editor_document_highlight_write_background,
 5121                        cx,
 5122                    );
 5123                    cx.notify();
 5124                })
 5125                .log_err();
 5126            }
 5127        }));
 5128        None
 5129    }
 5130
 5131    pub fn refresh_inline_completion(
 5132        &mut self,
 5133        debounce: bool,
 5134        user_requested: bool,
 5135        cx: &mut ViewContext<Self>,
 5136    ) -> Option<()> {
 5137        let provider = self.inline_completion_provider()?;
 5138        let cursor = self.selections.newest_anchor().head();
 5139        let (buffer, cursor_buffer_position) =
 5140            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5141
 5142        if !user_requested
 5143            && (!self.enable_inline_completions
 5144                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5145        {
 5146            self.discard_inline_completion(false, cx);
 5147            return None;
 5148        }
 5149
 5150        self.update_visible_inline_completion(cx);
 5151        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5152        Some(())
 5153    }
 5154
 5155    fn cycle_inline_completion(
 5156        &mut self,
 5157        direction: Direction,
 5158        cx: &mut ViewContext<Self>,
 5159    ) -> Option<()> {
 5160        let provider = self.inline_completion_provider()?;
 5161        let cursor = self.selections.newest_anchor().head();
 5162        let (buffer, cursor_buffer_position) =
 5163            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5164        if !self.enable_inline_completions
 5165            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5166        {
 5167            return None;
 5168        }
 5169
 5170        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5171        self.update_visible_inline_completion(cx);
 5172
 5173        Some(())
 5174    }
 5175
 5176    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5177        if !self.has_active_inline_completion(cx) {
 5178            self.refresh_inline_completion(false, true, cx);
 5179            return;
 5180        }
 5181
 5182        self.update_visible_inline_completion(cx);
 5183    }
 5184
 5185    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5186        self.show_cursor_names(cx);
 5187    }
 5188
 5189    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5190        self.show_cursor_names = true;
 5191        cx.notify();
 5192        cx.spawn(|this, mut cx| async move {
 5193            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5194            this.update(&mut cx, |this, cx| {
 5195                this.show_cursor_names = false;
 5196                cx.notify()
 5197            })
 5198            .ok()
 5199        })
 5200        .detach();
 5201    }
 5202
 5203    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5204        if self.has_active_inline_completion(cx) {
 5205            self.cycle_inline_completion(Direction::Next, cx);
 5206        } else {
 5207            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5208            if is_copilot_disabled {
 5209                cx.propagate();
 5210            }
 5211        }
 5212    }
 5213
 5214    pub fn previous_inline_completion(
 5215        &mut self,
 5216        _: &PreviousInlineCompletion,
 5217        cx: &mut ViewContext<Self>,
 5218    ) {
 5219        if self.has_active_inline_completion(cx) {
 5220            self.cycle_inline_completion(Direction::Prev, cx);
 5221        } else {
 5222            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5223            if is_copilot_disabled {
 5224                cx.propagate();
 5225            }
 5226        }
 5227    }
 5228
 5229    pub fn accept_inline_completion(
 5230        &mut self,
 5231        _: &AcceptInlineCompletion,
 5232        cx: &mut ViewContext<Self>,
 5233    ) {
 5234        let Some(completion) = self.take_active_inline_completion(cx) else {
 5235            return;
 5236        };
 5237        if let Some(provider) = self.inline_completion_provider() {
 5238            provider.accept(cx);
 5239        }
 5240
 5241        cx.emit(EditorEvent::InputHandled {
 5242            utf16_range_to_replace: None,
 5243            text: completion.text.to_string().into(),
 5244        });
 5245
 5246        if let Some(range) = completion.delete_range {
 5247            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5248        }
 5249        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5250        self.refresh_inline_completion(true, true, cx);
 5251        cx.notify();
 5252    }
 5253
 5254    pub fn accept_partial_inline_completion(
 5255        &mut self,
 5256        _: &AcceptPartialInlineCompletion,
 5257        cx: &mut ViewContext<Self>,
 5258    ) {
 5259        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5260            if let Some(completion) = self.take_active_inline_completion(cx) {
 5261                let mut partial_completion = completion
 5262                    .text
 5263                    .chars()
 5264                    .by_ref()
 5265                    .take_while(|c| c.is_alphabetic())
 5266                    .collect::<String>();
 5267                if partial_completion.is_empty() {
 5268                    partial_completion = completion
 5269                        .text
 5270                        .chars()
 5271                        .by_ref()
 5272                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5273                        .collect::<String>();
 5274                }
 5275
 5276                cx.emit(EditorEvent::InputHandled {
 5277                    utf16_range_to_replace: None,
 5278                    text: partial_completion.clone().into(),
 5279                });
 5280
 5281                if let Some(range) = completion.delete_range {
 5282                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5283                }
 5284                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5285
 5286                self.refresh_inline_completion(true, true, cx);
 5287                cx.notify();
 5288            }
 5289        }
 5290    }
 5291
 5292    fn discard_inline_completion(
 5293        &mut self,
 5294        should_report_inline_completion_event: bool,
 5295        cx: &mut ViewContext<Self>,
 5296    ) -> bool {
 5297        if let Some(provider) = self.inline_completion_provider() {
 5298            provider.discard(should_report_inline_completion_event, cx);
 5299        }
 5300
 5301        self.take_active_inline_completion(cx).is_some()
 5302    }
 5303
 5304    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5305        if let Some(completion) = self.active_inline_completion.as_ref() {
 5306            let buffer = self.buffer.read(cx).read(cx);
 5307            completion.position.is_valid(&buffer)
 5308        } else {
 5309            false
 5310        }
 5311    }
 5312
 5313    fn take_active_inline_completion(
 5314        &mut self,
 5315        cx: &mut ViewContext<Self>,
 5316    ) -> Option<CompletionState> {
 5317        let completion = self.active_inline_completion.take()?;
 5318        let render_inlay_ids = completion.render_inlay_ids.clone();
 5319        self.display_map.update(cx, |map, cx| {
 5320            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5321        });
 5322        let buffer = self.buffer.read(cx).read(cx);
 5323
 5324        if completion.position.is_valid(&buffer) {
 5325            Some(completion)
 5326        } else {
 5327            None
 5328        }
 5329    }
 5330
 5331    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5332        let selection = self.selections.newest_anchor();
 5333        let cursor = selection.head();
 5334
 5335        let excerpt_id = cursor.excerpt_id;
 5336
 5337        if self.context_menu.read().is_none()
 5338            && self.completion_tasks.is_empty()
 5339            && selection.start == selection.end
 5340        {
 5341            if let Some(provider) = self.inline_completion_provider() {
 5342                if let Some((buffer, cursor_buffer_position)) =
 5343                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5344                {
 5345                    if let Some(proposal) =
 5346                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5347                    {
 5348                        let mut to_remove = Vec::new();
 5349                        if let Some(completion) = self.active_inline_completion.take() {
 5350                            to_remove.extend(completion.render_inlay_ids.iter());
 5351                        }
 5352
 5353                        let to_add = proposal
 5354                            .inlays
 5355                            .iter()
 5356                            .filter_map(|inlay| {
 5357                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5358                                let id = post_inc(&mut self.next_inlay_id);
 5359                                match inlay {
 5360                                    InlayProposal::Hint(position, hint) => {
 5361                                        let position =
 5362                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5363                                        Some(Inlay::hint(id, position, hint))
 5364                                    }
 5365                                    InlayProposal::Suggestion(position, text) => {
 5366                                        let position =
 5367                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5368                                        Some(Inlay::suggestion(id, position, text.clone()))
 5369                                    }
 5370                                }
 5371                            })
 5372                            .collect_vec();
 5373
 5374                        self.active_inline_completion = Some(CompletionState {
 5375                            position: cursor,
 5376                            text: proposal.text,
 5377                            delete_range: proposal.delete_range.and_then(|range| {
 5378                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5379                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5380                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5381                                Some(start?..end?)
 5382                            }),
 5383                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5384                        });
 5385
 5386                        self.display_map
 5387                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5388
 5389                        cx.notify();
 5390                        return;
 5391                    }
 5392                }
 5393            }
 5394        }
 5395
 5396        self.discard_inline_completion(false, cx);
 5397    }
 5398
 5399    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5400        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5401    }
 5402
 5403    fn render_code_actions_indicator(
 5404        &self,
 5405        _style: &EditorStyle,
 5406        row: DisplayRow,
 5407        is_active: bool,
 5408        cx: &mut ViewContext<Self>,
 5409    ) -> Option<IconButton> {
 5410        if self.available_code_actions.is_some() {
 5411            Some(
 5412                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5413                    .shape(ui::IconButtonShape::Square)
 5414                    .icon_size(IconSize::XSmall)
 5415                    .icon_color(Color::Muted)
 5416                    .selected(is_active)
 5417                    .tooltip({
 5418                        let focus_handle = self.focus_handle.clone();
 5419                        move |cx| {
 5420                            Tooltip::for_action_in(
 5421                                "Toggle Code Actions",
 5422                                &ToggleCodeActions {
 5423                                    deployed_from_indicator: None,
 5424                                },
 5425                                &focus_handle,
 5426                                cx,
 5427                            )
 5428                        }
 5429                    })
 5430                    .on_click(cx.listener(move |editor, _e, cx| {
 5431                        editor.focus(cx);
 5432                        editor.toggle_code_actions(
 5433                            &ToggleCodeActions {
 5434                                deployed_from_indicator: Some(row),
 5435                            },
 5436                            cx,
 5437                        );
 5438                    })),
 5439            )
 5440        } else {
 5441            None
 5442        }
 5443    }
 5444
 5445    fn clear_tasks(&mut self) {
 5446        self.tasks.clear()
 5447    }
 5448
 5449    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5450        if self.tasks.insert(key, value).is_some() {
 5451            // This case should hopefully be rare, but just in case...
 5452            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5453        }
 5454    }
 5455
 5456    fn render_run_indicator(
 5457        &self,
 5458        _style: &EditorStyle,
 5459        is_active: bool,
 5460        row: DisplayRow,
 5461        cx: &mut ViewContext<Self>,
 5462    ) -> IconButton {
 5463        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5464            .shape(ui::IconButtonShape::Square)
 5465            .icon_size(IconSize::XSmall)
 5466            .icon_color(Color::Muted)
 5467            .selected(is_active)
 5468            .on_click(cx.listener(move |editor, _e, cx| {
 5469                editor.focus(cx);
 5470                editor.toggle_code_actions(
 5471                    &ToggleCodeActions {
 5472                        deployed_from_indicator: Some(row),
 5473                    },
 5474                    cx,
 5475                );
 5476            }))
 5477    }
 5478
 5479    pub fn context_menu_visible(&self) -> bool {
 5480        self.context_menu
 5481            .read()
 5482            .as_ref()
 5483            .map_or(false, |menu| menu.visible())
 5484    }
 5485
 5486    fn render_context_menu(
 5487        &self,
 5488        cursor_position: DisplayPoint,
 5489        style: &EditorStyle,
 5490        max_height: Pixels,
 5491        cx: &mut ViewContext<Editor>,
 5492    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5493        self.context_menu.read().as_ref().map(|menu| {
 5494            menu.render(
 5495                cursor_position,
 5496                style,
 5497                max_height,
 5498                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5499                cx,
 5500            )
 5501        })
 5502    }
 5503
 5504    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5505        cx.notify();
 5506        self.completion_tasks.clear();
 5507        let context_menu = self.context_menu.write().take();
 5508        if context_menu.is_some() {
 5509            self.update_visible_inline_completion(cx);
 5510        }
 5511        context_menu
 5512    }
 5513
 5514    pub fn insert_snippet(
 5515        &mut self,
 5516        insertion_ranges: &[Range<usize>],
 5517        snippet: Snippet,
 5518        cx: &mut ViewContext<Self>,
 5519    ) -> Result<()> {
 5520        struct Tabstop<T> {
 5521            is_end_tabstop: bool,
 5522            ranges: Vec<Range<T>>,
 5523        }
 5524
 5525        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5526            let snippet_text: Arc<str> = snippet.text.clone().into();
 5527            buffer.edit(
 5528                insertion_ranges
 5529                    .iter()
 5530                    .cloned()
 5531                    .map(|range| (range, snippet_text.clone())),
 5532                Some(AutoindentMode::EachLine),
 5533                cx,
 5534            );
 5535
 5536            let snapshot = &*buffer.read(cx);
 5537            let snippet = &snippet;
 5538            snippet
 5539                .tabstops
 5540                .iter()
 5541                .map(|tabstop| {
 5542                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5543                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5544                    });
 5545                    let mut tabstop_ranges = tabstop
 5546                        .iter()
 5547                        .flat_map(|tabstop_range| {
 5548                            let mut delta = 0_isize;
 5549                            insertion_ranges.iter().map(move |insertion_range| {
 5550                                let insertion_start = insertion_range.start as isize + delta;
 5551                                delta +=
 5552                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5553
 5554                                let start = ((insertion_start + tabstop_range.start) as usize)
 5555                                    .min(snapshot.len());
 5556                                let end = ((insertion_start + tabstop_range.end) as usize)
 5557                                    .min(snapshot.len());
 5558                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5559                            })
 5560                        })
 5561                        .collect::<Vec<_>>();
 5562                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5563
 5564                    Tabstop {
 5565                        is_end_tabstop,
 5566                        ranges: tabstop_ranges,
 5567                    }
 5568                })
 5569                .collect::<Vec<_>>()
 5570        });
 5571        if let Some(tabstop) = tabstops.first() {
 5572            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5573                s.select_ranges(tabstop.ranges.iter().cloned());
 5574            });
 5575
 5576            // If we're already at the last tabstop and it's at the end of the snippet,
 5577            // we're done, we don't need to keep the state around.
 5578            if !tabstop.is_end_tabstop {
 5579                let ranges = tabstops
 5580                    .into_iter()
 5581                    .map(|tabstop| tabstop.ranges)
 5582                    .collect::<Vec<_>>();
 5583                self.snippet_stack.push(SnippetState {
 5584                    active_index: 0,
 5585                    ranges,
 5586                });
 5587            }
 5588
 5589            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5590            if self.autoclose_regions.is_empty() {
 5591                let snapshot = self.buffer.read(cx).snapshot(cx);
 5592                for selection in &mut self.selections.all::<Point>(cx) {
 5593                    let selection_head = selection.head();
 5594                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5595                        continue;
 5596                    };
 5597
 5598                    let mut bracket_pair = None;
 5599                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5600                    let prev_chars = snapshot
 5601                        .reversed_chars_at(selection_head)
 5602                        .collect::<String>();
 5603                    for (pair, enabled) in scope.brackets() {
 5604                        if enabled
 5605                            && pair.close
 5606                            && prev_chars.starts_with(pair.start.as_str())
 5607                            && next_chars.starts_with(pair.end.as_str())
 5608                        {
 5609                            bracket_pair = Some(pair.clone());
 5610                            break;
 5611                        }
 5612                    }
 5613                    if let Some(pair) = bracket_pair {
 5614                        let start = snapshot.anchor_after(selection_head);
 5615                        let end = snapshot.anchor_after(selection_head);
 5616                        self.autoclose_regions.push(AutocloseRegion {
 5617                            selection_id: selection.id,
 5618                            range: start..end,
 5619                            pair,
 5620                        });
 5621                    }
 5622                }
 5623            }
 5624        }
 5625        Ok(())
 5626    }
 5627
 5628    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5629        self.move_to_snippet_tabstop(Bias::Right, cx)
 5630    }
 5631
 5632    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5633        self.move_to_snippet_tabstop(Bias::Left, cx)
 5634    }
 5635
 5636    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5637        if let Some(mut snippet) = self.snippet_stack.pop() {
 5638            match bias {
 5639                Bias::Left => {
 5640                    if snippet.active_index > 0 {
 5641                        snippet.active_index -= 1;
 5642                    } else {
 5643                        self.snippet_stack.push(snippet);
 5644                        return false;
 5645                    }
 5646                }
 5647                Bias::Right => {
 5648                    if snippet.active_index + 1 < snippet.ranges.len() {
 5649                        snippet.active_index += 1;
 5650                    } else {
 5651                        self.snippet_stack.push(snippet);
 5652                        return false;
 5653                    }
 5654                }
 5655            }
 5656            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5657                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5658                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5659                });
 5660                // If snippet state is not at the last tabstop, push it back on the stack
 5661                if snippet.active_index + 1 < snippet.ranges.len() {
 5662                    self.snippet_stack.push(snippet);
 5663                }
 5664                return true;
 5665            }
 5666        }
 5667
 5668        false
 5669    }
 5670
 5671    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5672        self.transact(cx, |this, cx| {
 5673            this.select_all(&SelectAll, cx);
 5674            this.insert("", cx);
 5675        });
 5676    }
 5677
 5678    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5679        self.transact(cx, |this, cx| {
 5680            this.select_autoclose_pair(cx);
 5681            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5682            if !this.linked_edit_ranges.is_empty() {
 5683                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5684                let snapshot = this.buffer.read(cx).snapshot(cx);
 5685
 5686                for selection in selections.iter() {
 5687                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5688                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5689                    if selection_start.buffer_id != selection_end.buffer_id {
 5690                        continue;
 5691                    }
 5692                    if let Some(ranges) =
 5693                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5694                    {
 5695                        for (buffer, entries) in ranges {
 5696                            linked_ranges.entry(buffer).or_default().extend(entries);
 5697                        }
 5698                    }
 5699                }
 5700            }
 5701
 5702            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5703            if !this.selections.line_mode {
 5704                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5705                for selection in &mut selections {
 5706                    if selection.is_empty() {
 5707                        let old_head = selection.head();
 5708                        let mut new_head =
 5709                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5710                                .to_point(&display_map);
 5711                        if let Some((buffer, line_buffer_range)) = display_map
 5712                            .buffer_snapshot
 5713                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5714                        {
 5715                            let indent_size =
 5716                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5717                            let indent_len = match indent_size.kind {
 5718                                IndentKind::Space => {
 5719                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5720                                }
 5721                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5722                            };
 5723                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5724                                let indent_len = indent_len.get();
 5725                                new_head = cmp::min(
 5726                                    new_head,
 5727                                    MultiBufferPoint::new(
 5728                                        old_head.row,
 5729                                        ((old_head.column - 1) / indent_len) * indent_len,
 5730                                    ),
 5731                                );
 5732                            }
 5733                        }
 5734
 5735                        selection.set_head(new_head, SelectionGoal::None);
 5736                    }
 5737                }
 5738            }
 5739
 5740            this.signature_help_state.set_backspace_pressed(true);
 5741            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5742            this.insert("", cx);
 5743            let empty_str: Arc<str> = Arc::from("");
 5744            for (buffer, edits) in linked_ranges {
 5745                let snapshot = buffer.read(cx).snapshot();
 5746                use text::ToPoint as TP;
 5747
 5748                let edits = edits
 5749                    .into_iter()
 5750                    .map(|range| {
 5751                        let end_point = TP::to_point(&range.end, &snapshot);
 5752                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5753
 5754                        if end_point == start_point {
 5755                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5756                                .saturating_sub(1);
 5757                            start_point = TP::to_point(&offset, &snapshot);
 5758                        };
 5759
 5760                        (start_point..end_point, empty_str.clone())
 5761                    })
 5762                    .sorted_by_key(|(range, _)| range.start)
 5763                    .collect::<Vec<_>>();
 5764                buffer.update(cx, |this, cx| {
 5765                    this.edit(edits, None, cx);
 5766                })
 5767            }
 5768            this.refresh_inline_completion(true, false, cx);
 5769            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5770        });
 5771    }
 5772
 5773    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5774        self.transact(cx, |this, cx| {
 5775            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5776                let line_mode = s.line_mode;
 5777                s.move_with(|map, selection| {
 5778                    if selection.is_empty() && !line_mode {
 5779                        let cursor = movement::right(map, selection.head());
 5780                        selection.end = cursor;
 5781                        selection.reversed = true;
 5782                        selection.goal = SelectionGoal::None;
 5783                    }
 5784                })
 5785            });
 5786            this.insert("", cx);
 5787            this.refresh_inline_completion(true, false, cx);
 5788        });
 5789    }
 5790
 5791    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5792        if self.move_to_prev_snippet_tabstop(cx) {
 5793            return;
 5794        }
 5795
 5796        self.outdent(&Outdent, cx);
 5797    }
 5798
 5799    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5800        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5801            return;
 5802        }
 5803
 5804        let mut selections = self.selections.all_adjusted(cx);
 5805        let buffer = self.buffer.read(cx);
 5806        let snapshot = buffer.snapshot(cx);
 5807        let rows_iter = selections.iter().map(|s| s.head().row);
 5808        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5809
 5810        let mut edits = Vec::new();
 5811        let mut prev_edited_row = 0;
 5812        let mut row_delta = 0;
 5813        for selection in &mut selections {
 5814            if selection.start.row != prev_edited_row {
 5815                row_delta = 0;
 5816            }
 5817            prev_edited_row = selection.end.row;
 5818
 5819            // If the selection is non-empty, then increase the indentation of the selected lines.
 5820            if !selection.is_empty() {
 5821                row_delta =
 5822                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5823                continue;
 5824            }
 5825
 5826            // If the selection is empty and the cursor is in the leading whitespace before the
 5827            // suggested indentation, then auto-indent the line.
 5828            let cursor = selection.head();
 5829            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5830            if let Some(suggested_indent) =
 5831                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5832            {
 5833                if cursor.column < suggested_indent.len
 5834                    && cursor.column <= current_indent.len
 5835                    && current_indent.len <= suggested_indent.len
 5836                {
 5837                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5838                    selection.end = selection.start;
 5839                    if row_delta == 0 {
 5840                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5841                            cursor.row,
 5842                            current_indent,
 5843                            suggested_indent,
 5844                        ));
 5845                        row_delta = suggested_indent.len - current_indent.len;
 5846                    }
 5847                    continue;
 5848                }
 5849            }
 5850
 5851            // Otherwise, insert a hard or soft tab.
 5852            let settings = buffer.settings_at(cursor, cx);
 5853            let tab_size = if settings.hard_tabs {
 5854                IndentSize::tab()
 5855            } else {
 5856                let tab_size = settings.tab_size.get();
 5857                let char_column = snapshot
 5858                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5859                    .flat_map(str::chars)
 5860                    .count()
 5861                    + row_delta as usize;
 5862                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5863                IndentSize::spaces(chars_to_next_tab_stop)
 5864            };
 5865            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5866            selection.end = selection.start;
 5867            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5868            row_delta += tab_size.len;
 5869        }
 5870
 5871        self.transact(cx, |this, cx| {
 5872            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5873            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5874            this.refresh_inline_completion(true, false, cx);
 5875        });
 5876    }
 5877
 5878    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5879        if self.read_only(cx) {
 5880            return;
 5881        }
 5882        let mut selections = self.selections.all::<Point>(cx);
 5883        let mut prev_edited_row = 0;
 5884        let mut row_delta = 0;
 5885        let mut edits = Vec::new();
 5886        let buffer = self.buffer.read(cx);
 5887        let snapshot = buffer.snapshot(cx);
 5888        for selection in &mut selections {
 5889            if selection.start.row != prev_edited_row {
 5890                row_delta = 0;
 5891            }
 5892            prev_edited_row = selection.end.row;
 5893
 5894            row_delta =
 5895                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5896        }
 5897
 5898        self.transact(cx, |this, cx| {
 5899            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5900            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5901        });
 5902    }
 5903
 5904    fn indent_selection(
 5905        buffer: &MultiBuffer,
 5906        snapshot: &MultiBufferSnapshot,
 5907        selection: &mut Selection<Point>,
 5908        edits: &mut Vec<(Range<Point>, String)>,
 5909        delta_for_start_row: u32,
 5910        cx: &AppContext,
 5911    ) -> u32 {
 5912        let settings = buffer.settings_at(selection.start, cx);
 5913        let tab_size = settings.tab_size.get();
 5914        let indent_kind = if settings.hard_tabs {
 5915            IndentKind::Tab
 5916        } else {
 5917            IndentKind::Space
 5918        };
 5919        let mut start_row = selection.start.row;
 5920        let mut end_row = selection.end.row + 1;
 5921
 5922        // If a selection ends at the beginning of a line, don't indent
 5923        // that last line.
 5924        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5925            end_row -= 1;
 5926        }
 5927
 5928        // Avoid re-indenting a row that has already been indented by a
 5929        // previous selection, but still update this selection's column
 5930        // to reflect that indentation.
 5931        if delta_for_start_row > 0 {
 5932            start_row += 1;
 5933            selection.start.column += delta_for_start_row;
 5934            if selection.end.row == selection.start.row {
 5935                selection.end.column += delta_for_start_row;
 5936            }
 5937        }
 5938
 5939        let mut delta_for_end_row = 0;
 5940        let has_multiple_rows = start_row + 1 != end_row;
 5941        for row in start_row..end_row {
 5942            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5943            let indent_delta = match (current_indent.kind, indent_kind) {
 5944                (IndentKind::Space, IndentKind::Space) => {
 5945                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5946                    IndentSize::spaces(columns_to_next_tab_stop)
 5947                }
 5948                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5949                (_, IndentKind::Tab) => IndentSize::tab(),
 5950            };
 5951
 5952            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5953                0
 5954            } else {
 5955                selection.start.column
 5956            };
 5957            let row_start = Point::new(row, start);
 5958            edits.push((
 5959                row_start..row_start,
 5960                indent_delta.chars().collect::<String>(),
 5961            ));
 5962
 5963            // Update this selection's endpoints to reflect the indentation.
 5964            if row == selection.start.row {
 5965                selection.start.column += indent_delta.len;
 5966            }
 5967            if row == selection.end.row {
 5968                selection.end.column += indent_delta.len;
 5969                delta_for_end_row = indent_delta.len;
 5970            }
 5971        }
 5972
 5973        if selection.start.row == selection.end.row {
 5974            delta_for_start_row + delta_for_end_row
 5975        } else {
 5976            delta_for_end_row
 5977        }
 5978    }
 5979
 5980    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5981        if self.read_only(cx) {
 5982            return;
 5983        }
 5984        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5985        let selections = self.selections.all::<Point>(cx);
 5986        let mut deletion_ranges = Vec::new();
 5987        let mut last_outdent = None;
 5988        {
 5989            let buffer = self.buffer.read(cx);
 5990            let snapshot = buffer.snapshot(cx);
 5991            for selection in &selections {
 5992                let settings = buffer.settings_at(selection.start, cx);
 5993                let tab_size = settings.tab_size.get();
 5994                let mut rows = selection.spanned_rows(false, &display_map);
 5995
 5996                // Avoid re-outdenting a row that has already been outdented by a
 5997                // previous selection.
 5998                if let Some(last_row) = last_outdent {
 5999                    if last_row == rows.start {
 6000                        rows.start = rows.start.next_row();
 6001                    }
 6002                }
 6003                let has_multiple_rows = rows.len() > 1;
 6004                for row in rows.iter_rows() {
 6005                    let indent_size = snapshot.indent_size_for_line(row);
 6006                    if indent_size.len > 0 {
 6007                        let deletion_len = match indent_size.kind {
 6008                            IndentKind::Space => {
 6009                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6010                                if columns_to_prev_tab_stop == 0 {
 6011                                    tab_size
 6012                                } else {
 6013                                    columns_to_prev_tab_stop
 6014                                }
 6015                            }
 6016                            IndentKind::Tab => 1,
 6017                        };
 6018                        let start = if has_multiple_rows
 6019                            || deletion_len > selection.start.column
 6020                            || indent_size.len < selection.start.column
 6021                        {
 6022                            0
 6023                        } else {
 6024                            selection.start.column - deletion_len
 6025                        };
 6026                        deletion_ranges.push(
 6027                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6028                        );
 6029                        last_outdent = Some(row);
 6030                    }
 6031                }
 6032            }
 6033        }
 6034
 6035        self.transact(cx, |this, cx| {
 6036            this.buffer.update(cx, |buffer, cx| {
 6037                let empty_str: Arc<str> = Arc::default();
 6038                buffer.edit(
 6039                    deletion_ranges
 6040                        .into_iter()
 6041                        .map(|range| (range, empty_str.clone())),
 6042                    None,
 6043                    cx,
 6044                );
 6045            });
 6046            let selections = this.selections.all::<usize>(cx);
 6047            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6048        });
 6049    }
 6050
 6051    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6052        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6053        let selections = self.selections.all::<Point>(cx);
 6054
 6055        let mut new_cursors = Vec::new();
 6056        let mut edit_ranges = Vec::new();
 6057        let mut selections = selections.iter().peekable();
 6058        while let Some(selection) = selections.next() {
 6059            let mut rows = selection.spanned_rows(false, &display_map);
 6060            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6061
 6062            // Accumulate contiguous regions of rows that we want to delete.
 6063            while let Some(next_selection) = selections.peek() {
 6064                let next_rows = next_selection.spanned_rows(false, &display_map);
 6065                if next_rows.start <= rows.end {
 6066                    rows.end = next_rows.end;
 6067                    selections.next().unwrap();
 6068                } else {
 6069                    break;
 6070                }
 6071            }
 6072
 6073            let buffer = &display_map.buffer_snapshot;
 6074            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6075            let edit_end;
 6076            let cursor_buffer_row;
 6077            if buffer.max_point().row >= rows.end.0 {
 6078                // If there's a line after the range, delete the \n from the end of the row range
 6079                // and position the cursor on the next line.
 6080                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6081                cursor_buffer_row = rows.end;
 6082            } else {
 6083                // If there isn't a line after the range, delete the \n from the line before the
 6084                // start of the row range and position the cursor there.
 6085                edit_start = edit_start.saturating_sub(1);
 6086                edit_end = buffer.len();
 6087                cursor_buffer_row = rows.start.previous_row();
 6088            }
 6089
 6090            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6091            *cursor.column_mut() =
 6092                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6093
 6094            new_cursors.push((
 6095                selection.id,
 6096                buffer.anchor_after(cursor.to_point(&display_map)),
 6097            ));
 6098            edit_ranges.push(edit_start..edit_end);
 6099        }
 6100
 6101        self.transact(cx, |this, cx| {
 6102            let buffer = this.buffer.update(cx, |buffer, cx| {
 6103                let empty_str: Arc<str> = Arc::default();
 6104                buffer.edit(
 6105                    edit_ranges
 6106                        .into_iter()
 6107                        .map(|range| (range, empty_str.clone())),
 6108                    None,
 6109                    cx,
 6110                );
 6111                buffer.snapshot(cx)
 6112            });
 6113            let new_selections = new_cursors
 6114                .into_iter()
 6115                .map(|(id, cursor)| {
 6116                    let cursor = cursor.to_point(&buffer);
 6117                    Selection {
 6118                        id,
 6119                        start: cursor,
 6120                        end: cursor,
 6121                        reversed: false,
 6122                        goal: SelectionGoal::None,
 6123                    }
 6124                })
 6125                .collect();
 6126
 6127            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6128                s.select(new_selections);
 6129            });
 6130        });
 6131    }
 6132
 6133    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6134        if self.read_only(cx) {
 6135            return;
 6136        }
 6137        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6138        for selection in self.selections.all::<Point>(cx) {
 6139            let start = MultiBufferRow(selection.start.row);
 6140            let end = if selection.start.row == selection.end.row {
 6141                MultiBufferRow(selection.start.row + 1)
 6142            } else {
 6143                MultiBufferRow(selection.end.row)
 6144            };
 6145
 6146            if let Some(last_row_range) = row_ranges.last_mut() {
 6147                if start <= last_row_range.end {
 6148                    last_row_range.end = end;
 6149                    continue;
 6150                }
 6151            }
 6152            row_ranges.push(start..end);
 6153        }
 6154
 6155        let snapshot = self.buffer.read(cx).snapshot(cx);
 6156        let mut cursor_positions = Vec::new();
 6157        for row_range in &row_ranges {
 6158            let anchor = snapshot.anchor_before(Point::new(
 6159                row_range.end.previous_row().0,
 6160                snapshot.line_len(row_range.end.previous_row()),
 6161            ));
 6162            cursor_positions.push(anchor..anchor);
 6163        }
 6164
 6165        self.transact(cx, |this, cx| {
 6166            for row_range in row_ranges.into_iter().rev() {
 6167                for row in row_range.iter_rows().rev() {
 6168                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6169                    let next_line_row = row.next_row();
 6170                    let indent = snapshot.indent_size_for_line(next_line_row);
 6171                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6172
 6173                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6174                        " "
 6175                    } else {
 6176                        ""
 6177                    };
 6178
 6179                    this.buffer.update(cx, |buffer, cx| {
 6180                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6181                    });
 6182                }
 6183            }
 6184
 6185            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6186                s.select_anchor_ranges(cursor_positions)
 6187            });
 6188        });
 6189    }
 6190
 6191    pub fn sort_lines_case_sensitive(
 6192        &mut self,
 6193        _: &SortLinesCaseSensitive,
 6194        cx: &mut ViewContext<Self>,
 6195    ) {
 6196        self.manipulate_lines(cx, |lines| lines.sort())
 6197    }
 6198
 6199    pub fn sort_lines_case_insensitive(
 6200        &mut self,
 6201        _: &SortLinesCaseInsensitive,
 6202        cx: &mut ViewContext<Self>,
 6203    ) {
 6204        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6205    }
 6206
 6207    pub fn unique_lines_case_insensitive(
 6208        &mut self,
 6209        _: &UniqueLinesCaseInsensitive,
 6210        cx: &mut ViewContext<Self>,
 6211    ) {
 6212        self.manipulate_lines(cx, |lines| {
 6213            let mut seen = HashSet::default();
 6214            lines.retain(|line| seen.insert(line.to_lowercase()));
 6215        })
 6216    }
 6217
 6218    pub fn unique_lines_case_sensitive(
 6219        &mut self,
 6220        _: &UniqueLinesCaseSensitive,
 6221        cx: &mut ViewContext<Self>,
 6222    ) {
 6223        self.manipulate_lines(cx, |lines| {
 6224            let mut seen = HashSet::default();
 6225            lines.retain(|line| seen.insert(*line));
 6226        })
 6227    }
 6228
 6229    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6230        let mut revert_changes = HashMap::default();
 6231        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6232        for hunk in hunks_for_rows(
 6233            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6234            &multi_buffer_snapshot,
 6235        ) {
 6236            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6237        }
 6238        if !revert_changes.is_empty() {
 6239            self.transact(cx, |editor, cx| {
 6240                editor.revert(revert_changes, cx);
 6241            });
 6242        }
 6243    }
 6244
 6245    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6246        let Some(project) = self.project.clone() else {
 6247            return;
 6248        };
 6249        self.reload(project, cx).detach_and_notify_err(cx);
 6250    }
 6251
 6252    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6253        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6254        if !revert_changes.is_empty() {
 6255            self.transact(cx, |editor, cx| {
 6256                editor.revert(revert_changes, cx);
 6257            });
 6258        }
 6259    }
 6260
 6261    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6262        let snapshot = self.buffer.read(cx).snapshot(cx);
 6263        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6264        let mut ranges_by_buffer = HashMap::default();
 6265        self.transact(cx, |editor, cx| {
 6266            for hunk in hunks {
 6267                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6268                    ranges_by_buffer
 6269                        .entry(buffer.clone())
 6270                        .or_insert_with(Vec::new)
 6271                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 6272                }
 6273            }
 6274
 6275            for (buffer, ranges) in ranges_by_buffer {
 6276                buffer.update(cx, |buffer, cx| {
 6277                    buffer.merge_into_base(ranges, cx);
 6278                });
 6279            }
 6280        });
 6281    }
 6282
 6283    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6284        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6285            let project_path = buffer.read(cx).project_path(cx)?;
 6286            let project = self.project.as_ref()?.read(cx);
 6287            let entry = project.entry_for_path(&project_path, cx)?;
 6288            let abs_path = project.absolute_path(&project_path, cx)?;
 6289            let parent = if entry.is_symlink {
 6290                abs_path.canonicalize().ok()?
 6291            } else {
 6292                abs_path
 6293            }
 6294            .parent()?
 6295            .to_path_buf();
 6296            Some(parent)
 6297        }) {
 6298            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6299        }
 6300    }
 6301
 6302    fn gather_revert_changes(
 6303        &mut self,
 6304        selections: &[Selection<Anchor>],
 6305        cx: &mut ViewContext<'_, Editor>,
 6306    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6307        let mut revert_changes = HashMap::default();
 6308        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6309        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6310            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6311        }
 6312        revert_changes
 6313    }
 6314
 6315    pub fn prepare_revert_change(
 6316        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6317        multi_buffer: &Model<MultiBuffer>,
 6318        hunk: &MultiBufferDiffHunk,
 6319        cx: &AppContext,
 6320    ) -> Option<()> {
 6321        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6322        let buffer = buffer.read(cx);
 6323        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6324        let buffer_snapshot = buffer.snapshot();
 6325        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6326        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6327            probe
 6328                .0
 6329                .start
 6330                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6331                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6332        }) {
 6333            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6334            Some(())
 6335        } else {
 6336            None
 6337        }
 6338    }
 6339
 6340    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6341        self.manipulate_lines(cx, |lines| lines.reverse())
 6342    }
 6343
 6344    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6345        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6346    }
 6347
 6348    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6349    where
 6350        Fn: FnMut(&mut Vec<&str>),
 6351    {
 6352        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6353        let buffer = self.buffer.read(cx).snapshot(cx);
 6354
 6355        let mut edits = Vec::new();
 6356
 6357        let selections = self.selections.all::<Point>(cx);
 6358        let mut selections = selections.iter().peekable();
 6359        let mut contiguous_row_selections = Vec::new();
 6360        let mut new_selections = Vec::new();
 6361        let mut added_lines = 0;
 6362        let mut removed_lines = 0;
 6363
 6364        while let Some(selection) = selections.next() {
 6365            let (start_row, end_row) = consume_contiguous_rows(
 6366                &mut contiguous_row_selections,
 6367                selection,
 6368                &display_map,
 6369                &mut selections,
 6370            );
 6371
 6372            let start_point = Point::new(start_row.0, 0);
 6373            let end_point = Point::new(
 6374                end_row.previous_row().0,
 6375                buffer.line_len(end_row.previous_row()),
 6376            );
 6377            let text = buffer
 6378                .text_for_range(start_point..end_point)
 6379                .collect::<String>();
 6380
 6381            let mut lines = text.split('\n').collect_vec();
 6382
 6383            let lines_before = lines.len();
 6384            callback(&mut lines);
 6385            let lines_after = lines.len();
 6386
 6387            edits.push((start_point..end_point, lines.join("\n")));
 6388
 6389            // Selections must change based on added and removed line count
 6390            let start_row =
 6391                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6392            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6393            new_selections.push(Selection {
 6394                id: selection.id,
 6395                start: start_row,
 6396                end: end_row,
 6397                goal: SelectionGoal::None,
 6398                reversed: selection.reversed,
 6399            });
 6400
 6401            if lines_after > lines_before {
 6402                added_lines += lines_after - lines_before;
 6403            } else if lines_before > lines_after {
 6404                removed_lines += lines_before - lines_after;
 6405            }
 6406        }
 6407
 6408        self.transact(cx, |this, cx| {
 6409            let buffer = this.buffer.update(cx, |buffer, cx| {
 6410                buffer.edit(edits, None, cx);
 6411                buffer.snapshot(cx)
 6412            });
 6413
 6414            // Recalculate offsets on newly edited buffer
 6415            let new_selections = new_selections
 6416                .iter()
 6417                .map(|s| {
 6418                    let start_point = Point::new(s.start.0, 0);
 6419                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6420                    Selection {
 6421                        id: s.id,
 6422                        start: buffer.point_to_offset(start_point),
 6423                        end: buffer.point_to_offset(end_point),
 6424                        goal: s.goal,
 6425                        reversed: s.reversed,
 6426                    }
 6427                })
 6428                .collect();
 6429
 6430            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6431                s.select(new_selections);
 6432            });
 6433
 6434            this.request_autoscroll(Autoscroll::fit(), cx);
 6435        });
 6436    }
 6437
 6438    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6439        self.manipulate_text(cx, |text| text.to_uppercase())
 6440    }
 6441
 6442    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6443        self.manipulate_text(cx, |text| text.to_lowercase())
 6444    }
 6445
 6446    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6447        self.manipulate_text(cx, |text| {
 6448            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6449            // https://github.com/rutrum/convert-case/issues/16
 6450            text.split('\n')
 6451                .map(|line| line.to_case(Case::Title))
 6452                .join("\n")
 6453        })
 6454    }
 6455
 6456    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6457        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6458    }
 6459
 6460    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6461        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6462    }
 6463
 6464    pub fn convert_to_upper_camel_case(
 6465        &mut self,
 6466        _: &ConvertToUpperCamelCase,
 6467        cx: &mut ViewContext<Self>,
 6468    ) {
 6469        self.manipulate_text(cx, |text| {
 6470            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6471            // https://github.com/rutrum/convert-case/issues/16
 6472            text.split('\n')
 6473                .map(|line| line.to_case(Case::UpperCamel))
 6474                .join("\n")
 6475        })
 6476    }
 6477
 6478    pub fn convert_to_lower_camel_case(
 6479        &mut self,
 6480        _: &ConvertToLowerCamelCase,
 6481        cx: &mut ViewContext<Self>,
 6482    ) {
 6483        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6484    }
 6485
 6486    pub fn convert_to_opposite_case(
 6487        &mut self,
 6488        _: &ConvertToOppositeCase,
 6489        cx: &mut ViewContext<Self>,
 6490    ) {
 6491        self.manipulate_text(cx, |text| {
 6492            text.chars()
 6493                .fold(String::with_capacity(text.len()), |mut t, c| {
 6494                    if c.is_uppercase() {
 6495                        t.extend(c.to_lowercase());
 6496                    } else {
 6497                        t.extend(c.to_uppercase());
 6498                    }
 6499                    t
 6500                })
 6501        })
 6502    }
 6503
 6504    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6505    where
 6506        Fn: FnMut(&str) -> String,
 6507    {
 6508        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6509        let buffer = self.buffer.read(cx).snapshot(cx);
 6510
 6511        let mut new_selections = Vec::new();
 6512        let mut edits = Vec::new();
 6513        let mut selection_adjustment = 0i32;
 6514
 6515        for selection in self.selections.all::<usize>(cx) {
 6516            let selection_is_empty = selection.is_empty();
 6517
 6518            let (start, end) = if selection_is_empty {
 6519                let word_range = movement::surrounding_word(
 6520                    &display_map,
 6521                    selection.start.to_display_point(&display_map),
 6522                );
 6523                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6524                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6525                (start, end)
 6526            } else {
 6527                (selection.start, selection.end)
 6528            };
 6529
 6530            let text = buffer.text_for_range(start..end).collect::<String>();
 6531            let old_length = text.len() as i32;
 6532            let text = callback(&text);
 6533
 6534            new_selections.push(Selection {
 6535                start: (start as i32 - selection_adjustment) as usize,
 6536                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6537                goal: SelectionGoal::None,
 6538                ..selection
 6539            });
 6540
 6541            selection_adjustment += old_length - text.len() as i32;
 6542
 6543            edits.push((start..end, text));
 6544        }
 6545
 6546        self.transact(cx, |this, cx| {
 6547            this.buffer.update(cx, |buffer, cx| {
 6548                buffer.edit(edits, None, cx);
 6549            });
 6550
 6551            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6552                s.select(new_selections);
 6553            });
 6554
 6555            this.request_autoscroll(Autoscroll::fit(), cx);
 6556        });
 6557    }
 6558
 6559    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6560        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6561        let buffer = &display_map.buffer_snapshot;
 6562        let selections = self.selections.all::<Point>(cx);
 6563
 6564        let mut edits = Vec::new();
 6565        let mut selections_iter = selections.iter().peekable();
 6566        while let Some(selection) = selections_iter.next() {
 6567            // Avoid duplicating the same lines twice.
 6568            let mut rows = selection.spanned_rows(false, &display_map);
 6569
 6570            while let Some(next_selection) = selections_iter.peek() {
 6571                let next_rows = next_selection.spanned_rows(false, &display_map);
 6572                if next_rows.start < rows.end {
 6573                    rows.end = next_rows.end;
 6574                    selections_iter.next().unwrap();
 6575                } else {
 6576                    break;
 6577                }
 6578            }
 6579
 6580            // Copy the text from the selected row region and splice it either at the start
 6581            // or end of the region.
 6582            let start = Point::new(rows.start.0, 0);
 6583            let end = Point::new(
 6584                rows.end.previous_row().0,
 6585                buffer.line_len(rows.end.previous_row()),
 6586            );
 6587            let text = buffer
 6588                .text_for_range(start..end)
 6589                .chain(Some("\n"))
 6590                .collect::<String>();
 6591            let insert_location = if upwards {
 6592                Point::new(rows.end.0, 0)
 6593            } else {
 6594                start
 6595            };
 6596            edits.push((insert_location..insert_location, text));
 6597        }
 6598
 6599        self.transact(cx, |this, cx| {
 6600            this.buffer.update(cx, |buffer, cx| {
 6601                buffer.edit(edits, None, cx);
 6602            });
 6603
 6604            this.request_autoscroll(Autoscroll::fit(), cx);
 6605        });
 6606    }
 6607
 6608    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6609        self.duplicate_line(true, cx);
 6610    }
 6611
 6612    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6613        self.duplicate_line(false, cx);
 6614    }
 6615
 6616    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6617        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6618        let buffer = self.buffer.read(cx).snapshot(cx);
 6619
 6620        let mut edits = Vec::new();
 6621        let mut unfold_ranges = Vec::new();
 6622        let mut refold_ranges = Vec::new();
 6623
 6624        let selections = self.selections.all::<Point>(cx);
 6625        let mut selections = selections.iter().peekable();
 6626        let mut contiguous_row_selections = Vec::new();
 6627        let mut new_selections = Vec::new();
 6628
 6629        while let Some(selection) = selections.next() {
 6630            // Find all the selections that span a contiguous row range
 6631            let (start_row, end_row) = consume_contiguous_rows(
 6632                &mut contiguous_row_selections,
 6633                selection,
 6634                &display_map,
 6635                &mut selections,
 6636            );
 6637
 6638            // Move the text spanned by the row range to be before the line preceding the row range
 6639            if start_row.0 > 0 {
 6640                let range_to_move = Point::new(
 6641                    start_row.previous_row().0,
 6642                    buffer.line_len(start_row.previous_row()),
 6643                )
 6644                    ..Point::new(
 6645                        end_row.previous_row().0,
 6646                        buffer.line_len(end_row.previous_row()),
 6647                    );
 6648                let insertion_point = display_map
 6649                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6650                    .0;
 6651
 6652                // Don't move lines across excerpts
 6653                if buffer
 6654                    .excerpt_boundaries_in_range((
 6655                        Bound::Excluded(insertion_point),
 6656                        Bound::Included(range_to_move.end),
 6657                    ))
 6658                    .next()
 6659                    .is_none()
 6660                {
 6661                    let text = buffer
 6662                        .text_for_range(range_to_move.clone())
 6663                        .flat_map(|s| s.chars())
 6664                        .skip(1)
 6665                        .chain(['\n'])
 6666                        .collect::<String>();
 6667
 6668                    edits.push((
 6669                        buffer.anchor_after(range_to_move.start)
 6670                            ..buffer.anchor_before(range_to_move.end),
 6671                        String::new(),
 6672                    ));
 6673                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6674                    edits.push((insertion_anchor..insertion_anchor, text));
 6675
 6676                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6677
 6678                    // Move selections up
 6679                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6680                        |mut selection| {
 6681                            selection.start.row -= row_delta;
 6682                            selection.end.row -= row_delta;
 6683                            selection
 6684                        },
 6685                    ));
 6686
 6687                    // Move folds up
 6688                    unfold_ranges.push(range_to_move.clone());
 6689                    for fold in display_map.folds_in_range(
 6690                        buffer.anchor_before(range_to_move.start)
 6691                            ..buffer.anchor_after(range_to_move.end),
 6692                    ) {
 6693                        let mut start = fold.range.start.to_point(&buffer);
 6694                        let mut end = fold.range.end.to_point(&buffer);
 6695                        start.row -= row_delta;
 6696                        end.row -= row_delta;
 6697                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6698                    }
 6699                }
 6700            }
 6701
 6702            // If we didn't move line(s), preserve the existing selections
 6703            new_selections.append(&mut contiguous_row_selections);
 6704        }
 6705
 6706        self.transact(cx, |this, cx| {
 6707            this.unfold_ranges(unfold_ranges, true, true, cx);
 6708            this.buffer.update(cx, |buffer, cx| {
 6709                for (range, text) in edits {
 6710                    buffer.edit([(range, text)], None, cx);
 6711                }
 6712            });
 6713            this.fold_ranges(refold_ranges, true, cx);
 6714            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6715                s.select(new_selections);
 6716            })
 6717        });
 6718    }
 6719
 6720    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6721        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6722        let buffer = self.buffer.read(cx).snapshot(cx);
 6723
 6724        let mut edits = Vec::new();
 6725        let mut unfold_ranges = Vec::new();
 6726        let mut refold_ranges = Vec::new();
 6727
 6728        let selections = self.selections.all::<Point>(cx);
 6729        let mut selections = selections.iter().peekable();
 6730        let mut contiguous_row_selections = Vec::new();
 6731        let mut new_selections = Vec::new();
 6732
 6733        while let Some(selection) = selections.next() {
 6734            // Find all the selections that span a contiguous row range
 6735            let (start_row, end_row) = consume_contiguous_rows(
 6736                &mut contiguous_row_selections,
 6737                selection,
 6738                &display_map,
 6739                &mut selections,
 6740            );
 6741
 6742            // Move the text spanned by the row range to be after the last line of the row range
 6743            if end_row.0 <= buffer.max_point().row {
 6744                let range_to_move =
 6745                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6746                let insertion_point = display_map
 6747                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6748                    .0;
 6749
 6750                // Don't move lines across excerpt boundaries
 6751                if buffer
 6752                    .excerpt_boundaries_in_range((
 6753                        Bound::Excluded(range_to_move.start),
 6754                        Bound::Included(insertion_point),
 6755                    ))
 6756                    .next()
 6757                    .is_none()
 6758                {
 6759                    let mut text = String::from("\n");
 6760                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6761                    text.pop(); // Drop trailing newline
 6762                    edits.push((
 6763                        buffer.anchor_after(range_to_move.start)
 6764                            ..buffer.anchor_before(range_to_move.end),
 6765                        String::new(),
 6766                    ));
 6767                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6768                    edits.push((insertion_anchor..insertion_anchor, text));
 6769
 6770                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6771
 6772                    // Move selections down
 6773                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6774                        |mut selection| {
 6775                            selection.start.row += row_delta;
 6776                            selection.end.row += row_delta;
 6777                            selection
 6778                        },
 6779                    ));
 6780
 6781                    // Move folds down
 6782                    unfold_ranges.push(range_to_move.clone());
 6783                    for fold in display_map.folds_in_range(
 6784                        buffer.anchor_before(range_to_move.start)
 6785                            ..buffer.anchor_after(range_to_move.end),
 6786                    ) {
 6787                        let mut start = fold.range.start.to_point(&buffer);
 6788                        let mut end = fold.range.end.to_point(&buffer);
 6789                        start.row += row_delta;
 6790                        end.row += row_delta;
 6791                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6792                    }
 6793                }
 6794            }
 6795
 6796            // If we didn't move line(s), preserve the existing selections
 6797            new_selections.append(&mut contiguous_row_selections);
 6798        }
 6799
 6800        self.transact(cx, |this, cx| {
 6801            this.unfold_ranges(unfold_ranges, true, true, cx);
 6802            this.buffer.update(cx, |buffer, cx| {
 6803                for (range, text) in edits {
 6804                    buffer.edit([(range, text)], None, cx);
 6805                }
 6806            });
 6807            this.fold_ranges(refold_ranges, true, cx);
 6808            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6809        });
 6810    }
 6811
 6812    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6813        let text_layout_details = &self.text_layout_details(cx);
 6814        self.transact(cx, |this, cx| {
 6815            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6816                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6817                let line_mode = s.line_mode;
 6818                s.move_with(|display_map, selection| {
 6819                    if !selection.is_empty() || line_mode {
 6820                        return;
 6821                    }
 6822
 6823                    let mut head = selection.head();
 6824                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6825                    if head.column() == display_map.line_len(head.row()) {
 6826                        transpose_offset = display_map
 6827                            .buffer_snapshot
 6828                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6829                    }
 6830
 6831                    if transpose_offset == 0 {
 6832                        return;
 6833                    }
 6834
 6835                    *head.column_mut() += 1;
 6836                    head = display_map.clip_point(head, Bias::Right);
 6837                    let goal = SelectionGoal::HorizontalPosition(
 6838                        display_map
 6839                            .x_for_display_point(head, text_layout_details)
 6840                            .into(),
 6841                    );
 6842                    selection.collapse_to(head, goal);
 6843
 6844                    let transpose_start = display_map
 6845                        .buffer_snapshot
 6846                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6847                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6848                        let transpose_end = display_map
 6849                            .buffer_snapshot
 6850                            .clip_offset(transpose_offset + 1, Bias::Right);
 6851                        if let Some(ch) =
 6852                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6853                        {
 6854                            edits.push((transpose_start..transpose_offset, String::new()));
 6855                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6856                        }
 6857                    }
 6858                });
 6859                edits
 6860            });
 6861            this.buffer
 6862                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6863            let selections = this.selections.all::<usize>(cx);
 6864            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6865                s.select(selections);
 6866            });
 6867        });
 6868    }
 6869
 6870    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6871        self.rewrap_impl(true, cx)
 6872    }
 6873
 6874    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6875        let buffer = self.buffer.read(cx).snapshot(cx);
 6876        let selections = self.selections.all::<Point>(cx);
 6877        let mut selections = selections.iter().peekable();
 6878
 6879        let mut edits = Vec::new();
 6880        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6881
 6882        while let Some(selection) = selections.next() {
 6883            let mut start_row = selection.start.row;
 6884            let mut end_row = selection.end.row;
 6885
 6886            // Skip selections that overlap with a range that has already been rewrapped.
 6887            let selection_range = start_row..end_row;
 6888            if rewrapped_row_ranges
 6889                .iter()
 6890                .any(|range| range.overlaps(&selection_range))
 6891            {
 6892                continue;
 6893            }
 6894
 6895            let mut should_rewrap = !only_text;
 6896
 6897            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6898                match language_scope.language_name().0.as_ref() {
 6899                    "Markdown" | "Plain Text" => {
 6900                        should_rewrap = true;
 6901                    }
 6902                    _ => {}
 6903                }
 6904            }
 6905
 6906            // Since not all lines in the selection may be at the same indent
 6907            // level, choose the indent size that is the most common between all
 6908            // of the lines.
 6909            //
 6910            // If there is a tie, we use the deepest indent.
 6911            let (indent_size, indent_end) = {
 6912                let mut indent_size_occurrences = HashMap::default();
 6913                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6914
 6915                for row in start_row..=end_row {
 6916                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6917                    rows_by_indent_size.entry(indent).or_default().push(row);
 6918                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6919                }
 6920
 6921                let indent_size = indent_size_occurrences
 6922                    .into_iter()
 6923                    .max_by_key(|(indent, count)| (*count, indent.len))
 6924                    .map(|(indent, _)| indent)
 6925                    .unwrap_or_default();
 6926                let row = rows_by_indent_size[&indent_size][0];
 6927                let indent_end = Point::new(row, indent_size.len);
 6928
 6929                (indent_size, indent_end)
 6930            };
 6931
 6932            let mut line_prefix = indent_size.chars().collect::<String>();
 6933
 6934            if let Some(comment_prefix) =
 6935                buffer
 6936                    .language_scope_at(selection.head())
 6937                    .and_then(|language| {
 6938                        language
 6939                            .line_comment_prefixes()
 6940                            .iter()
 6941                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6942                            .cloned()
 6943                    })
 6944            {
 6945                line_prefix.push_str(&comment_prefix);
 6946                should_rewrap = true;
 6947            }
 6948
 6949            if selection.is_empty() {
 6950                'expand_upwards: while start_row > 0 {
 6951                    let prev_row = start_row - 1;
 6952                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6953                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6954                    {
 6955                        start_row = prev_row;
 6956                    } else {
 6957                        break 'expand_upwards;
 6958                    }
 6959                }
 6960
 6961                'expand_downwards: while end_row < buffer.max_point().row {
 6962                    let next_row = end_row + 1;
 6963                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6964                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6965                    {
 6966                        end_row = next_row;
 6967                    } else {
 6968                        break 'expand_downwards;
 6969                    }
 6970                }
 6971            }
 6972
 6973            if !should_rewrap {
 6974                continue;
 6975            }
 6976
 6977            let start = Point::new(start_row, 0);
 6978            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6979            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6980            let Some(lines_without_prefixes) = selection_text
 6981                .lines()
 6982                .map(|line| {
 6983                    line.strip_prefix(&line_prefix)
 6984                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6985                        .ok_or_else(|| {
 6986                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6987                        })
 6988                })
 6989                .collect::<Result<Vec<_>, _>>()
 6990                .log_err()
 6991            else {
 6992                continue;
 6993            };
 6994
 6995            let unwrapped_text = lines_without_prefixes.join(" ");
 6996            let wrap_column = buffer
 6997                .settings_at(Point::new(start_row, 0), cx)
 6998                .preferred_line_length as usize;
 6999            let mut wrapped_text = String::new();
 7000            let mut current_line = line_prefix.clone();
 7001            for word in unwrapped_text.split_whitespace() {
 7002                if current_line.len() + word.len() >= wrap_column {
 7003                    wrapped_text.push_str(&current_line);
 7004                    wrapped_text.push('\n');
 7005                    current_line.truncate(line_prefix.len());
 7006                }
 7007
 7008                if current_line.len() > line_prefix.len() {
 7009                    current_line.push(' ');
 7010                }
 7011
 7012                current_line.push_str(word);
 7013            }
 7014
 7015            if !current_line.is_empty() {
 7016                wrapped_text.push_str(&current_line);
 7017            }
 7018
 7019            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7020            let mut offset = start.to_offset(&buffer);
 7021            let mut moved_since_edit = true;
 7022
 7023            for change in diff.iter_all_changes() {
 7024                let value = change.value();
 7025                match change.tag() {
 7026                    ChangeTag::Equal => {
 7027                        offset += value.len();
 7028                        moved_since_edit = true;
 7029                    }
 7030                    ChangeTag::Delete => {
 7031                        let start = buffer.anchor_after(offset);
 7032                        let end = buffer.anchor_before(offset + value.len());
 7033
 7034                        if moved_since_edit {
 7035                            edits.push((start..end, String::new()));
 7036                        } else {
 7037                            edits.last_mut().unwrap().0.end = end;
 7038                        }
 7039
 7040                        offset += value.len();
 7041                        moved_since_edit = false;
 7042                    }
 7043                    ChangeTag::Insert => {
 7044                        if moved_since_edit {
 7045                            let anchor = buffer.anchor_after(offset);
 7046                            edits.push((anchor..anchor, value.to_string()));
 7047                        } else {
 7048                            edits.last_mut().unwrap().1.push_str(value);
 7049                        }
 7050
 7051                        moved_since_edit = false;
 7052                    }
 7053                }
 7054            }
 7055
 7056            rewrapped_row_ranges.push(start_row..=end_row);
 7057        }
 7058
 7059        self.buffer
 7060            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7061    }
 7062
 7063    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7064        let mut text = String::new();
 7065        let buffer = self.buffer.read(cx).snapshot(cx);
 7066        let mut selections = self.selections.all::<Point>(cx);
 7067        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7068        {
 7069            let max_point = buffer.max_point();
 7070            let mut is_first = true;
 7071            for selection in &mut selections {
 7072                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7073                if is_entire_line {
 7074                    selection.start = Point::new(selection.start.row, 0);
 7075                    if !selection.is_empty() && selection.end.column == 0 {
 7076                        selection.end = cmp::min(max_point, selection.end);
 7077                    } else {
 7078                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7079                    }
 7080                    selection.goal = SelectionGoal::None;
 7081                }
 7082                if is_first {
 7083                    is_first = false;
 7084                } else {
 7085                    text += "\n";
 7086                }
 7087                let mut len = 0;
 7088                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7089                    text.push_str(chunk);
 7090                    len += chunk.len();
 7091                }
 7092                clipboard_selections.push(ClipboardSelection {
 7093                    len,
 7094                    is_entire_line,
 7095                    first_line_indent: buffer
 7096                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7097                        .len,
 7098                });
 7099            }
 7100        }
 7101
 7102        self.transact(cx, |this, cx| {
 7103            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7104                s.select(selections);
 7105            });
 7106            this.insert("", cx);
 7107            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7108                text,
 7109                clipboard_selections,
 7110            ));
 7111        });
 7112    }
 7113
 7114    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7115        let selections = self.selections.all::<Point>(cx);
 7116        let buffer = self.buffer.read(cx).read(cx);
 7117        let mut text = String::new();
 7118
 7119        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7120        {
 7121            let max_point = buffer.max_point();
 7122            let mut is_first = true;
 7123            for selection in selections.iter() {
 7124                let mut start = selection.start;
 7125                let mut end = selection.end;
 7126                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7127                if is_entire_line {
 7128                    start = Point::new(start.row, 0);
 7129                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7130                }
 7131                if is_first {
 7132                    is_first = false;
 7133                } else {
 7134                    text += "\n";
 7135                }
 7136                let mut len = 0;
 7137                for chunk in buffer.text_for_range(start..end) {
 7138                    text.push_str(chunk);
 7139                    len += chunk.len();
 7140                }
 7141                clipboard_selections.push(ClipboardSelection {
 7142                    len,
 7143                    is_entire_line,
 7144                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7145                });
 7146            }
 7147        }
 7148
 7149        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7150            text,
 7151            clipboard_selections,
 7152        ));
 7153    }
 7154
 7155    pub fn do_paste(
 7156        &mut self,
 7157        text: &String,
 7158        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7159        handle_entire_lines: bool,
 7160        cx: &mut ViewContext<Self>,
 7161    ) {
 7162        if self.read_only(cx) {
 7163            return;
 7164        }
 7165
 7166        let clipboard_text = Cow::Borrowed(text);
 7167
 7168        self.transact(cx, |this, cx| {
 7169            if let Some(mut clipboard_selections) = clipboard_selections {
 7170                let old_selections = this.selections.all::<usize>(cx);
 7171                let all_selections_were_entire_line =
 7172                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7173                let first_selection_indent_column =
 7174                    clipboard_selections.first().map(|s| s.first_line_indent);
 7175                if clipboard_selections.len() != old_selections.len() {
 7176                    clipboard_selections.drain(..);
 7177                }
 7178
 7179                this.buffer.update(cx, |buffer, cx| {
 7180                    let snapshot = buffer.read(cx);
 7181                    let mut start_offset = 0;
 7182                    let mut edits = Vec::new();
 7183                    let mut original_indent_columns = Vec::new();
 7184                    for (ix, selection) in old_selections.iter().enumerate() {
 7185                        let to_insert;
 7186                        let entire_line;
 7187                        let original_indent_column;
 7188                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7189                            let end_offset = start_offset + clipboard_selection.len;
 7190                            to_insert = &clipboard_text[start_offset..end_offset];
 7191                            entire_line = clipboard_selection.is_entire_line;
 7192                            start_offset = end_offset + 1;
 7193                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7194                        } else {
 7195                            to_insert = clipboard_text.as_str();
 7196                            entire_line = all_selections_were_entire_line;
 7197                            original_indent_column = first_selection_indent_column
 7198                        }
 7199
 7200                        // If the corresponding selection was empty when this slice of the
 7201                        // clipboard text was written, then the entire line containing the
 7202                        // selection was copied. If this selection is also currently empty,
 7203                        // then paste the line before the current line of the buffer.
 7204                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7205                            let column = selection.start.to_point(&snapshot).column as usize;
 7206                            let line_start = selection.start - column;
 7207                            line_start..line_start
 7208                        } else {
 7209                            selection.range()
 7210                        };
 7211
 7212                        edits.push((range, to_insert));
 7213                        original_indent_columns.extend(original_indent_column);
 7214                    }
 7215                    drop(snapshot);
 7216
 7217                    buffer.edit(
 7218                        edits,
 7219                        Some(AutoindentMode::Block {
 7220                            original_indent_columns,
 7221                        }),
 7222                        cx,
 7223                    );
 7224                });
 7225
 7226                let selections = this.selections.all::<usize>(cx);
 7227                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7228            } else {
 7229                this.insert(&clipboard_text, cx);
 7230            }
 7231        });
 7232    }
 7233
 7234    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7235        if let Some(item) = cx.read_from_clipboard() {
 7236            let entries = item.entries();
 7237
 7238            match entries.first() {
 7239                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7240                // of all the pasted entries.
 7241                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7242                    .do_paste(
 7243                        clipboard_string.text(),
 7244                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7245                        true,
 7246                        cx,
 7247                    ),
 7248                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7249            }
 7250        }
 7251    }
 7252
 7253    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7254        if self.read_only(cx) {
 7255            return;
 7256        }
 7257
 7258        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7259            if let Some((selections, _)) =
 7260                self.selection_history.transaction(transaction_id).cloned()
 7261            {
 7262                self.change_selections(None, cx, |s| {
 7263                    s.select_anchors(selections.to_vec());
 7264                });
 7265            }
 7266            self.request_autoscroll(Autoscroll::fit(), cx);
 7267            self.unmark_text(cx);
 7268            self.refresh_inline_completion(true, false, cx);
 7269            cx.emit(EditorEvent::Edited { transaction_id });
 7270            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7271        }
 7272    }
 7273
 7274    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7275        if self.read_only(cx) {
 7276            return;
 7277        }
 7278
 7279        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7280            if let Some((_, Some(selections))) =
 7281                self.selection_history.transaction(transaction_id).cloned()
 7282            {
 7283                self.change_selections(None, cx, |s| {
 7284                    s.select_anchors(selections.to_vec());
 7285                });
 7286            }
 7287            self.request_autoscroll(Autoscroll::fit(), cx);
 7288            self.unmark_text(cx);
 7289            self.refresh_inline_completion(true, false, cx);
 7290            cx.emit(EditorEvent::Edited { transaction_id });
 7291        }
 7292    }
 7293
 7294    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7295        self.buffer
 7296            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7297    }
 7298
 7299    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7300        self.buffer
 7301            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7302    }
 7303
 7304    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7305        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7306            let line_mode = s.line_mode;
 7307            s.move_with(|map, selection| {
 7308                let cursor = if selection.is_empty() && !line_mode {
 7309                    movement::left(map, selection.start)
 7310                } else {
 7311                    selection.start
 7312                };
 7313                selection.collapse_to(cursor, SelectionGoal::None);
 7314            });
 7315        })
 7316    }
 7317
 7318    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7319        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7320            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7321        })
 7322    }
 7323
 7324    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7325        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7326            let line_mode = s.line_mode;
 7327            s.move_with(|map, selection| {
 7328                let cursor = if selection.is_empty() && !line_mode {
 7329                    movement::right(map, selection.end)
 7330                } else {
 7331                    selection.end
 7332                };
 7333                selection.collapse_to(cursor, SelectionGoal::None)
 7334            });
 7335        })
 7336    }
 7337
 7338    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7339        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7340            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7341        })
 7342    }
 7343
 7344    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7345        if self.take_rename(true, cx).is_some() {
 7346            return;
 7347        }
 7348
 7349        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7350            cx.propagate();
 7351            return;
 7352        }
 7353
 7354        let text_layout_details = &self.text_layout_details(cx);
 7355        let selection_count = self.selections.count();
 7356        let first_selection = self.selections.first_anchor();
 7357
 7358        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7359            let line_mode = s.line_mode;
 7360            s.move_with(|map, selection| {
 7361                if !selection.is_empty() && !line_mode {
 7362                    selection.goal = SelectionGoal::None;
 7363                }
 7364                let (cursor, goal) = movement::up(
 7365                    map,
 7366                    selection.start,
 7367                    selection.goal,
 7368                    false,
 7369                    text_layout_details,
 7370                );
 7371                selection.collapse_to(cursor, goal);
 7372            });
 7373        });
 7374
 7375        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7376        {
 7377            cx.propagate();
 7378        }
 7379    }
 7380
 7381    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7382        if self.take_rename(true, cx).is_some() {
 7383            return;
 7384        }
 7385
 7386        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7387            cx.propagate();
 7388            return;
 7389        }
 7390
 7391        let text_layout_details = &self.text_layout_details(cx);
 7392
 7393        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7394            let line_mode = s.line_mode;
 7395            s.move_with(|map, selection| {
 7396                if !selection.is_empty() && !line_mode {
 7397                    selection.goal = SelectionGoal::None;
 7398                }
 7399                let (cursor, goal) = movement::up_by_rows(
 7400                    map,
 7401                    selection.start,
 7402                    action.lines,
 7403                    selection.goal,
 7404                    false,
 7405                    text_layout_details,
 7406                );
 7407                selection.collapse_to(cursor, goal);
 7408            });
 7409        })
 7410    }
 7411
 7412    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7413        if self.take_rename(true, cx).is_some() {
 7414            return;
 7415        }
 7416
 7417        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7418            cx.propagate();
 7419            return;
 7420        }
 7421
 7422        let text_layout_details = &self.text_layout_details(cx);
 7423
 7424        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7425            let line_mode = s.line_mode;
 7426            s.move_with(|map, selection| {
 7427                if !selection.is_empty() && !line_mode {
 7428                    selection.goal = SelectionGoal::None;
 7429                }
 7430                let (cursor, goal) = movement::down_by_rows(
 7431                    map,
 7432                    selection.start,
 7433                    action.lines,
 7434                    selection.goal,
 7435                    false,
 7436                    text_layout_details,
 7437                );
 7438                selection.collapse_to(cursor, goal);
 7439            });
 7440        })
 7441    }
 7442
 7443    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7444        let text_layout_details = &self.text_layout_details(cx);
 7445        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7446            s.move_heads_with(|map, head, goal| {
 7447                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7448            })
 7449        })
 7450    }
 7451
 7452    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7453        let text_layout_details = &self.text_layout_details(cx);
 7454        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7455            s.move_heads_with(|map, head, goal| {
 7456                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7457            })
 7458        })
 7459    }
 7460
 7461    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7462        let Some(row_count) = self.visible_row_count() else {
 7463            return;
 7464        };
 7465
 7466        let text_layout_details = &self.text_layout_details(cx);
 7467
 7468        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7469            s.move_heads_with(|map, head, goal| {
 7470                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7471            })
 7472        })
 7473    }
 7474
 7475    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7476        if self.take_rename(true, cx).is_some() {
 7477            return;
 7478        }
 7479
 7480        if self
 7481            .context_menu
 7482            .write()
 7483            .as_mut()
 7484            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7485            .unwrap_or(false)
 7486        {
 7487            return;
 7488        }
 7489
 7490        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7491            cx.propagate();
 7492            return;
 7493        }
 7494
 7495        let Some(row_count) = self.visible_row_count() else {
 7496            return;
 7497        };
 7498
 7499        let autoscroll = if action.center_cursor {
 7500            Autoscroll::center()
 7501        } else {
 7502            Autoscroll::fit()
 7503        };
 7504
 7505        let text_layout_details = &self.text_layout_details(cx);
 7506
 7507        self.change_selections(Some(autoscroll), cx, |s| {
 7508            let line_mode = s.line_mode;
 7509            s.move_with(|map, selection| {
 7510                if !selection.is_empty() && !line_mode {
 7511                    selection.goal = SelectionGoal::None;
 7512                }
 7513                let (cursor, goal) = movement::up_by_rows(
 7514                    map,
 7515                    selection.end,
 7516                    row_count,
 7517                    selection.goal,
 7518                    false,
 7519                    text_layout_details,
 7520                );
 7521                selection.collapse_to(cursor, goal);
 7522            });
 7523        });
 7524    }
 7525
 7526    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7527        let text_layout_details = &self.text_layout_details(cx);
 7528        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7529            s.move_heads_with(|map, head, goal| {
 7530                movement::up(map, head, goal, false, text_layout_details)
 7531            })
 7532        })
 7533    }
 7534
 7535    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7536        self.take_rename(true, cx);
 7537
 7538        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7539            cx.propagate();
 7540            return;
 7541        }
 7542
 7543        let text_layout_details = &self.text_layout_details(cx);
 7544        let selection_count = self.selections.count();
 7545        let first_selection = self.selections.first_anchor();
 7546
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            let line_mode = s.line_mode;
 7549            s.move_with(|map, selection| {
 7550                if !selection.is_empty() && !line_mode {
 7551                    selection.goal = SelectionGoal::None;
 7552                }
 7553                let (cursor, goal) = movement::down(
 7554                    map,
 7555                    selection.end,
 7556                    selection.goal,
 7557                    false,
 7558                    text_layout_details,
 7559                );
 7560                selection.collapse_to(cursor, goal);
 7561            });
 7562        });
 7563
 7564        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7565        {
 7566            cx.propagate();
 7567        }
 7568    }
 7569
 7570    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7571        let Some(row_count) = self.visible_row_count() else {
 7572            return;
 7573        };
 7574
 7575        let text_layout_details = &self.text_layout_details(cx);
 7576
 7577        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7578            s.move_heads_with(|map, head, goal| {
 7579                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7580            })
 7581        })
 7582    }
 7583
 7584    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7585        if self.take_rename(true, cx).is_some() {
 7586            return;
 7587        }
 7588
 7589        if self
 7590            .context_menu
 7591            .write()
 7592            .as_mut()
 7593            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7594            .unwrap_or(false)
 7595        {
 7596            return;
 7597        }
 7598
 7599        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7600            cx.propagate();
 7601            return;
 7602        }
 7603
 7604        let Some(row_count) = self.visible_row_count() else {
 7605            return;
 7606        };
 7607
 7608        let autoscroll = if action.center_cursor {
 7609            Autoscroll::center()
 7610        } else {
 7611            Autoscroll::fit()
 7612        };
 7613
 7614        let text_layout_details = &self.text_layout_details(cx);
 7615        self.change_selections(Some(autoscroll), cx, |s| {
 7616            let line_mode = s.line_mode;
 7617            s.move_with(|map, selection| {
 7618                if !selection.is_empty() && !line_mode {
 7619                    selection.goal = SelectionGoal::None;
 7620                }
 7621                let (cursor, goal) = movement::down_by_rows(
 7622                    map,
 7623                    selection.end,
 7624                    row_count,
 7625                    selection.goal,
 7626                    false,
 7627                    text_layout_details,
 7628                );
 7629                selection.collapse_to(cursor, goal);
 7630            });
 7631        });
 7632    }
 7633
 7634    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7635        let text_layout_details = &self.text_layout_details(cx);
 7636        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7637            s.move_heads_with(|map, head, goal| {
 7638                movement::down(map, head, goal, false, text_layout_details)
 7639            })
 7640        });
 7641    }
 7642
 7643    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7644        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7645            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7646        }
 7647    }
 7648
 7649    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7650        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7651            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7652        }
 7653    }
 7654
 7655    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7656        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7657            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7658        }
 7659    }
 7660
 7661    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7662        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7663            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7664        }
 7665    }
 7666
 7667    pub fn move_to_previous_word_start(
 7668        &mut self,
 7669        _: &MoveToPreviousWordStart,
 7670        cx: &mut ViewContext<Self>,
 7671    ) {
 7672        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7673            s.move_cursors_with(|map, head, _| {
 7674                (
 7675                    movement::previous_word_start(map, head),
 7676                    SelectionGoal::None,
 7677                )
 7678            });
 7679        })
 7680    }
 7681
 7682    pub fn move_to_previous_subword_start(
 7683        &mut self,
 7684        _: &MoveToPreviousSubwordStart,
 7685        cx: &mut ViewContext<Self>,
 7686    ) {
 7687        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7688            s.move_cursors_with(|map, head, _| {
 7689                (
 7690                    movement::previous_subword_start(map, head),
 7691                    SelectionGoal::None,
 7692                )
 7693            });
 7694        })
 7695    }
 7696
 7697    pub fn select_to_previous_word_start(
 7698        &mut self,
 7699        _: &SelectToPreviousWordStart,
 7700        cx: &mut ViewContext<Self>,
 7701    ) {
 7702        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7703            s.move_heads_with(|map, head, _| {
 7704                (
 7705                    movement::previous_word_start(map, head),
 7706                    SelectionGoal::None,
 7707                )
 7708            });
 7709        })
 7710    }
 7711
 7712    pub fn select_to_previous_subword_start(
 7713        &mut self,
 7714        _: &SelectToPreviousSubwordStart,
 7715        cx: &mut ViewContext<Self>,
 7716    ) {
 7717        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7718            s.move_heads_with(|map, head, _| {
 7719                (
 7720                    movement::previous_subword_start(map, head),
 7721                    SelectionGoal::None,
 7722                )
 7723            });
 7724        })
 7725    }
 7726
 7727    pub fn delete_to_previous_word_start(
 7728        &mut self,
 7729        action: &DeleteToPreviousWordStart,
 7730        cx: &mut ViewContext<Self>,
 7731    ) {
 7732        self.transact(cx, |this, cx| {
 7733            this.select_autoclose_pair(cx);
 7734            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7735                let line_mode = s.line_mode;
 7736                s.move_with(|map, selection| {
 7737                    if selection.is_empty() && !line_mode {
 7738                        let cursor = if action.ignore_newlines {
 7739                            movement::previous_word_start(map, selection.head())
 7740                        } else {
 7741                            movement::previous_word_start_or_newline(map, selection.head())
 7742                        };
 7743                        selection.set_head(cursor, SelectionGoal::None);
 7744                    }
 7745                });
 7746            });
 7747            this.insert("", cx);
 7748        });
 7749    }
 7750
 7751    pub fn delete_to_previous_subword_start(
 7752        &mut self,
 7753        _: &DeleteToPreviousSubwordStart,
 7754        cx: &mut ViewContext<Self>,
 7755    ) {
 7756        self.transact(cx, |this, cx| {
 7757            this.select_autoclose_pair(cx);
 7758            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7759                let line_mode = s.line_mode;
 7760                s.move_with(|map, selection| {
 7761                    if selection.is_empty() && !line_mode {
 7762                        let cursor = movement::previous_subword_start(map, selection.head());
 7763                        selection.set_head(cursor, SelectionGoal::None);
 7764                    }
 7765                });
 7766            });
 7767            this.insert("", cx);
 7768        });
 7769    }
 7770
 7771    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7772        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7773            s.move_cursors_with(|map, head, _| {
 7774                (movement::next_word_end(map, head), SelectionGoal::None)
 7775            });
 7776        })
 7777    }
 7778
 7779    pub fn move_to_next_subword_end(
 7780        &mut self,
 7781        _: &MoveToNextSubwordEnd,
 7782        cx: &mut ViewContext<Self>,
 7783    ) {
 7784        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7785            s.move_cursors_with(|map, head, _| {
 7786                (movement::next_subword_end(map, head), SelectionGoal::None)
 7787            });
 7788        })
 7789    }
 7790
 7791    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7792        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7793            s.move_heads_with(|map, head, _| {
 7794                (movement::next_word_end(map, head), SelectionGoal::None)
 7795            });
 7796        })
 7797    }
 7798
 7799    pub fn select_to_next_subword_end(
 7800        &mut self,
 7801        _: &SelectToNextSubwordEnd,
 7802        cx: &mut ViewContext<Self>,
 7803    ) {
 7804        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7805            s.move_heads_with(|map, head, _| {
 7806                (movement::next_subword_end(map, head), SelectionGoal::None)
 7807            });
 7808        })
 7809    }
 7810
 7811    pub fn delete_to_next_word_end(
 7812        &mut self,
 7813        action: &DeleteToNextWordEnd,
 7814        cx: &mut ViewContext<Self>,
 7815    ) {
 7816        self.transact(cx, |this, cx| {
 7817            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7818                let line_mode = s.line_mode;
 7819                s.move_with(|map, selection| {
 7820                    if selection.is_empty() && !line_mode {
 7821                        let cursor = if action.ignore_newlines {
 7822                            movement::next_word_end(map, selection.head())
 7823                        } else {
 7824                            movement::next_word_end_or_newline(map, selection.head())
 7825                        };
 7826                        selection.set_head(cursor, SelectionGoal::None);
 7827                    }
 7828                });
 7829            });
 7830            this.insert("", cx);
 7831        });
 7832    }
 7833
 7834    pub fn delete_to_next_subword_end(
 7835        &mut self,
 7836        _: &DeleteToNextSubwordEnd,
 7837        cx: &mut ViewContext<Self>,
 7838    ) {
 7839        self.transact(cx, |this, cx| {
 7840            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7841                s.move_with(|map, selection| {
 7842                    if selection.is_empty() {
 7843                        let cursor = movement::next_subword_end(map, selection.head());
 7844                        selection.set_head(cursor, SelectionGoal::None);
 7845                    }
 7846                });
 7847            });
 7848            this.insert("", cx);
 7849        });
 7850    }
 7851
 7852    pub fn move_to_beginning_of_line(
 7853        &mut self,
 7854        action: &MoveToBeginningOfLine,
 7855        cx: &mut ViewContext<Self>,
 7856    ) {
 7857        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7858            s.move_cursors_with(|map, head, _| {
 7859                (
 7860                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7861                    SelectionGoal::None,
 7862                )
 7863            });
 7864        })
 7865    }
 7866
 7867    pub fn select_to_beginning_of_line(
 7868        &mut self,
 7869        action: &SelectToBeginningOfLine,
 7870        cx: &mut ViewContext<Self>,
 7871    ) {
 7872        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7873            s.move_heads_with(|map, head, _| {
 7874                (
 7875                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7876                    SelectionGoal::None,
 7877                )
 7878            });
 7879        });
 7880    }
 7881
 7882    pub fn delete_to_beginning_of_line(
 7883        &mut self,
 7884        _: &DeleteToBeginningOfLine,
 7885        cx: &mut ViewContext<Self>,
 7886    ) {
 7887        self.transact(cx, |this, cx| {
 7888            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7889                s.move_with(|_, selection| {
 7890                    selection.reversed = true;
 7891                });
 7892            });
 7893
 7894            this.select_to_beginning_of_line(
 7895                &SelectToBeginningOfLine {
 7896                    stop_at_soft_wraps: false,
 7897                },
 7898                cx,
 7899            );
 7900            this.backspace(&Backspace, cx);
 7901        });
 7902    }
 7903
 7904    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7905        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7906            s.move_cursors_with(|map, head, _| {
 7907                (
 7908                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7909                    SelectionGoal::None,
 7910                )
 7911            });
 7912        })
 7913    }
 7914
 7915    pub fn select_to_end_of_line(
 7916        &mut self,
 7917        action: &SelectToEndOfLine,
 7918        cx: &mut ViewContext<Self>,
 7919    ) {
 7920        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7921            s.move_heads_with(|map, head, _| {
 7922                (
 7923                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7924                    SelectionGoal::None,
 7925                )
 7926            });
 7927        })
 7928    }
 7929
 7930    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7931        self.transact(cx, |this, cx| {
 7932            this.select_to_end_of_line(
 7933                &SelectToEndOfLine {
 7934                    stop_at_soft_wraps: false,
 7935                },
 7936                cx,
 7937            );
 7938            this.delete(&Delete, cx);
 7939        });
 7940    }
 7941
 7942    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7943        self.transact(cx, |this, cx| {
 7944            this.select_to_end_of_line(
 7945                &SelectToEndOfLine {
 7946                    stop_at_soft_wraps: false,
 7947                },
 7948                cx,
 7949            );
 7950            this.cut(&Cut, cx);
 7951        });
 7952    }
 7953
 7954    pub fn move_to_start_of_paragraph(
 7955        &mut self,
 7956        _: &MoveToStartOfParagraph,
 7957        cx: &mut ViewContext<Self>,
 7958    ) {
 7959        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7960            cx.propagate();
 7961            return;
 7962        }
 7963
 7964        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7965            s.move_with(|map, selection| {
 7966                selection.collapse_to(
 7967                    movement::start_of_paragraph(map, selection.head(), 1),
 7968                    SelectionGoal::None,
 7969                )
 7970            });
 7971        })
 7972    }
 7973
 7974    pub fn move_to_end_of_paragraph(
 7975        &mut self,
 7976        _: &MoveToEndOfParagraph,
 7977        cx: &mut ViewContext<Self>,
 7978    ) {
 7979        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7980            cx.propagate();
 7981            return;
 7982        }
 7983
 7984        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7985            s.move_with(|map, selection| {
 7986                selection.collapse_to(
 7987                    movement::end_of_paragraph(map, selection.head(), 1),
 7988                    SelectionGoal::None,
 7989                )
 7990            });
 7991        })
 7992    }
 7993
 7994    pub fn select_to_start_of_paragraph(
 7995        &mut self,
 7996        _: &SelectToStartOfParagraph,
 7997        cx: &mut ViewContext<Self>,
 7998    ) {
 7999        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8000            cx.propagate();
 8001            return;
 8002        }
 8003
 8004        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8005            s.move_heads_with(|map, head, _| {
 8006                (
 8007                    movement::start_of_paragraph(map, head, 1),
 8008                    SelectionGoal::None,
 8009                )
 8010            });
 8011        })
 8012    }
 8013
 8014    pub fn select_to_end_of_paragraph(
 8015        &mut self,
 8016        _: &SelectToEndOfParagraph,
 8017        cx: &mut ViewContext<Self>,
 8018    ) {
 8019        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8020            cx.propagate();
 8021            return;
 8022        }
 8023
 8024        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8025            s.move_heads_with(|map, head, _| {
 8026                (
 8027                    movement::end_of_paragraph(map, head, 1),
 8028                    SelectionGoal::None,
 8029                )
 8030            });
 8031        })
 8032    }
 8033
 8034    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8035        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8036            cx.propagate();
 8037            return;
 8038        }
 8039
 8040        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8041            s.select_ranges(vec![0..0]);
 8042        });
 8043    }
 8044
 8045    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8046        let mut selection = self.selections.last::<Point>(cx);
 8047        selection.set_head(Point::zero(), SelectionGoal::None);
 8048
 8049        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8050            s.select(vec![selection]);
 8051        });
 8052    }
 8053
 8054    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8055        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8056            cx.propagate();
 8057            return;
 8058        }
 8059
 8060        let cursor = self.buffer.read(cx).read(cx).len();
 8061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8062            s.select_ranges(vec![cursor..cursor])
 8063        });
 8064    }
 8065
 8066    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8067        self.nav_history = nav_history;
 8068    }
 8069
 8070    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8071        self.nav_history.as_ref()
 8072    }
 8073
 8074    fn push_to_nav_history(
 8075        &mut self,
 8076        cursor_anchor: Anchor,
 8077        new_position: Option<Point>,
 8078        cx: &mut ViewContext<Self>,
 8079    ) {
 8080        if let Some(nav_history) = self.nav_history.as_mut() {
 8081            let buffer = self.buffer.read(cx).read(cx);
 8082            let cursor_position = cursor_anchor.to_point(&buffer);
 8083            let scroll_state = self.scroll_manager.anchor();
 8084            let scroll_top_row = scroll_state.top_row(&buffer);
 8085            drop(buffer);
 8086
 8087            if let Some(new_position) = new_position {
 8088                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8089                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8090                    return;
 8091                }
 8092            }
 8093
 8094            nav_history.push(
 8095                Some(NavigationData {
 8096                    cursor_anchor,
 8097                    cursor_position,
 8098                    scroll_anchor: scroll_state,
 8099                    scroll_top_row,
 8100                }),
 8101                cx,
 8102            );
 8103        }
 8104    }
 8105
 8106    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8107        let buffer = self.buffer.read(cx).snapshot(cx);
 8108        let mut selection = self.selections.first::<usize>(cx);
 8109        selection.set_head(buffer.len(), SelectionGoal::None);
 8110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8111            s.select(vec![selection]);
 8112        });
 8113    }
 8114
 8115    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8116        let end = self.buffer.read(cx).read(cx).len();
 8117        self.change_selections(None, cx, |s| {
 8118            s.select_ranges(vec![0..end]);
 8119        });
 8120    }
 8121
 8122    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8124        let mut selections = self.selections.all::<Point>(cx);
 8125        let max_point = display_map.buffer_snapshot.max_point();
 8126        for selection in &mut selections {
 8127            let rows = selection.spanned_rows(true, &display_map);
 8128            selection.start = Point::new(rows.start.0, 0);
 8129            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8130            selection.reversed = false;
 8131        }
 8132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8133            s.select(selections);
 8134        });
 8135    }
 8136
 8137    pub fn split_selection_into_lines(
 8138        &mut self,
 8139        _: &SplitSelectionIntoLines,
 8140        cx: &mut ViewContext<Self>,
 8141    ) {
 8142        let mut to_unfold = Vec::new();
 8143        let mut new_selection_ranges = Vec::new();
 8144        {
 8145            let selections = self.selections.all::<Point>(cx);
 8146            let buffer = self.buffer.read(cx).read(cx);
 8147            for selection in selections {
 8148                for row in selection.start.row..selection.end.row {
 8149                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8150                    new_selection_ranges.push(cursor..cursor);
 8151                }
 8152                new_selection_ranges.push(selection.end..selection.end);
 8153                to_unfold.push(selection.start..selection.end);
 8154            }
 8155        }
 8156        self.unfold_ranges(to_unfold, true, true, cx);
 8157        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8158            s.select_ranges(new_selection_ranges);
 8159        });
 8160    }
 8161
 8162    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8163        self.add_selection(true, cx);
 8164    }
 8165
 8166    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8167        self.add_selection(false, cx);
 8168    }
 8169
 8170    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8171        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8172        let mut selections = self.selections.all::<Point>(cx);
 8173        let text_layout_details = self.text_layout_details(cx);
 8174        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8175            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8176            let range = oldest_selection.display_range(&display_map).sorted();
 8177
 8178            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8179            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8180            let positions = start_x.min(end_x)..start_x.max(end_x);
 8181
 8182            selections.clear();
 8183            let mut stack = Vec::new();
 8184            for row in range.start.row().0..=range.end.row().0 {
 8185                if let Some(selection) = self.selections.build_columnar_selection(
 8186                    &display_map,
 8187                    DisplayRow(row),
 8188                    &positions,
 8189                    oldest_selection.reversed,
 8190                    &text_layout_details,
 8191                ) {
 8192                    stack.push(selection.id);
 8193                    selections.push(selection);
 8194                }
 8195            }
 8196
 8197            if above {
 8198                stack.reverse();
 8199            }
 8200
 8201            AddSelectionsState { above, stack }
 8202        });
 8203
 8204        let last_added_selection = *state.stack.last().unwrap();
 8205        let mut new_selections = Vec::new();
 8206        if above == state.above {
 8207            let end_row = if above {
 8208                DisplayRow(0)
 8209            } else {
 8210                display_map.max_point().row()
 8211            };
 8212
 8213            'outer: for selection in selections {
 8214                if selection.id == last_added_selection {
 8215                    let range = selection.display_range(&display_map).sorted();
 8216                    debug_assert_eq!(range.start.row(), range.end.row());
 8217                    let mut row = range.start.row();
 8218                    let positions =
 8219                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8220                            px(start)..px(end)
 8221                        } else {
 8222                            let start_x =
 8223                                display_map.x_for_display_point(range.start, &text_layout_details);
 8224                            let end_x =
 8225                                display_map.x_for_display_point(range.end, &text_layout_details);
 8226                            start_x.min(end_x)..start_x.max(end_x)
 8227                        };
 8228
 8229                    while row != end_row {
 8230                        if above {
 8231                            row.0 -= 1;
 8232                        } else {
 8233                            row.0 += 1;
 8234                        }
 8235
 8236                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8237                            &display_map,
 8238                            row,
 8239                            &positions,
 8240                            selection.reversed,
 8241                            &text_layout_details,
 8242                        ) {
 8243                            state.stack.push(new_selection.id);
 8244                            if above {
 8245                                new_selections.push(new_selection);
 8246                                new_selections.push(selection);
 8247                            } else {
 8248                                new_selections.push(selection);
 8249                                new_selections.push(new_selection);
 8250                            }
 8251
 8252                            continue 'outer;
 8253                        }
 8254                    }
 8255                }
 8256
 8257                new_selections.push(selection);
 8258            }
 8259        } else {
 8260            new_selections = selections;
 8261            new_selections.retain(|s| s.id != last_added_selection);
 8262            state.stack.pop();
 8263        }
 8264
 8265        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8266            s.select(new_selections);
 8267        });
 8268        if state.stack.len() > 1 {
 8269            self.add_selections_state = Some(state);
 8270        }
 8271    }
 8272
 8273    pub fn select_next_match_internal(
 8274        &mut self,
 8275        display_map: &DisplaySnapshot,
 8276        replace_newest: bool,
 8277        autoscroll: Option<Autoscroll>,
 8278        cx: &mut ViewContext<Self>,
 8279    ) -> Result<()> {
 8280        fn select_next_match_ranges(
 8281            this: &mut Editor,
 8282            range: Range<usize>,
 8283            replace_newest: bool,
 8284            auto_scroll: Option<Autoscroll>,
 8285            cx: &mut ViewContext<Editor>,
 8286        ) {
 8287            this.unfold_ranges([range.clone()], false, true, cx);
 8288            this.change_selections(auto_scroll, cx, |s| {
 8289                if replace_newest {
 8290                    s.delete(s.newest_anchor().id);
 8291                }
 8292                s.insert_range(range.clone());
 8293            });
 8294        }
 8295
 8296        let buffer = &display_map.buffer_snapshot;
 8297        let mut selections = self.selections.all::<usize>(cx);
 8298        if let Some(mut select_next_state) = self.select_next_state.take() {
 8299            let query = &select_next_state.query;
 8300            if !select_next_state.done {
 8301                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8302                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8303                let mut next_selected_range = None;
 8304
 8305                let bytes_after_last_selection =
 8306                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8307                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8308                let query_matches = query
 8309                    .stream_find_iter(bytes_after_last_selection)
 8310                    .map(|result| (last_selection.end, result))
 8311                    .chain(
 8312                        query
 8313                            .stream_find_iter(bytes_before_first_selection)
 8314                            .map(|result| (0, result)),
 8315                    );
 8316
 8317                for (start_offset, query_match) in query_matches {
 8318                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8319                    let offset_range =
 8320                        start_offset + query_match.start()..start_offset + query_match.end();
 8321                    let display_range = offset_range.start.to_display_point(display_map)
 8322                        ..offset_range.end.to_display_point(display_map);
 8323
 8324                    if !select_next_state.wordwise
 8325                        || (!movement::is_inside_word(display_map, display_range.start)
 8326                            && !movement::is_inside_word(display_map, display_range.end))
 8327                    {
 8328                        // TODO: This is n^2, because we might check all the selections
 8329                        if !selections
 8330                            .iter()
 8331                            .any(|selection| selection.range().overlaps(&offset_range))
 8332                        {
 8333                            next_selected_range = Some(offset_range);
 8334                            break;
 8335                        }
 8336                    }
 8337                }
 8338
 8339                if let Some(next_selected_range) = next_selected_range {
 8340                    select_next_match_ranges(
 8341                        self,
 8342                        next_selected_range,
 8343                        replace_newest,
 8344                        autoscroll,
 8345                        cx,
 8346                    );
 8347                } else {
 8348                    select_next_state.done = true;
 8349                }
 8350            }
 8351
 8352            self.select_next_state = Some(select_next_state);
 8353        } else {
 8354            let mut only_carets = true;
 8355            let mut same_text_selected = true;
 8356            let mut selected_text = None;
 8357
 8358            let mut selections_iter = selections.iter().peekable();
 8359            while let Some(selection) = selections_iter.next() {
 8360                if selection.start != selection.end {
 8361                    only_carets = false;
 8362                }
 8363
 8364                if same_text_selected {
 8365                    if selected_text.is_none() {
 8366                        selected_text =
 8367                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8368                    }
 8369
 8370                    if let Some(next_selection) = selections_iter.peek() {
 8371                        if next_selection.range().len() == selection.range().len() {
 8372                            let next_selected_text = buffer
 8373                                .text_for_range(next_selection.range())
 8374                                .collect::<String>();
 8375                            if Some(next_selected_text) != selected_text {
 8376                                same_text_selected = false;
 8377                                selected_text = None;
 8378                            }
 8379                        } else {
 8380                            same_text_selected = false;
 8381                            selected_text = None;
 8382                        }
 8383                    }
 8384                }
 8385            }
 8386
 8387            if only_carets {
 8388                for selection in &mut selections {
 8389                    let word_range = movement::surrounding_word(
 8390                        display_map,
 8391                        selection.start.to_display_point(display_map),
 8392                    );
 8393                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8394                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8395                    selection.goal = SelectionGoal::None;
 8396                    selection.reversed = false;
 8397                    select_next_match_ranges(
 8398                        self,
 8399                        selection.start..selection.end,
 8400                        replace_newest,
 8401                        autoscroll,
 8402                        cx,
 8403                    );
 8404                }
 8405
 8406                if selections.len() == 1 {
 8407                    let selection = selections
 8408                        .last()
 8409                        .expect("ensured that there's only one selection");
 8410                    let query = buffer
 8411                        .text_for_range(selection.start..selection.end)
 8412                        .collect::<String>();
 8413                    let is_empty = query.is_empty();
 8414                    let select_state = SelectNextState {
 8415                        query: AhoCorasick::new(&[query])?,
 8416                        wordwise: true,
 8417                        done: is_empty,
 8418                    };
 8419                    self.select_next_state = Some(select_state);
 8420                } else {
 8421                    self.select_next_state = None;
 8422                }
 8423            } else if let Some(selected_text) = selected_text {
 8424                self.select_next_state = Some(SelectNextState {
 8425                    query: AhoCorasick::new(&[selected_text])?,
 8426                    wordwise: false,
 8427                    done: false,
 8428                });
 8429                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8430            }
 8431        }
 8432        Ok(())
 8433    }
 8434
 8435    pub fn select_all_matches(
 8436        &mut self,
 8437        _action: &SelectAllMatches,
 8438        cx: &mut ViewContext<Self>,
 8439    ) -> Result<()> {
 8440        self.push_to_selection_history();
 8441        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8442
 8443        self.select_next_match_internal(&display_map, false, None, cx)?;
 8444        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8445            return Ok(());
 8446        };
 8447        if select_next_state.done {
 8448            return Ok(());
 8449        }
 8450
 8451        let mut new_selections = self.selections.all::<usize>(cx);
 8452
 8453        let buffer = &display_map.buffer_snapshot;
 8454        let query_matches = select_next_state
 8455            .query
 8456            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8457
 8458        for query_match in query_matches {
 8459            let query_match = query_match.unwrap(); // can only fail due to I/O
 8460            let offset_range = query_match.start()..query_match.end();
 8461            let display_range = offset_range.start.to_display_point(&display_map)
 8462                ..offset_range.end.to_display_point(&display_map);
 8463
 8464            if !select_next_state.wordwise
 8465                || (!movement::is_inside_word(&display_map, display_range.start)
 8466                    && !movement::is_inside_word(&display_map, display_range.end))
 8467            {
 8468                self.selections.change_with(cx, |selections| {
 8469                    new_selections.push(Selection {
 8470                        id: selections.new_selection_id(),
 8471                        start: offset_range.start,
 8472                        end: offset_range.end,
 8473                        reversed: false,
 8474                        goal: SelectionGoal::None,
 8475                    });
 8476                });
 8477            }
 8478        }
 8479
 8480        new_selections.sort_by_key(|selection| selection.start);
 8481        let mut ix = 0;
 8482        while ix + 1 < new_selections.len() {
 8483            let current_selection = &new_selections[ix];
 8484            let next_selection = &new_selections[ix + 1];
 8485            if current_selection.range().overlaps(&next_selection.range()) {
 8486                if current_selection.id < next_selection.id {
 8487                    new_selections.remove(ix + 1);
 8488                } else {
 8489                    new_selections.remove(ix);
 8490                }
 8491            } else {
 8492                ix += 1;
 8493            }
 8494        }
 8495
 8496        select_next_state.done = true;
 8497        self.unfold_ranges(
 8498            new_selections.iter().map(|selection| selection.range()),
 8499            false,
 8500            false,
 8501            cx,
 8502        );
 8503        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8504            selections.select(new_selections)
 8505        });
 8506
 8507        Ok(())
 8508    }
 8509
 8510    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8511        self.push_to_selection_history();
 8512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8513        self.select_next_match_internal(
 8514            &display_map,
 8515            action.replace_newest,
 8516            Some(Autoscroll::newest()),
 8517            cx,
 8518        )?;
 8519        Ok(())
 8520    }
 8521
 8522    pub fn select_previous(
 8523        &mut self,
 8524        action: &SelectPrevious,
 8525        cx: &mut ViewContext<Self>,
 8526    ) -> Result<()> {
 8527        self.push_to_selection_history();
 8528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8529        let buffer = &display_map.buffer_snapshot;
 8530        let mut selections = self.selections.all::<usize>(cx);
 8531        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8532            let query = &select_prev_state.query;
 8533            if !select_prev_state.done {
 8534                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8535                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8536                let mut next_selected_range = None;
 8537                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8538                let bytes_before_last_selection =
 8539                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8540                let bytes_after_first_selection =
 8541                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8542                let query_matches = query
 8543                    .stream_find_iter(bytes_before_last_selection)
 8544                    .map(|result| (last_selection.start, result))
 8545                    .chain(
 8546                        query
 8547                            .stream_find_iter(bytes_after_first_selection)
 8548                            .map(|result| (buffer.len(), result)),
 8549                    );
 8550                for (end_offset, query_match) in query_matches {
 8551                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8552                    let offset_range =
 8553                        end_offset - query_match.end()..end_offset - query_match.start();
 8554                    let display_range = offset_range.start.to_display_point(&display_map)
 8555                        ..offset_range.end.to_display_point(&display_map);
 8556
 8557                    if !select_prev_state.wordwise
 8558                        || (!movement::is_inside_word(&display_map, display_range.start)
 8559                            && !movement::is_inside_word(&display_map, display_range.end))
 8560                    {
 8561                        next_selected_range = Some(offset_range);
 8562                        break;
 8563                    }
 8564                }
 8565
 8566                if let Some(next_selected_range) = next_selected_range {
 8567                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8568                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8569                        if action.replace_newest {
 8570                            s.delete(s.newest_anchor().id);
 8571                        }
 8572                        s.insert_range(next_selected_range);
 8573                    });
 8574                } else {
 8575                    select_prev_state.done = true;
 8576                }
 8577            }
 8578
 8579            self.select_prev_state = Some(select_prev_state);
 8580        } else {
 8581            let mut only_carets = true;
 8582            let mut same_text_selected = true;
 8583            let mut selected_text = None;
 8584
 8585            let mut selections_iter = selections.iter().peekable();
 8586            while let Some(selection) = selections_iter.next() {
 8587                if selection.start != selection.end {
 8588                    only_carets = false;
 8589                }
 8590
 8591                if same_text_selected {
 8592                    if selected_text.is_none() {
 8593                        selected_text =
 8594                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8595                    }
 8596
 8597                    if let Some(next_selection) = selections_iter.peek() {
 8598                        if next_selection.range().len() == selection.range().len() {
 8599                            let next_selected_text = buffer
 8600                                .text_for_range(next_selection.range())
 8601                                .collect::<String>();
 8602                            if Some(next_selected_text) != selected_text {
 8603                                same_text_selected = false;
 8604                                selected_text = None;
 8605                            }
 8606                        } else {
 8607                            same_text_selected = false;
 8608                            selected_text = None;
 8609                        }
 8610                    }
 8611                }
 8612            }
 8613
 8614            if only_carets {
 8615                for selection in &mut selections {
 8616                    let word_range = movement::surrounding_word(
 8617                        &display_map,
 8618                        selection.start.to_display_point(&display_map),
 8619                    );
 8620                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8621                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8622                    selection.goal = SelectionGoal::None;
 8623                    selection.reversed = false;
 8624                }
 8625                if selections.len() == 1 {
 8626                    let selection = selections
 8627                        .last()
 8628                        .expect("ensured that there's only one selection");
 8629                    let query = buffer
 8630                        .text_for_range(selection.start..selection.end)
 8631                        .collect::<String>();
 8632                    let is_empty = query.is_empty();
 8633                    let select_state = SelectNextState {
 8634                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8635                        wordwise: true,
 8636                        done: is_empty,
 8637                    };
 8638                    self.select_prev_state = Some(select_state);
 8639                } else {
 8640                    self.select_prev_state = None;
 8641                }
 8642
 8643                self.unfold_ranges(
 8644                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8645                    false,
 8646                    true,
 8647                    cx,
 8648                );
 8649                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8650                    s.select(selections);
 8651                });
 8652            } else if let Some(selected_text) = selected_text {
 8653                self.select_prev_state = Some(SelectNextState {
 8654                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8655                    wordwise: false,
 8656                    done: false,
 8657                });
 8658                self.select_previous(action, cx)?;
 8659            }
 8660        }
 8661        Ok(())
 8662    }
 8663
 8664    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8665        let text_layout_details = &self.text_layout_details(cx);
 8666        self.transact(cx, |this, cx| {
 8667            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8668            let mut edits = Vec::new();
 8669            let mut selection_edit_ranges = Vec::new();
 8670            let mut last_toggled_row = None;
 8671            let snapshot = this.buffer.read(cx).read(cx);
 8672            let empty_str: Arc<str> = Arc::default();
 8673            let mut suffixes_inserted = Vec::new();
 8674
 8675            fn comment_prefix_range(
 8676                snapshot: &MultiBufferSnapshot,
 8677                row: MultiBufferRow,
 8678                comment_prefix: &str,
 8679                comment_prefix_whitespace: &str,
 8680            ) -> Range<Point> {
 8681                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8682
 8683                let mut line_bytes = snapshot
 8684                    .bytes_in_range(start..snapshot.max_point())
 8685                    .flatten()
 8686                    .copied();
 8687
 8688                // If this line currently begins with the line comment prefix, then record
 8689                // the range containing the prefix.
 8690                if line_bytes
 8691                    .by_ref()
 8692                    .take(comment_prefix.len())
 8693                    .eq(comment_prefix.bytes())
 8694                {
 8695                    // Include any whitespace that matches the comment prefix.
 8696                    let matching_whitespace_len = line_bytes
 8697                        .zip(comment_prefix_whitespace.bytes())
 8698                        .take_while(|(a, b)| a == b)
 8699                        .count() as u32;
 8700                    let end = Point::new(
 8701                        start.row,
 8702                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8703                    );
 8704                    start..end
 8705                } else {
 8706                    start..start
 8707                }
 8708            }
 8709
 8710            fn comment_suffix_range(
 8711                snapshot: &MultiBufferSnapshot,
 8712                row: MultiBufferRow,
 8713                comment_suffix: &str,
 8714                comment_suffix_has_leading_space: bool,
 8715            ) -> Range<Point> {
 8716                let end = Point::new(row.0, snapshot.line_len(row));
 8717                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8718
 8719                let mut line_end_bytes = snapshot
 8720                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8721                    .flatten()
 8722                    .copied();
 8723
 8724                let leading_space_len = if suffix_start_column > 0
 8725                    && line_end_bytes.next() == Some(b' ')
 8726                    && comment_suffix_has_leading_space
 8727                {
 8728                    1
 8729                } else {
 8730                    0
 8731                };
 8732
 8733                // If this line currently begins with the line comment prefix, then record
 8734                // the range containing the prefix.
 8735                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8736                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8737                    start..end
 8738                } else {
 8739                    end..end
 8740                }
 8741            }
 8742
 8743            // TODO: Handle selections that cross excerpts
 8744            for selection in &mut selections {
 8745                let start_column = snapshot
 8746                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8747                    .len;
 8748                let language = if let Some(language) =
 8749                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8750                {
 8751                    language
 8752                } else {
 8753                    continue;
 8754                };
 8755
 8756                selection_edit_ranges.clear();
 8757
 8758                // If multiple selections contain a given row, avoid processing that
 8759                // row more than once.
 8760                let mut start_row = MultiBufferRow(selection.start.row);
 8761                if last_toggled_row == Some(start_row) {
 8762                    start_row = start_row.next_row();
 8763                }
 8764                let end_row =
 8765                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8766                        MultiBufferRow(selection.end.row - 1)
 8767                    } else {
 8768                        MultiBufferRow(selection.end.row)
 8769                    };
 8770                last_toggled_row = Some(end_row);
 8771
 8772                if start_row > end_row {
 8773                    continue;
 8774                }
 8775
 8776                // If the language has line comments, toggle those.
 8777                let full_comment_prefixes = language.line_comment_prefixes();
 8778                if !full_comment_prefixes.is_empty() {
 8779                    let first_prefix = full_comment_prefixes
 8780                        .first()
 8781                        .expect("prefixes is non-empty");
 8782                    let prefix_trimmed_lengths = full_comment_prefixes
 8783                        .iter()
 8784                        .map(|p| p.trim_end_matches(' ').len())
 8785                        .collect::<SmallVec<[usize; 4]>>();
 8786
 8787                    let mut all_selection_lines_are_comments = true;
 8788
 8789                    for row in start_row.0..=end_row.0 {
 8790                        let row = MultiBufferRow(row);
 8791                        if start_row < end_row && snapshot.is_line_blank(row) {
 8792                            continue;
 8793                        }
 8794
 8795                        let prefix_range = full_comment_prefixes
 8796                            .iter()
 8797                            .zip(prefix_trimmed_lengths.iter().copied())
 8798                            .map(|(prefix, trimmed_prefix_len)| {
 8799                                comment_prefix_range(
 8800                                    snapshot.deref(),
 8801                                    row,
 8802                                    &prefix[..trimmed_prefix_len],
 8803                                    &prefix[trimmed_prefix_len..],
 8804                                )
 8805                            })
 8806                            .max_by_key(|range| range.end.column - range.start.column)
 8807                            .expect("prefixes is non-empty");
 8808
 8809                        if prefix_range.is_empty() {
 8810                            all_selection_lines_are_comments = false;
 8811                        }
 8812
 8813                        selection_edit_ranges.push(prefix_range);
 8814                    }
 8815
 8816                    if all_selection_lines_are_comments {
 8817                        edits.extend(
 8818                            selection_edit_ranges
 8819                                .iter()
 8820                                .cloned()
 8821                                .map(|range| (range, empty_str.clone())),
 8822                        );
 8823                    } else {
 8824                        let min_column = selection_edit_ranges
 8825                            .iter()
 8826                            .map(|range| range.start.column)
 8827                            .min()
 8828                            .unwrap_or(0);
 8829                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8830                            let position = Point::new(range.start.row, min_column);
 8831                            (position..position, first_prefix.clone())
 8832                        }));
 8833                    }
 8834                } else if let Some((full_comment_prefix, comment_suffix)) =
 8835                    language.block_comment_delimiters()
 8836                {
 8837                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8838                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8839                    let prefix_range = comment_prefix_range(
 8840                        snapshot.deref(),
 8841                        start_row,
 8842                        comment_prefix,
 8843                        comment_prefix_whitespace,
 8844                    );
 8845                    let suffix_range = comment_suffix_range(
 8846                        snapshot.deref(),
 8847                        end_row,
 8848                        comment_suffix.trim_start_matches(' '),
 8849                        comment_suffix.starts_with(' '),
 8850                    );
 8851
 8852                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8853                        edits.push((
 8854                            prefix_range.start..prefix_range.start,
 8855                            full_comment_prefix.clone(),
 8856                        ));
 8857                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8858                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8859                    } else {
 8860                        edits.push((prefix_range, empty_str.clone()));
 8861                        edits.push((suffix_range, empty_str.clone()));
 8862                    }
 8863                } else {
 8864                    continue;
 8865                }
 8866            }
 8867
 8868            drop(snapshot);
 8869            this.buffer.update(cx, |buffer, cx| {
 8870                buffer.edit(edits, None, cx);
 8871            });
 8872
 8873            // Adjust selections so that they end before any comment suffixes that
 8874            // were inserted.
 8875            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8876            let mut selections = this.selections.all::<Point>(cx);
 8877            let snapshot = this.buffer.read(cx).read(cx);
 8878            for selection in &mut selections {
 8879                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8880                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8881                        Ordering::Less => {
 8882                            suffixes_inserted.next();
 8883                            continue;
 8884                        }
 8885                        Ordering::Greater => break,
 8886                        Ordering::Equal => {
 8887                            if selection.end.column == snapshot.line_len(row) {
 8888                                if selection.is_empty() {
 8889                                    selection.start.column -= suffix_len as u32;
 8890                                }
 8891                                selection.end.column -= suffix_len as u32;
 8892                            }
 8893                            break;
 8894                        }
 8895                    }
 8896                }
 8897            }
 8898
 8899            drop(snapshot);
 8900            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8901
 8902            let selections = this.selections.all::<Point>(cx);
 8903            let selections_on_single_row = selections.windows(2).all(|selections| {
 8904                selections[0].start.row == selections[1].start.row
 8905                    && selections[0].end.row == selections[1].end.row
 8906                    && selections[0].start.row == selections[0].end.row
 8907            });
 8908            let selections_selecting = selections
 8909                .iter()
 8910                .any(|selection| selection.start != selection.end);
 8911            let advance_downwards = action.advance_downwards
 8912                && selections_on_single_row
 8913                && !selections_selecting
 8914                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8915
 8916            if advance_downwards {
 8917                let snapshot = this.buffer.read(cx).snapshot(cx);
 8918
 8919                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8920                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8921                        let mut point = display_point.to_point(display_snapshot);
 8922                        point.row += 1;
 8923                        point = snapshot.clip_point(point, Bias::Left);
 8924                        let display_point = point.to_display_point(display_snapshot);
 8925                        let goal = SelectionGoal::HorizontalPosition(
 8926                            display_snapshot
 8927                                .x_for_display_point(display_point, text_layout_details)
 8928                                .into(),
 8929                        );
 8930                        (display_point, goal)
 8931                    })
 8932                });
 8933            }
 8934        });
 8935    }
 8936
 8937    pub fn select_enclosing_symbol(
 8938        &mut self,
 8939        _: &SelectEnclosingSymbol,
 8940        cx: &mut ViewContext<Self>,
 8941    ) {
 8942        let buffer = self.buffer.read(cx).snapshot(cx);
 8943        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8944
 8945        fn update_selection(
 8946            selection: &Selection<usize>,
 8947            buffer_snap: &MultiBufferSnapshot,
 8948        ) -> Option<Selection<usize>> {
 8949            let cursor = selection.head();
 8950            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8951            for symbol in symbols.iter().rev() {
 8952                let start = symbol.range.start.to_offset(buffer_snap);
 8953                let end = symbol.range.end.to_offset(buffer_snap);
 8954                let new_range = start..end;
 8955                if start < selection.start || end > selection.end {
 8956                    return Some(Selection {
 8957                        id: selection.id,
 8958                        start: new_range.start,
 8959                        end: new_range.end,
 8960                        goal: SelectionGoal::None,
 8961                        reversed: selection.reversed,
 8962                    });
 8963                }
 8964            }
 8965            None
 8966        }
 8967
 8968        let mut selected_larger_symbol = false;
 8969        let new_selections = old_selections
 8970            .iter()
 8971            .map(|selection| match update_selection(selection, &buffer) {
 8972                Some(new_selection) => {
 8973                    if new_selection.range() != selection.range() {
 8974                        selected_larger_symbol = true;
 8975                    }
 8976                    new_selection
 8977                }
 8978                None => selection.clone(),
 8979            })
 8980            .collect::<Vec<_>>();
 8981
 8982        if selected_larger_symbol {
 8983            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8984                s.select(new_selections);
 8985            });
 8986        }
 8987    }
 8988
 8989    pub fn select_larger_syntax_node(
 8990        &mut self,
 8991        _: &SelectLargerSyntaxNode,
 8992        cx: &mut ViewContext<Self>,
 8993    ) {
 8994        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8995        let buffer = self.buffer.read(cx).snapshot(cx);
 8996        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8997
 8998        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8999        let mut selected_larger_node = false;
 9000        let new_selections = old_selections
 9001            .iter()
 9002            .map(|selection| {
 9003                let old_range = selection.start..selection.end;
 9004                let mut new_range = old_range.clone();
 9005                while let Some(containing_range) =
 9006                    buffer.range_for_syntax_ancestor(new_range.clone())
 9007                {
 9008                    new_range = containing_range;
 9009                    if !display_map.intersects_fold(new_range.start)
 9010                        && !display_map.intersects_fold(new_range.end)
 9011                    {
 9012                        break;
 9013                    }
 9014                }
 9015
 9016                selected_larger_node |= new_range != old_range;
 9017                Selection {
 9018                    id: selection.id,
 9019                    start: new_range.start,
 9020                    end: new_range.end,
 9021                    goal: SelectionGoal::None,
 9022                    reversed: selection.reversed,
 9023                }
 9024            })
 9025            .collect::<Vec<_>>();
 9026
 9027        if selected_larger_node {
 9028            stack.push(old_selections);
 9029            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9030                s.select(new_selections);
 9031            });
 9032        }
 9033        self.select_larger_syntax_node_stack = stack;
 9034    }
 9035
 9036    pub fn select_smaller_syntax_node(
 9037        &mut self,
 9038        _: &SelectSmallerSyntaxNode,
 9039        cx: &mut ViewContext<Self>,
 9040    ) {
 9041        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9042        if let Some(selections) = stack.pop() {
 9043            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9044                s.select(selections.to_vec());
 9045            });
 9046        }
 9047        self.select_larger_syntax_node_stack = stack;
 9048    }
 9049
 9050    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9051        if !EditorSettings::get_global(cx).gutter.runnables {
 9052            self.clear_tasks();
 9053            return Task::ready(());
 9054        }
 9055        let project = self.project.clone();
 9056        cx.spawn(|this, mut cx| async move {
 9057            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9058                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9059            }) else {
 9060                return;
 9061            };
 9062
 9063            let Some(project) = project else {
 9064                return;
 9065            };
 9066
 9067            let hide_runnables = project
 9068                .update(&mut cx, |project, cx| {
 9069                    // Do not display any test indicators in non-dev server remote projects.
 9070                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9071                })
 9072                .unwrap_or(true);
 9073            if hide_runnables {
 9074                return;
 9075            }
 9076            let new_rows =
 9077                cx.background_executor()
 9078                    .spawn({
 9079                        let snapshot = display_snapshot.clone();
 9080                        async move {
 9081                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9082                        }
 9083                    })
 9084                    .await;
 9085            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9086
 9087            this.update(&mut cx, |this, _| {
 9088                this.clear_tasks();
 9089                for (key, value) in rows {
 9090                    this.insert_tasks(key, value);
 9091                }
 9092            })
 9093            .ok();
 9094        })
 9095    }
 9096    fn fetch_runnable_ranges(
 9097        snapshot: &DisplaySnapshot,
 9098        range: Range<Anchor>,
 9099    ) -> Vec<language::RunnableRange> {
 9100        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9101    }
 9102
 9103    fn runnable_rows(
 9104        project: Model<Project>,
 9105        snapshot: DisplaySnapshot,
 9106        runnable_ranges: Vec<RunnableRange>,
 9107        mut cx: AsyncWindowContext,
 9108    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9109        runnable_ranges
 9110            .into_iter()
 9111            .filter_map(|mut runnable| {
 9112                let tasks = cx
 9113                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9114                    .ok()?;
 9115                if tasks.is_empty() {
 9116                    return None;
 9117                }
 9118
 9119                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9120
 9121                let row = snapshot
 9122                    .buffer_snapshot
 9123                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9124                    .1
 9125                    .start
 9126                    .row;
 9127
 9128                let context_range =
 9129                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9130                Some((
 9131                    (runnable.buffer_id, row),
 9132                    RunnableTasks {
 9133                        templates: tasks,
 9134                        offset: MultiBufferOffset(runnable.run_range.start),
 9135                        context_range,
 9136                        column: point.column,
 9137                        extra_variables: runnable.extra_captures,
 9138                    },
 9139                ))
 9140            })
 9141            .collect()
 9142    }
 9143
 9144    fn templates_with_tags(
 9145        project: &Model<Project>,
 9146        runnable: &mut Runnable,
 9147        cx: &WindowContext<'_>,
 9148    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9149        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9150            let (worktree_id, file) = project
 9151                .buffer_for_id(runnable.buffer, cx)
 9152                .and_then(|buffer| buffer.read(cx).file())
 9153                .map(|file| (file.worktree_id(cx), file.clone()))
 9154                .unzip();
 9155
 9156            (
 9157                project.task_store().read(cx).task_inventory().cloned(),
 9158                worktree_id,
 9159                file,
 9160            )
 9161        });
 9162
 9163        let tags = mem::take(&mut runnable.tags);
 9164        let mut tags: Vec<_> = tags
 9165            .into_iter()
 9166            .flat_map(|tag| {
 9167                let tag = tag.0.clone();
 9168                inventory
 9169                    .as_ref()
 9170                    .into_iter()
 9171                    .flat_map(|inventory| {
 9172                        inventory.read(cx).list_tasks(
 9173                            file.clone(),
 9174                            Some(runnable.language.clone()),
 9175                            worktree_id,
 9176                            cx,
 9177                        )
 9178                    })
 9179                    .filter(move |(_, template)| {
 9180                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9181                    })
 9182            })
 9183            .sorted_by_key(|(kind, _)| kind.to_owned())
 9184            .collect();
 9185        if let Some((leading_tag_source, _)) = tags.first() {
 9186            // Strongest source wins; if we have worktree tag binding, prefer that to
 9187            // global and language bindings;
 9188            // if we have a global binding, prefer that to language binding.
 9189            let first_mismatch = tags
 9190                .iter()
 9191                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9192            if let Some(index) = first_mismatch {
 9193                tags.truncate(index);
 9194            }
 9195        }
 9196
 9197        tags
 9198    }
 9199
 9200    pub fn move_to_enclosing_bracket(
 9201        &mut self,
 9202        _: &MoveToEnclosingBracket,
 9203        cx: &mut ViewContext<Self>,
 9204    ) {
 9205        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9206            s.move_offsets_with(|snapshot, selection| {
 9207                let Some(enclosing_bracket_ranges) =
 9208                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9209                else {
 9210                    return;
 9211                };
 9212
 9213                let mut best_length = usize::MAX;
 9214                let mut best_inside = false;
 9215                let mut best_in_bracket_range = false;
 9216                let mut best_destination = None;
 9217                for (open, close) in enclosing_bracket_ranges {
 9218                    let close = close.to_inclusive();
 9219                    let length = close.end() - open.start;
 9220                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9221                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9222                        || close.contains(&selection.head());
 9223
 9224                    // If best is next to a bracket and current isn't, skip
 9225                    if !in_bracket_range && best_in_bracket_range {
 9226                        continue;
 9227                    }
 9228
 9229                    // Prefer smaller lengths unless best is inside and current isn't
 9230                    if length > best_length && (best_inside || !inside) {
 9231                        continue;
 9232                    }
 9233
 9234                    best_length = length;
 9235                    best_inside = inside;
 9236                    best_in_bracket_range = in_bracket_range;
 9237                    best_destination = Some(
 9238                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9239                            if inside {
 9240                                open.end
 9241                            } else {
 9242                                open.start
 9243                            }
 9244                        } else if inside {
 9245                            *close.start()
 9246                        } else {
 9247                            *close.end()
 9248                        },
 9249                    );
 9250                }
 9251
 9252                if let Some(destination) = best_destination {
 9253                    selection.collapse_to(destination, SelectionGoal::None);
 9254                }
 9255            })
 9256        });
 9257    }
 9258
 9259    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9260        self.end_selection(cx);
 9261        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9262        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9263            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9264            self.select_next_state = entry.select_next_state;
 9265            self.select_prev_state = entry.select_prev_state;
 9266            self.add_selections_state = entry.add_selections_state;
 9267            self.request_autoscroll(Autoscroll::newest(), cx);
 9268        }
 9269        self.selection_history.mode = SelectionHistoryMode::Normal;
 9270    }
 9271
 9272    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9273        self.end_selection(cx);
 9274        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9275        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9276            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9277            self.select_next_state = entry.select_next_state;
 9278            self.select_prev_state = entry.select_prev_state;
 9279            self.add_selections_state = entry.add_selections_state;
 9280            self.request_autoscroll(Autoscroll::newest(), cx);
 9281        }
 9282        self.selection_history.mode = SelectionHistoryMode::Normal;
 9283    }
 9284
 9285    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9286        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9287    }
 9288
 9289    pub fn expand_excerpts_down(
 9290        &mut self,
 9291        action: &ExpandExcerptsDown,
 9292        cx: &mut ViewContext<Self>,
 9293    ) {
 9294        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9295    }
 9296
 9297    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9298        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9299    }
 9300
 9301    pub fn expand_excerpts_for_direction(
 9302        &mut self,
 9303        lines: u32,
 9304        direction: ExpandExcerptDirection,
 9305        cx: &mut ViewContext<Self>,
 9306    ) {
 9307        let selections = self.selections.disjoint_anchors();
 9308
 9309        let lines = if lines == 0 {
 9310            EditorSettings::get_global(cx).expand_excerpt_lines
 9311        } else {
 9312            lines
 9313        };
 9314
 9315        self.buffer.update(cx, |buffer, cx| {
 9316            buffer.expand_excerpts(
 9317                selections
 9318                    .iter()
 9319                    .map(|selection| selection.head().excerpt_id)
 9320                    .dedup(),
 9321                lines,
 9322                direction,
 9323                cx,
 9324            )
 9325        })
 9326    }
 9327
 9328    pub fn expand_excerpt(
 9329        &mut self,
 9330        excerpt: ExcerptId,
 9331        direction: ExpandExcerptDirection,
 9332        cx: &mut ViewContext<Self>,
 9333    ) {
 9334        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9335        self.buffer.update(cx, |buffer, cx| {
 9336            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9337        })
 9338    }
 9339
 9340    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9341        self.go_to_diagnostic_impl(Direction::Next, cx)
 9342    }
 9343
 9344    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9345        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9346    }
 9347
 9348    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9349        let buffer = self.buffer.read(cx).snapshot(cx);
 9350        let selection = self.selections.newest::<usize>(cx);
 9351
 9352        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9353        if direction == Direction::Next {
 9354            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9355                let (group_id, jump_to) = popover.activation_info();
 9356                if self.activate_diagnostics(group_id, cx) {
 9357                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9358                        let mut new_selection = s.newest_anchor().clone();
 9359                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9360                        s.select_anchors(vec![new_selection.clone()]);
 9361                    });
 9362                }
 9363                return;
 9364            }
 9365        }
 9366
 9367        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9368            active_diagnostics
 9369                .primary_range
 9370                .to_offset(&buffer)
 9371                .to_inclusive()
 9372        });
 9373        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9374            if active_primary_range.contains(&selection.head()) {
 9375                *active_primary_range.start()
 9376            } else {
 9377                selection.head()
 9378            }
 9379        } else {
 9380            selection.head()
 9381        };
 9382        let snapshot = self.snapshot(cx);
 9383        loop {
 9384            let diagnostics = if direction == Direction::Prev {
 9385                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9386            } else {
 9387                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9388            }
 9389            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9390            let group = diagnostics
 9391                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9392                // be sorted in a stable way
 9393                // skip until we are at current active diagnostic, if it exists
 9394                .skip_while(|entry| {
 9395                    (match direction {
 9396                        Direction::Prev => entry.range.start >= search_start,
 9397                        Direction::Next => entry.range.start <= search_start,
 9398                    }) && self
 9399                        .active_diagnostics
 9400                        .as_ref()
 9401                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9402                })
 9403                .find_map(|entry| {
 9404                    if entry.diagnostic.is_primary
 9405                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9406                        && !entry.range.is_empty()
 9407                        // if we match with the active diagnostic, skip it
 9408                        && Some(entry.diagnostic.group_id)
 9409                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9410                    {
 9411                        Some((entry.range, entry.diagnostic.group_id))
 9412                    } else {
 9413                        None
 9414                    }
 9415                });
 9416
 9417            if let Some((primary_range, group_id)) = group {
 9418                if self.activate_diagnostics(group_id, cx) {
 9419                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9420                        s.select(vec![Selection {
 9421                            id: selection.id,
 9422                            start: primary_range.start,
 9423                            end: primary_range.start,
 9424                            reversed: false,
 9425                            goal: SelectionGoal::None,
 9426                        }]);
 9427                    });
 9428                }
 9429                break;
 9430            } else {
 9431                // Cycle around to the start of the buffer, potentially moving back to the start of
 9432                // the currently active diagnostic.
 9433                active_primary_range.take();
 9434                if direction == Direction::Prev {
 9435                    if search_start == buffer.len() {
 9436                        break;
 9437                    } else {
 9438                        search_start = buffer.len();
 9439                    }
 9440                } else if search_start == 0 {
 9441                    break;
 9442                } else {
 9443                    search_start = 0;
 9444                }
 9445            }
 9446        }
 9447    }
 9448
 9449    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9450        let snapshot = self
 9451            .display_map
 9452            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9453        let selection = self.selections.newest::<Point>(cx);
 9454        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9455    }
 9456
 9457    fn go_to_hunk_after_position(
 9458        &mut self,
 9459        snapshot: &DisplaySnapshot,
 9460        position: Point,
 9461        cx: &mut ViewContext<'_, Editor>,
 9462    ) -> Option<MultiBufferDiffHunk> {
 9463        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9464            snapshot,
 9465            position,
 9466            false,
 9467            snapshot
 9468                .buffer_snapshot
 9469                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9470            cx,
 9471        ) {
 9472            return Some(hunk);
 9473        }
 9474
 9475        let wrapped_point = Point::zero();
 9476        self.go_to_next_hunk_in_direction(
 9477            snapshot,
 9478            wrapped_point,
 9479            true,
 9480            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9481                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9482            ),
 9483            cx,
 9484        )
 9485    }
 9486
 9487    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9488        let snapshot = self
 9489            .display_map
 9490            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9491        let selection = self.selections.newest::<Point>(cx);
 9492
 9493        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9494    }
 9495
 9496    fn go_to_hunk_before_position(
 9497        &mut self,
 9498        snapshot: &DisplaySnapshot,
 9499        position: Point,
 9500        cx: &mut ViewContext<'_, Editor>,
 9501    ) -> Option<MultiBufferDiffHunk> {
 9502        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9503            snapshot,
 9504            position,
 9505            false,
 9506            snapshot
 9507                .buffer_snapshot
 9508                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9509            cx,
 9510        ) {
 9511            return Some(hunk);
 9512        }
 9513
 9514        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9515        self.go_to_next_hunk_in_direction(
 9516            snapshot,
 9517            wrapped_point,
 9518            true,
 9519            snapshot
 9520                .buffer_snapshot
 9521                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9522            cx,
 9523        )
 9524    }
 9525
 9526    fn go_to_next_hunk_in_direction(
 9527        &mut self,
 9528        snapshot: &DisplaySnapshot,
 9529        initial_point: Point,
 9530        is_wrapped: bool,
 9531        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9532        cx: &mut ViewContext<Editor>,
 9533    ) -> Option<MultiBufferDiffHunk> {
 9534        let display_point = initial_point.to_display_point(snapshot);
 9535        let mut hunks = hunks
 9536            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9537            .filter(|(display_hunk, _)| {
 9538                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9539            })
 9540            .dedup();
 9541
 9542        if let Some((display_hunk, hunk)) = hunks.next() {
 9543            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9544                let row = display_hunk.start_display_row();
 9545                let point = DisplayPoint::new(row, 0);
 9546                s.select_display_ranges([point..point]);
 9547            });
 9548
 9549            Some(hunk)
 9550        } else {
 9551            None
 9552        }
 9553    }
 9554
 9555    pub fn go_to_definition(
 9556        &mut self,
 9557        _: &GoToDefinition,
 9558        cx: &mut ViewContext<Self>,
 9559    ) -> Task<Result<Navigated>> {
 9560        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9561        cx.spawn(|editor, mut cx| async move {
 9562            if definition.await? == Navigated::Yes {
 9563                return Ok(Navigated::Yes);
 9564            }
 9565            match editor.update(&mut cx, |editor, cx| {
 9566                editor.find_all_references(&FindAllReferences, cx)
 9567            })? {
 9568                Some(references) => references.await,
 9569                None => Ok(Navigated::No),
 9570            }
 9571        })
 9572    }
 9573
 9574    pub fn go_to_declaration(
 9575        &mut self,
 9576        _: &GoToDeclaration,
 9577        cx: &mut ViewContext<Self>,
 9578    ) -> Task<Result<Navigated>> {
 9579        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9580    }
 9581
 9582    pub fn go_to_declaration_split(
 9583        &mut self,
 9584        _: &GoToDeclaration,
 9585        cx: &mut ViewContext<Self>,
 9586    ) -> Task<Result<Navigated>> {
 9587        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9588    }
 9589
 9590    pub fn go_to_implementation(
 9591        &mut self,
 9592        _: &GoToImplementation,
 9593        cx: &mut ViewContext<Self>,
 9594    ) -> Task<Result<Navigated>> {
 9595        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9596    }
 9597
 9598    pub fn go_to_implementation_split(
 9599        &mut self,
 9600        _: &GoToImplementationSplit,
 9601        cx: &mut ViewContext<Self>,
 9602    ) -> Task<Result<Navigated>> {
 9603        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9604    }
 9605
 9606    pub fn go_to_type_definition(
 9607        &mut self,
 9608        _: &GoToTypeDefinition,
 9609        cx: &mut ViewContext<Self>,
 9610    ) -> Task<Result<Navigated>> {
 9611        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9612    }
 9613
 9614    pub fn go_to_definition_split(
 9615        &mut self,
 9616        _: &GoToDefinitionSplit,
 9617        cx: &mut ViewContext<Self>,
 9618    ) -> Task<Result<Navigated>> {
 9619        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9620    }
 9621
 9622    pub fn go_to_type_definition_split(
 9623        &mut self,
 9624        _: &GoToTypeDefinitionSplit,
 9625        cx: &mut ViewContext<Self>,
 9626    ) -> Task<Result<Navigated>> {
 9627        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9628    }
 9629
 9630    fn go_to_definition_of_kind(
 9631        &mut self,
 9632        kind: GotoDefinitionKind,
 9633        split: bool,
 9634        cx: &mut ViewContext<Self>,
 9635    ) -> Task<Result<Navigated>> {
 9636        let Some(provider) = self.semantics_provider.clone() else {
 9637            return Task::ready(Ok(Navigated::No));
 9638        };
 9639        let buffer = self.buffer.read(cx);
 9640        let head = self.selections.newest::<usize>(cx).head();
 9641        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9642            text_anchor
 9643        } else {
 9644            return Task::ready(Ok(Navigated::No));
 9645        };
 9646
 9647        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9648            return Task::ready(Ok(Navigated::No));
 9649        };
 9650
 9651        cx.spawn(|editor, mut cx| async move {
 9652            let definitions = definitions.await?;
 9653            let navigated = editor
 9654                .update(&mut cx, |editor, cx| {
 9655                    editor.navigate_to_hover_links(
 9656                        Some(kind),
 9657                        definitions
 9658                            .into_iter()
 9659                            .filter(|location| {
 9660                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9661                            })
 9662                            .map(HoverLink::Text)
 9663                            .collect::<Vec<_>>(),
 9664                        split,
 9665                        cx,
 9666                    )
 9667                })?
 9668                .await?;
 9669            anyhow::Ok(navigated)
 9670        })
 9671    }
 9672
 9673    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9674        let position = self.selections.newest_anchor().head();
 9675        let Some((buffer, buffer_position)) =
 9676            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9677        else {
 9678            return;
 9679        };
 9680
 9681        cx.spawn(|editor, mut cx| async move {
 9682            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9683                editor.update(&mut cx, |_, cx| {
 9684                    cx.open_url(&url);
 9685                })
 9686            } else {
 9687                Ok(())
 9688            }
 9689        })
 9690        .detach();
 9691    }
 9692
 9693    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9694        let Some(workspace) = self.workspace() else {
 9695            return;
 9696        };
 9697
 9698        let position = self.selections.newest_anchor().head();
 9699
 9700        let Some((buffer, buffer_position)) =
 9701            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9702        else {
 9703            return;
 9704        };
 9705
 9706        let project = self.project.clone();
 9707
 9708        cx.spawn(|_, mut cx| async move {
 9709            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9710
 9711            if let Some((_, path)) = result {
 9712                workspace
 9713                    .update(&mut cx, |workspace, cx| {
 9714                        workspace.open_resolved_path(path, cx)
 9715                    })?
 9716                    .await?;
 9717            }
 9718            anyhow::Ok(())
 9719        })
 9720        .detach();
 9721    }
 9722
 9723    pub(crate) fn navigate_to_hover_links(
 9724        &mut self,
 9725        kind: Option<GotoDefinitionKind>,
 9726        mut definitions: Vec<HoverLink>,
 9727        split: bool,
 9728        cx: &mut ViewContext<Editor>,
 9729    ) -> Task<Result<Navigated>> {
 9730        // If there is one definition, just open it directly
 9731        if definitions.len() == 1 {
 9732            let definition = definitions.pop().unwrap();
 9733
 9734            enum TargetTaskResult {
 9735                Location(Option<Location>),
 9736                AlreadyNavigated,
 9737            }
 9738
 9739            let target_task = match definition {
 9740                HoverLink::Text(link) => {
 9741                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9742                }
 9743                HoverLink::InlayHint(lsp_location, server_id) => {
 9744                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9745                    cx.background_executor().spawn(async move {
 9746                        let location = computation.await?;
 9747                        Ok(TargetTaskResult::Location(location))
 9748                    })
 9749                }
 9750                HoverLink::Url(url) => {
 9751                    cx.open_url(&url);
 9752                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9753                }
 9754                HoverLink::File(path) => {
 9755                    if let Some(workspace) = self.workspace() {
 9756                        cx.spawn(|_, mut cx| async move {
 9757                            workspace
 9758                                .update(&mut cx, |workspace, cx| {
 9759                                    workspace.open_resolved_path(path, cx)
 9760                                })?
 9761                                .await
 9762                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9763                        })
 9764                    } else {
 9765                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9766                    }
 9767                }
 9768            };
 9769            cx.spawn(|editor, mut cx| async move {
 9770                let target = match target_task.await.context("target resolution task")? {
 9771                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9772                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9773                    TargetTaskResult::Location(Some(target)) => target,
 9774                };
 9775
 9776                editor.update(&mut cx, |editor, cx| {
 9777                    let Some(workspace) = editor.workspace() else {
 9778                        return Navigated::No;
 9779                    };
 9780                    let pane = workspace.read(cx).active_pane().clone();
 9781
 9782                    let range = target.range.to_offset(target.buffer.read(cx));
 9783                    let range = editor.range_for_match(&range);
 9784
 9785                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9786                        let buffer = target.buffer.read(cx);
 9787                        let range = check_multiline_range(buffer, range);
 9788                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9789                            s.select_ranges([range]);
 9790                        });
 9791                    } else {
 9792                        cx.window_context().defer(move |cx| {
 9793                            let target_editor: View<Self> =
 9794                                workspace.update(cx, |workspace, cx| {
 9795                                    let pane = if split {
 9796                                        workspace.adjacent_pane(cx)
 9797                                    } else {
 9798                                        workspace.active_pane().clone()
 9799                                    };
 9800
 9801                                    workspace.open_project_item(
 9802                                        pane,
 9803                                        target.buffer.clone(),
 9804                                        true,
 9805                                        true,
 9806                                        cx,
 9807                                    )
 9808                                });
 9809                            target_editor.update(cx, |target_editor, cx| {
 9810                                // When selecting a definition in a different buffer, disable the nav history
 9811                                // to avoid creating a history entry at the previous cursor location.
 9812                                pane.update(cx, |pane, _| pane.disable_history());
 9813                                let buffer = target.buffer.read(cx);
 9814                                let range = check_multiline_range(buffer, range);
 9815                                target_editor.change_selections(
 9816                                    Some(Autoscroll::focused()),
 9817                                    cx,
 9818                                    |s| {
 9819                                        s.select_ranges([range]);
 9820                                    },
 9821                                );
 9822                                pane.update(cx, |pane, _| pane.enable_history());
 9823                            });
 9824                        });
 9825                    }
 9826                    Navigated::Yes
 9827                })
 9828            })
 9829        } else if !definitions.is_empty() {
 9830            cx.spawn(|editor, mut cx| async move {
 9831                let (title, location_tasks, workspace) = editor
 9832                    .update(&mut cx, |editor, cx| {
 9833                        let tab_kind = match kind {
 9834                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9835                            _ => "Definitions",
 9836                        };
 9837                        let title = definitions
 9838                            .iter()
 9839                            .find_map(|definition| match definition {
 9840                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9841                                    let buffer = origin.buffer.read(cx);
 9842                                    format!(
 9843                                        "{} for {}",
 9844                                        tab_kind,
 9845                                        buffer
 9846                                            .text_for_range(origin.range.clone())
 9847                                            .collect::<String>()
 9848                                    )
 9849                                }),
 9850                                HoverLink::InlayHint(_, _) => None,
 9851                                HoverLink::Url(_) => None,
 9852                                HoverLink::File(_) => None,
 9853                            })
 9854                            .unwrap_or(tab_kind.to_string());
 9855                        let location_tasks = definitions
 9856                            .into_iter()
 9857                            .map(|definition| match definition {
 9858                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9859                                HoverLink::InlayHint(lsp_location, server_id) => {
 9860                                    editor.compute_target_location(lsp_location, server_id, cx)
 9861                                }
 9862                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9863                                HoverLink::File(_) => Task::ready(Ok(None)),
 9864                            })
 9865                            .collect::<Vec<_>>();
 9866                        (title, location_tasks, editor.workspace().clone())
 9867                    })
 9868                    .context("location tasks preparation")?;
 9869
 9870                let locations = future::join_all(location_tasks)
 9871                    .await
 9872                    .into_iter()
 9873                    .filter_map(|location| location.transpose())
 9874                    .collect::<Result<_>>()
 9875                    .context("location tasks")?;
 9876
 9877                let Some(workspace) = workspace else {
 9878                    return Ok(Navigated::No);
 9879                };
 9880                let opened = workspace
 9881                    .update(&mut cx, |workspace, cx| {
 9882                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9883                    })
 9884                    .ok();
 9885
 9886                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9887            })
 9888        } else {
 9889            Task::ready(Ok(Navigated::No))
 9890        }
 9891    }
 9892
 9893    fn compute_target_location(
 9894        &self,
 9895        lsp_location: lsp::Location,
 9896        server_id: LanguageServerId,
 9897        cx: &mut ViewContext<Self>,
 9898    ) -> Task<anyhow::Result<Option<Location>>> {
 9899        let Some(project) = self.project.clone() else {
 9900            return Task::Ready(Some(Ok(None)));
 9901        };
 9902
 9903        cx.spawn(move |editor, mut cx| async move {
 9904            let location_task = editor.update(&mut cx, |_, cx| {
 9905                project.update(cx, |project, cx| {
 9906                    let language_server_name = project
 9907                        .language_server_statuses(cx)
 9908                        .find(|(id, _)| server_id == *id)
 9909                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9910                    language_server_name.map(|language_server_name| {
 9911                        project.open_local_buffer_via_lsp(
 9912                            lsp_location.uri.clone(),
 9913                            server_id,
 9914                            language_server_name,
 9915                            cx,
 9916                        )
 9917                    })
 9918                })
 9919            })?;
 9920            let location = match location_task {
 9921                Some(task) => Some({
 9922                    let target_buffer_handle = task.await.context("open local buffer")?;
 9923                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9924                        let target_start = target_buffer
 9925                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9926                        let target_end = target_buffer
 9927                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9928                        target_buffer.anchor_after(target_start)
 9929                            ..target_buffer.anchor_before(target_end)
 9930                    })?;
 9931                    Location {
 9932                        buffer: target_buffer_handle,
 9933                        range,
 9934                    }
 9935                }),
 9936                None => None,
 9937            };
 9938            Ok(location)
 9939        })
 9940    }
 9941
 9942    pub fn find_all_references(
 9943        &mut self,
 9944        _: &FindAllReferences,
 9945        cx: &mut ViewContext<Self>,
 9946    ) -> Option<Task<Result<Navigated>>> {
 9947        let multi_buffer = self.buffer.read(cx);
 9948        let selection = self.selections.newest::<usize>(cx);
 9949        let head = selection.head();
 9950
 9951        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9952        let head_anchor = multi_buffer_snapshot.anchor_at(
 9953            head,
 9954            if head < selection.tail() {
 9955                Bias::Right
 9956            } else {
 9957                Bias::Left
 9958            },
 9959        );
 9960
 9961        match self
 9962            .find_all_references_task_sources
 9963            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9964        {
 9965            Ok(_) => {
 9966                log::info!(
 9967                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9968                );
 9969                return None;
 9970            }
 9971            Err(i) => {
 9972                self.find_all_references_task_sources.insert(i, head_anchor);
 9973            }
 9974        }
 9975
 9976        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9977        let workspace = self.workspace()?;
 9978        let project = workspace.read(cx).project().clone();
 9979        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9980        Some(cx.spawn(|editor, mut cx| async move {
 9981            let _cleanup = defer({
 9982                let mut cx = cx.clone();
 9983                move || {
 9984                    let _ = editor.update(&mut cx, |editor, _| {
 9985                        if let Ok(i) =
 9986                            editor
 9987                                .find_all_references_task_sources
 9988                                .binary_search_by(|anchor| {
 9989                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9990                                })
 9991                        {
 9992                            editor.find_all_references_task_sources.remove(i);
 9993                        }
 9994                    });
 9995                }
 9996            });
 9997
 9998            let locations = references.await?;
 9999            if locations.is_empty() {
10000                return anyhow::Ok(Navigated::No);
10001            }
10002
10003            workspace.update(&mut cx, |workspace, cx| {
10004                let title = locations
10005                    .first()
10006                    .as_ref()
10007                    .map(|location| {
10008                        let buffer = location.buffer.read(cx);
10009                        format!(
10010                            "References to `{}`",
10011                            buffer
10012                                .text_for_range(location.range.clone())
10013                                .collect::<String>()
10014                        )
10015                    })
10016                    .unwrap();
10017                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10018                Navigated::Yes
10019            })
10020        }))
10021    }
10022
10023    /// Opens a multibuffer with the given project locations in it
10024    pub fn open_locations_in_multibuffer(
10025        workspace: &mut Workspace,
10026        mut locations: Vec<Location>,
10027        title: String,
10028        split: bool,
10029        cx: &mut ViewContext<Workspace>,
10030    ) {
10031        // If there are multiple definitions, open them in a multibuffer
10032        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10033        let mut locations = locations.into_iter().peekable();
10034        let mut ranges_to_highlight = Vec::new();
10035        let capability = workspace.project().read(cx).capability();
10036
10037        let excerpt_buffer = cx.new_model(|cx| {
10038            let mut multibuffer = MultiBuffer::new(capability);
10039            while let Some(location) = locations.next() {
10040                let buffer = location.buffer.read(cx);
10041                let mut ranges_for_buffer = Vec::new();
10042                let range = location.range.to_offset(buffer);
10043                ranges_for_buffer.push(range.clone());
10044
10045                while let Some(next_location) = locations.peek() {
10046                    if next_location.buffer == location.buffer {
10047                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10048                        locations.next();
10049                    } else {
10050                        break;
10051                    }
10052                }
10053
10054                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10055                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10056                    location.buffer.clone(),
10057                    ranges_for_buffer,
10058                    DEFAULT_MULTIBUFFER_CONTEXT,
10059                    cx,
10060                ))
10061            }
10062
10063            multibuffer.with_title(title)
10064        });
10065
10066        let editor = cx.new_view(|cx| {
10067            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10068        });
10069        editor.update(cx, |editor, cx| {
10070            if let Some(first_range) = ranges_to_highlight.first() {
10071                editor.change_selections(None, cx, |selections| {
10072                    selections.clear_disjoint();
10073                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10074                });
10075            }
10076            editor.highlight_background::<Self>(
10077                &ranges_to_highlight,
10078                |theme| theme.editor_highlighted_line_background,
10079                cx,
10080            );
10081        });
10082
10083        let item = Box::new(editor);
10084        let item_id = item.item_id();
10085
10086        if split {
10087            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10088        } else {
10089            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10090                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10091                    pane.close_current_preview_item(cx)
10092                } else {
10093                    None
10094                }
10095            });
10096            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10097        }
10098        workspace.active_pane().update(cx, |pane, cx| {
10099            pane.set_preview_item_id(Some(item_id), cx);
10100        });
10101    }
10102
10103    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10104        use language::ToOffset as _;
10105
10106        let provider = self.semantics_provider.clone()?;
10107        let selection = self.selections.newest_anchor().clone();
10108        let (cursor_buffer, cursor_buffer_position) = self
10109            .buffer
10110            .read(cx)
10111            .text_anchor_for_position(selection.head(), cx)?;
10112        let (tail_buffer, cursor_buffer_position_end) = self
10113            .buffer
10114            .read(cx)
10115            .text_anchor_for_position(selection.tail(), cx)?;
10116        if tail_buffer != cursor_buffer {
10117            return None;
10118        }
10119
10120        let snapshot = cursor_buffer.read(cx).snapshot();
10121        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10122        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10123        let prepare_rename = provider
10124            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10125            .unwrap_or_else(|| Task::ready(Ok(None)));
10126        drop(snapshot);
10127
10128        Some(cx.spawn(|this, mut cx| async move {
10129            let rename_range = if let Some(range) = prepare_rename.await? {
10130                Some(range)
10131            } else {
10132                this.update(&mut cx, |this, cx| {
10133                    let buffer = this.buffer.read(cx).snapshot(cx);
10134                    let mut buffer_highlights = this
10135                        .document_highlights_for_position(selection.head(), &buffer)
10136                        .filter(|highlight| {
10137                            highlight.start.excerpt_id == selection.head().excerpt_id
10138                                && highlight.end.excerpt_id == selection.head().excerpt_id
10139                        });
10140                    buffer_highlights
10141                        .next()
10142                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10143                })?
10144            };
10145            if let Some(rename_range) = rename_range {
10146                this.update(&mut cx, |this, cx| {
10147                    let snapshot = cursor_buffer.read(cx).snapshot();
10148                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10149                    let cursor_offset_in_rename_range =
10150                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10151                    let cursor_offset_in_rename_range_end =
10152                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10153
10154                    this.take_rename(false, cx);
10155                    let buffer = this.buffer.read(cx).read(cx);
10156                    let cursor_offset = selection.head().to_offset(&buffer);
10157                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10158                    let rename_end = rename_start + rename_buffer_range.len();
10159                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10160                    let mut old_highlight_id = None;
10161                    let old_name: Arc<str> = buffer
10162                        .chunks(rename_start..rename_end, true)
10163                        .map(|chunk| {
10164                            if old_highlight_id.is_none() {
10165                                old_highlight_id = chunk.syntax_highlight_id;
10166                            }
10167                            chunk.text
10168                        })
10169                        .collect::<String>()
10170                        .into();
10171
10172                    drop(buffer);
10173
10174                    // Position the selection in the rename editor so that it matches the current selection.
10175                    this.show_local_selections = false;
10176                    let rename_editor = cx.new_view(|cx| {
10177                        let mut editor = Editor::single_line(cx);
10178                        editor.buffer.update(cx, |buffer, cx| {
10179                            buffer.edit([(0..0, old_name.clone())], None, cx)
10180                        });
10181                        let rename_selection_range = match cursor_offset_in_rename_range
10182                            .cmp(&cursor_offset_in_rename_range_end)
10183                        {
10184                            Ordering::Equal => {
10185                                editor.select_all(&SelectAll, cx);
10186                                return editor;
10187                            }
10188                            Ordering::Less => {
10189                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10190                            }
10191                            Ordering::Greater => {
10192                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10193                            }
10194                        };
10195                        if rename_selection_range.end > old_name.len() {
10196                            editor.select_all(&SelectAll, cx);
10197                        } else {
10198                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10199                                s.select_ranges([rename_selection_range]);
10200                            });
10201                        }
10202                        editor
10203                    });
10204                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10205                        if e == &EditorEvent::Focused {
10206                            cx.emit(EditorEvent::FocusedIn)
10207                        }
10208                    })
10209                    .detach();
10210
10211                    let write_highlights =
10212                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10213                    let read_highlights =
10214                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10215                    let ranges = write_highlights
10216                        .iter()
10217                        .flat_map(|(_, ranges)| ranges.iter())
10218                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10219                        .cloned()
10220                        .collect();
10221
10222                    this.highlight_text::<Rename>(
10223                        ranges,
10224                        HighlightStyle {
10225                            fade_out: Some(0.6),
10226                            ..Default::default()
10227                        },
10228                        cx,
10229                    );
10230                    let rename_focus_handle = rename_editor.focus_handle(cx);
10231                    cx.focus(&rename_focus_handle);
10232                    let block_id = this.insert_blocks(
10233                        [BlockProperties {
10234                            style: BlockStyle::Flex,
10235                            position: range.start,
10236                            height: 1,
10237                            render: Box::new({
10238                                let rename_editor = rename_editor.clone();
10239                                move |cx: &mut BlockContext| {
10240                                    let mut text_style = cx.editor_style.text.clone();
10241                                    if let Some(highlight_style) = old_highlight_id
10242                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10243                                    {
10244                                        text_style = text_style.highlight(highlight_style);
10245                                    }
10246                                    div()
10247                                        .pl(cx.anchor_x)
10248                                        .child(EditorElement::new(
10249                                            &rename_editor,
10250                                            EditorStyle {
10251                                                background: cx.theme().system().transparent,
10252                                                local_player: cx.editor_style.local_player,
10253                                                text: text_style,
10254                                                scrollbar_width: cx.editor_style.scrollbar_width,
10255                                                syntax: cx.editor_style.syntax.clone(),
10256                                                status: cx.editor_style.status.clone(),
10257                                                inlay_hints_style: HighlightStyle {
10258                                                    font_weight: Some(FontWeight::BOLD),
10259                                                    ..make_inlay_hints_style(cx)
10260                                                },
10261                                                suggestions_style: HighlightStyle {
10262                                                    color: Some(cx.theme().status().predictive),
10263                                                    ..HighlightStyle::default()
10264                                                },
10265                                                ..EditorStyle::default()
10266                                            },
10267                                        ))
10268                                        .into_any_element()
10269                                }
10270                            }),
10271                            disposition: BlockDisposition::Below,
10272                            priority: 0,
10273                        }],
10274                        Some(Autoscroll::fit()),
10275                        cx,
10276                    )[0];
10277                    this.pending_rename = Some(RenameState {
10278                        range,
10279                        old_name,
10280                        editor: rename_editor,
10281                        block_id,
10282                    });
10283                })?;
10284            }
10285
10286            Ok(())
10287        }))
10288    }
10289
10290    pub fn confirm_rename(
10291        &mut self,
10292        _: &ConfirmRename,
10293        cx: &mut ViewContext<Self>,
10294    ) -> Option<Task<Result<()>>> {
10295        let rename = self.take_rename(false, cx)?;
10296        let workspace = self.workspace()?.downgrade();
10297        let (buffer, start) = self
10298            .buffer
10299            .read(cx)
10300            .text_anchor_for_position(rename.range.start, cx)?;
10301        let (end_buffer, _) = self
10302            .buffer
10303            .read(cx)
10304            .text_anchor_for_position(rename.range.end, cx)?;
10305        if buffer != end_buffer {
10306            return None;
10307        }
10308
10309        let old_name = rename.old_name;
10310        let new_name = rename.editor.read(cx).text(cx);
10311
10312        let rename = self.semantics_provider.as_ref()?.perform_rename(
10313            &buffer,
10314            start,
10315            new_name.clone(),
10316            cx,
10317        )?;
10318
10319        Some(cx.spawn(|editor, mut cx| async move {
10320            let project_transaction = rename.await?;
10321            Self::open_project_transaction(
10322                &editor,
10323                workspace,
10324                project_transaction,
10325                format!("Rename: {}{}", old_name, new_name),
10326                cx.clone(),
10327            )
10328            .await?;
10329
10330            editor.update(&mut cx, |editor, cx| {
10331                editor.refresh_document_highlights(cx);
10332            })?;
10333            Ok(())
10334        }))
10335    }
10336
10337    fn take_rename(
10338        &mut self,
10339        moving_cursor: bool,
10340        cx: &mut ViewContext<Self>,
10341    ) -> Option<RenameState> {
10342        let rename = self.pending_rename.take()?;
10343        if rename.editor.focus_handle(cx).is_focused(cx) {
10344            cx.focus(&self.focus_handle);
10345        }
10346
10347        self.remove_blocks(
10348            [rename.block_id].into_iter().collect(),
10349            Some(Autoscroll::fit()),
10350            cx,
10351        );
10352        self.clear_highlights::<Rename>(cx);
10353        self.show_local_selections = true;
10354
10355        if moving_cursor {
10356            let rename_editor = rename.editor.read(cx);
10357            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10358
10359            // Update the selection to match the position of the selection inside
10360            // the rename editor.
10361            let snapshot = self.buffer.read(cx).read(cx);
10362            let rename_range = rename.range.to_offset(&snapshot);
10363            let cursor_in_editor = snapshot
10364                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10365                .min(rename_range.end);
10366            drop(snapshot);
10367
10368            self.change_selections(None, cx, |s| {
10369                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10370            });
10371        } else {
10372            self.refresh_document_highlights(cx);
10373        }
10374
10375        Some(rename)
10376    }
10377
10378    pub fn pending_rename(&self) -> Option<&RenameState> {
10379        self.pending_rename.as_ref()
10380    }
10381
10382    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10383        let project = match &self.project {
10384            Some(project) => project.clone(),
10385            None => return None,
10386        };
10387
10388        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10389    }
10390
10391    fn format_selections(
10392        &mut self,
10393        _: &FormatSelections,
10394        cx: &mut ViewContext<Self>,
10395    ) -> Option<Task<Result<()>>> {
10396        let project = match &self.project {
10397            Some(project) => project.clone(),
10398            None => return None,
10399        };
10400
10401        let selections = self
10402            .selections
10403            .all_adjusted(cx)
10404            .into_iter()
10405            .filter(|s| !s.is_empty())
10406            .collect_vec();
10407
10408        Some(self.perform_format(
10409            project,
10410            FormatTrigger::Manual,
10411            FormatTarget::Ranges(selections),
10412            cx,
10413        ))
10414    }
10415
10416    fn perform_format(
10417        &mut self,
10418        project: Model<Project>,
10419        trigger: FormatTrigger,
10420        target: FormatTarget,
10421        cx: &mut ViewContext<Self>,
10422    ) -> Task<Result<()>> {
10423        let buffer = self.buffer().clone();
10424        let mut buffers = buffer.read(cx).all_buffers();
10425        if trigger == FormatTrigger::Save {
10426            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10427        }
10428
10429        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10430        let format = project.update(cx, |project, cx| {
10431            project.format(buffers, true, trigger, target, cx)
10432        });
10433
10434        cx.spawn(|_, mut cx| async move {
10435            let transaction = futures::select_biased! {
10436                () = timeout => {
10437                    log::warn!("timed out waiting for formatting");
10438                    None
10439                }
10440                transaction = format.log_err().fuse() => transaction,
10441            };
10442
10443            buffer
10444                .update(&mut cx, |buffer, cx| {
10445                    if let Some(transaction) = transaction {
10446                        if !buffer.is_singleton() {
10447                            buffer.push_transaction(&transaction.0, cx);
10448                        }
10449                    }
10450
10451                    cx.notify();
10452                })
10453                .ok();
10454
10455            Ok(())
10456        })
10457    }
10458
10459    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10460        if let Some(project) = self.project.clone() {
10461            self.buffer.update(cx, |multi_buffer, cx| {
10462                project.update(cx, |project, cx| {
10463                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10464                });
10465            })
10466        }
10467    }
10468
10469    fn cancel_language_server_work(
10470        &mut self,
10471        _: &CancelLanguageServerWork,
10472        cx: &mut ViewContext<Self>,
10473    ) {
10474        if let Some(project) = self.project.clone() {
10475            self.buffer.update(cx, |multi_buffer, cx| {
10476                project.update(cx, |project, cx| {
10477                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10478                });
10479            })
10480        }
10481    }
10482
10483    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10484        cx.show_character_palette();
10485    }
10486
10487    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10488        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10489            let buffer = self.buffer.read(cx).snapshot(cx);
10490            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10491            let is_valid = buffer
10492                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10493                .any(|entry| {
10494                    entry.diagnostic.is_primary
10495                        && !entry.range.is_empty()
10496                        && entry.range.start == primary_range_start
10497                        && entry.diagnostic.message == active_diagnostics.primary_message
10498                });
10499
10500            if is_valid != active_diagnostics.is_valid {
10501                active_diagnostics.is_valid = is_valid;
10502                let mut new_styles = HashMap::default();
10503                for (block_id, diagnostic) in &active_diagnostics.blocks {
10504                    new_styles.insert(
10505                        *block_id,
10506                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10507                    );
10508                }
10509                self.display_map.update(cx, |display_map, _cx| {
10510                    display_map.replace_blocks(new_styles)
10511                });
10512            }
10513        }
10514    }
10515
10516    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10517        self.dismiss_diagnostics(cx);
10518        let snapshot = self.snapshot(cx);
10519        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10520            let buffer = self.buffer.read(cx).snapshot(cx);
10521
10522            let mut primary_range = None;
10523            let mut primary_message = None;
10524            let mut group_end = Point::zero();
10525            let diagnostic_group = buffer
10526                .diagnostic_group::<MultiBufferPoint>(group_id)
10527                .filter_map(|entry| {
10528                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10529                        && (entry.range.start.row == entry.range.end.row
10530                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10531                    {
10532                        return None;
10533                    }
10534                    if entry.range.end > group_end {
10535                        group_end = entry.range.end;
10536                    }
10537                    if entry.diagnostic.is_primary {
10538                        primary_range = Some(entry.range.clone());
10539                        primary_message = Some(entry.diagnostic.message.clone());
10540                    }
10541                    Some(entry)
10542                })
10543                .collect::<Vec<_>>();
10544            let primary_range = primary_range?;
10545            let primary_message = primary_message?;
10546            let primary_range =
10547                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10548
10549            let blocks = display_map
10550                .insert_blocks(
10551                    diagnostic_group.iter().map(|entry| {
10552                        let diagnostic = entry.diagnostic.clone();
10553                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10554                        BlockProperties {
10555                            style: BlockStyle::Fixed,
10556                            position: buffer.anchor_after(entry.range.start),
10557                            height: message_height,
10558                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10559                            disposition: BlockDisposition::Below,
10560                            priority: 0,
10561                        }
10562                    }),
10563                    cx,
10564                )
10565                .into_iter()
10566                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10567                .collect();
10568
10569            Some(ActiveDiagnosticGroup {
10570                primary_range,
10571                primary_message,
10572                group_id,
10573                blocks,
10574                is_valid: true,
10575            })
10576        });
10577        self.active_diagnostics.is_some()
10578    }
10579
10580    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10581        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10582            self.display_map.update(cx, |display_map, cx| {
10583                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10584            });
10585            cx.notify();
10586        }
10587    }
10588
10589    pub fn set_selections_from_remote(
10590        &mut self,
10591        selections: Vec<Selection<Anchor>>,
10592        pending_selection: Option<Selection<Anchor>>,
10593        cx: &mut ViewContext<Self>,
10594    ) {
10595        let old_cursor_position = self.selections.newest_anchor().head();
10596        self.selections.change_with(cx, |s| {
10597            s.select_anchors(selections);
10598            if let Some(pending_selection) = pending_selection {
10599                s.set_pending(pending_selection, SelectMode::Character);
10600            } else {
10601                s.clear_pending();
10602            }
10603        });
10604        self.selections_did_change(false, &old_cursor_position, true, cx);
10605    }
10606
10607    fn push_to_selection_history(&mut self) {
10608        self.selection_history.push(SelectionHistoryEntry {
10609            selections: self.selections.disjoint_anchors(),
10610            select_next_state: self.select_next_state.clone(),
10611            select_prev_state: self.select_prev_state.clone(),
10612            add_selections_state: self.add_selections_state.clone(),
10613        });
10614    }
10615
10616    pub fn transact(
10617        &mut self,
10618        cx: &mut ViewContext<Self>,
10619        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10620    ) -> Option<TransactionId> {
10621        self.start_transaction_at(Instant::now(), cx);
10622        update(self, cx);
10623        self.end_transaction_at(Instant::now(), cx)
10624    }
10625
10626    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10627        self.end_selection(cx);
10628        if let Some(tx_id) = self
10629            .buffer
10630            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10631        {
10632            self.selection_history
10633                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10634            cx.emit(EditorEvent::TransactionBegun {
10635                transaction_id: tx_id,
10636            })
10637        }
10638    }
10639
10640    fn end_transaction_at(
10641        &mut self,
10642        now: Instant,
10643        cx: &mut ViewContext<Self>,
10644    ) -> Option<TransactionId> {
10645        if let Some(transaction_id) = self
10646            .buffer
10647            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10648        {
10649            if let Some((_, end_selections)) =
10650                self.selection_history.transaction_mut(transaction_id)
10651            {
10652                *end_selections = Some(self.selections.disjoint_anchors());
10653            } else {
10654                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10655            }
10656
10657            cx.emit(EditorEvent::Edited { transaction_id });
10658            Some(transaction_id)
10659        } else {
10660            None
10661        }
10662    }
10663
10664    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10665        let selection = self.selections.newest::<Point>(cx);
10666
10667        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10668        let range = if selection.is_empty() {
10669            let point = selection.head().to_display_point(&display_map);
10670            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10671            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10672                .to_point(&display_map);
10673            start..end
10674        } else {
10675            selection.range()
10676        };
10677        if display_map.folds_in_range(range).next().is_some() {
10678            self.unfold_lines(&Default::default(), cx)
10679        } else {
10680            self.fold(&Default::default(), cx)
10681        }
10682    }
10683
10684    pub fn toggle_fold_recursive(
10685        &mut self,
10686        _: &actions::ToggleFoldRecursive,
10687        cx: &mut ViewContext<Self>,
10688    ) {
10689        let selection = self.selections.newest::<Point>(cx);
10690
10691        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10692        let range = if selection.is_empty() {
10693            let point = selection.head().to_display_point(&display_map);
10694            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10695            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10696                .to_point(&display_map);
10697            start..end
10698        } else {
10699            selection.range()
10700        };
10701        if display_map.folds_in_range(range).next().is_some() {
10702            self.unfold_recursive(&Default::default(), cx)
10703        } else {
10704            self.fold_recursive(&Default::default(), cx)
10705        }
10706    }
10707
10708    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10709        let mut fold_ranges = Vec::new();
10710        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10711        let selections = self.selections.all_adjusted(cx);
10712
10713        for selection in selections {
10714            let range = selection.range().sorted();
10715            let buffer_start_row = range.start.row;
10716
10717            if range.start.row != range.end.row {
10718                let mut found = false;
10719                let mut row = range.start.row;
10720                while row <= range.end.row {
10721                    if let Some((foldable_range, fold_text)) =
10722                        { display_map.foldable_range(MultiBufferRow(row)) }
10723                    {
10724                        found = true;
10725                        row = foldable_range.end.row + 1;
10726                        fold_ranges.push((foldable_range, fold_text));
10727                    } else {
10728                        row += 1
10729                    }
10730                }
10731                if found {
10732                    continue;
10733                }
10734            }
10735
10736            for row in (0..=range.start.row).rev() {
10737                if let Some((foldable_range, fold_text)) =
10738                    display_map.foldable_range(MultiBufferRow(row))
10739                {
10740                    if foldable_range.end.row >= buffer_start_row {
10741                        fold_ranges.push((foldable_range, fold_text));
10742                        if row <= range.start.row {
10743                            break;
10744                        }
10745                    }
10746                }
10747            }
10748        }
10749
10750        self.fold_ranges(fold_ranges, true, cx);
10751    }
10752
10753    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10754        let mut fold_ranges = Vec::new();
10755        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10756
10757        for row in 0..display_map.max_buffer_row().0 {
10758            if let Some((foldable_range, fold_text)) =
10759                display_map.foldable_range(MultiBufferRow(row))
10760            {
10761                fold_ranges.push((foldable_range, fold_text));
10762            }
10763        }
10764
10765        self.fold_ranges(fold_ranges, true, cx);
10766    }
10767
10768    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10769        let mut fold_ranges = Vec::new();
10770        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10771        let selections = self.selections.all_adjusted(cx);
10772
10773        for selection in selections {
10774            let range = selection.range().sorted();
10775            let buffer_start_row = range.start.row;
10776
10777            if range.start.row != range.end.row {
10778                let mut found = false;
10779                for row in range.start.row..=range.end.row {
10780                    if let Some((foldable_range, fold_text)) =
10781                        { display_map.foldable_range(MultiBufferRow(row)) }
10782                    {
10783                        found = true;
10784                        fold_ranges.push((foldable_range, fold_text));
10785                    }
10786                }
10787                if found {
10788                    continue;
10789                }
10790            }
10791
10792            for row in (0..=range.start.row).rev() {
10793                if let Some((foldable_range, fold_text)) =
10794                    display_map.foldable_range(MultiBufferRow(row))
10795                {
10796                    if foldable_range.end.row >= buffer_start_row {
10797                        fold_ranges.push((foldable_range, fold_text));
10798                    } else {
10799                        break;
10800                    }
10801                }
10802            }
10803        }
10804
10805        self.fold_ranges(fold_ranges, true, cx);
10806    }
10807
10808    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10809        let buffer_row = fold_at.buffer_row;
10810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10811
10812        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10813            let autoscroll = self
10814                .selections
10815                .all::<Point>(cx)
10816                .iter()
10817                .any(|selection| fold_range.overlaps(&selection.range()));
10818
10819            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10820        }
10821    }
10822
10823    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10824        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10825        let buffer = &display_map.buffer_snapshot;
10826        let selections = self.selections.all::<Point>(cx);
10827        let ranges = selections
10828            .iter()
10829            .map(|s| {
10830                let range = s.display_range(&display_map).sorted();
10831                let mut start = range.start.to_point(&display_map);
10832                let mut end = range.end.to_point(&display_map);
10833                start.column = 0;
10834                end.column = buffer.line_len(MultiBufferRow(end.row));
10835                start..end
10836            })
10837            .collect::<Vec<_>>();
10838
10839        self.unfold_ranges(ranges, true, true, cx);
10840    }
10841
10842    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10843        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10844        let selections = self.selections.all::<Point>(cx);
10845        let ranges = selections
10846            .iter()
10847            .map(|s| {
10848                let mut range = s.display_range(&display_map).sorted();
10849                *range.start.column_mut() = 0;
10850                *range.end.column_mut() = display_map.line_len(range.end.row());
10851                let start = range.start.to_point(&display_map);
10852                let end = range.end.to_point(&display_map);
10853                start..end
10854            })
10855            .collect::<Vec<_>>();
10856
10857        self.unfold_ranges(ranges, true, true, cx);
10858    }
10859
10860    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10861        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10862
10863        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10864            ..Point::new(
10865                unfold_at.buffer_row.0,
10866                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10867            );
10868
10869        let autoscroll = self
10870            .selections
10871            .all::<Point>(cx)
10872            .iter()
10873            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10874
10875        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10876    }
10877
10878    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10880        self.unfold_ranges(
10881            [Point::zero()..display_map.max_point().to_point(&display_map)],
10882            true,
10883            true,
10884            cx,
10885        );
10886    }
10887
10888    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10889        let selections = self.selections.all::<Point>(cx);
10890        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10891        let line_mode = self.selections.line_mode;
10892        let ranges = selections.into_iter().map(|s| {
10893            if line_mode {
10894                let start = Point::new(s.start.row, 0);
10895                let end = Point::new(
10896                    s.end.row,
10897                    display_map
10898                        .buffer_snapshot
10899                        .line_len(MultiBufferRow(s.end.row)),
10900                );
10901                (start..end, display_map.fold_placeholder.clone())
10902            } else {
10903                (s.start..s.end, display_map.fold_placeholder.clone())
10904            }
10905        });
10906        self.fold_ranges(ranges, true, cx);
10907    }
10908
10909    pub fn fold_ranges<T: ToOffset + Clone>(
10910        &mut self,
10911        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10912        auto_scroll: bool,
10913        cx: &mut ViewContext<Self>,
10914    ) {
10915        let mut fold_ranges = Vec::new();
10916        let mut buffers_affected = HashMap::default();
10917        let multi_buffer = self.buffer().read(cx);
10918        for (fold_range, fold_text) in ranges {
10919            if let Some((_, buffer, _)) =
10920                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10921            {
10922                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10923            };
10924            fold_ranges.push((fold_range, fold_text));
10925        }
10926
10927        let mut ranges = fold_ranges.into_iter().peekable();
10928        if ranges.peek().is_some() {
10929            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10930
10931            if auto_scroll {
10932                self.request_autoscroll(Autoscroll::fit(), cx);
10933            }
10934
10935            for buffer in buffers_affected.into_values() {
10936                self.sync_expanded_diff_hunks(buffer, cx);
10937            }
10938
10939            cx.notify();
10940
10941            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10942                // Clear diagnostics block when folding a range that contains it.
10943                let snapshot = self.snapshot(cx);
10944                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10945                    drop(snapshot);
10946                    self.active_diagnostics = Some(active_diagnostics);
10947                    self.dismiss_diagnostics(cx);
10948                } else {
10949                    self.active_diagnostics = Some(active_diagnostics);
10950                }
10951            }
10952
10953            self.scrollbar_marker_state.dirty = true;
10954        }
10955    }
10956
10957    pub fn unfold_ranges<T: ToOffset + Clone>(
10958        &mut self,
10959        ranges: impl IntoIterator<Item = Range<T>>,
10960        inclusive: bool,
10961        auto_scroll: bool,
10962        cx: &mut ViewContext<Self>,
10963    ) {
10964        let mut unfold_ranges = Vec::new();
10965        let mut buffers_affected = HashMap::default();
10966        let multi_buffer = self.buffer().read(cx);
10967        for range in ranges {
10968            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10969                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10970            };
10971            unfold_ranges.push(range);
10972        }
10973
10974        let mut ranges = unfold_ranges.into_iter().peekable();
10975        if ranges.peek().is_some() {
10976            self.display_map
10977                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10978            if auto_scroll {
10979                self.request_autoscroll(Autoscroll::fit(), cx);
10980            }
10981
10982            for buffer in buffers_affected.into_values() {
10983                self.sync_expanded_diff_hunks(buffer, cx);
10984            }
10985
10986            cx.notify();
10987            self.scrollbar_marker_state.dirty = true;
10988            self.active_indent_guides_state.dirty = true;
10989        }
10990    }
10991
10992    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10993        self.display_map.read(cx).fold_placeholder.clone()
10994    }
10995
10996    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10997        if hovered != self.gutter_hovered {
10998            self.gutter_hovered = hovered;
10999            cx.notify();
11000        }
11001    }
11002
11003    pub fn insert_blocks(
11004        &mut self,
11005        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11006        autoscroll: Option<Autoscroll>,
11007        cx: &mut ViewContext<Self>,
11008    ) -> Vec<CustomBlockId> {
11009        let blocks = self
11010            .display_map
11011            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11012        if let Some(autoscroll) = autoscroll {
11013            self.request_autoscroll(autoscroll, cx);
11014        }
11015        cx.notify();
11016        blocks
11017    }
11018
11019    pub fn resize_blocks(
11020        &mut self,
11021        heights: HashMap<CustomBlockId, u32>,
11022        autoscroll: Option<Autoscroll>,
11023        cx: &mut ViewContext<Self>,
11024    ) {
11025        self.display_map
11026            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11027        if let Some(autoscroll) = autoscroll {
11028            self.request_autoscroll(autoscroll, cx);
11029        }
11030        cx.notify();
11031    }
11032
11033    pub fn replace_blocks(
11034        &mut self,
11035        renderers: HashMap<CustomBlockId, RenderBlock>,
11036        autoscroll: Option<Autoscroll>,
11037        cx: &mut ViewContext<Self>,
11038    ) {
11039        self.display_map
11040            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11041        if let Some(autoscroll) = autoscroll {
11042            self.request_autoscroll(autoscroll, cx);
11043        }
11044        cx.notify();
11045    }
11046
11047    pub fn remove_blocks(
11048        &mut self,
11049        block_ids: HashSet<CustomBlockId>,
11050        autoscroll: Option<Autoscroll>,
11051        cx: &mut ViewContext<Self>,
11052    ) {
11053        self.display_map.update(cx, |display_map, cx| {
11054            display_map.remove_blocks(block_ids, cx)
11055        });
11056        if let Some(autoscroll) = autoscroll {
11057            self.request_autoscroll(autoscroll, cx);
11058        }
11059        cx.notify();
11060    }
11061
11062    pub fn row_for_block(
11063        &self,
11064        block_id: CustomBlockId,
11065        cx: &mut ViewContext<Self>,
11066    ) -> Option<DisplayRow> {
11067        self.display_map
11068            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11069    }
11070
11071    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11072        self.focused_block = Some(focused_block);
11073    }
11074
11075    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11076        self.focused_block.take()
11077    }
11078
11079    pub fn insert_creases(
11080        &mut self,
11081        creases: impl IntoIterator<Item = Crease>,
11082        cx: &mut ViewContext<Self>,
11083    ) -> Vec<CreaseId> {
11084        self.display_map
11085            .update(cx, |map, cx| map.insert_creases(creases, cx))
11086    }
11087
11088    pub fn remove_creases(
11089        &mut self,
11090        ids: impl IntoIterator<Item = CreaseId>,
11091        cx: &mut ViewContext<Self>,
11092    ) {
11093        self.display_map
11094            .update(cx, |map, cx| map.remove_creases(ids, cx));
11095    }
11096
11097    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11098        self.display_map
11099            .update(cx, |map, cx| map.snapshot(cx))
11100            .longest_row()
11101    }
11102
11103    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11104        self.display_map
11105            .update(cx, |map, cx| map.snapshot(cx))
11106            .max_point()
11107    }
11108
11109    pub fn text(&self, cx: &AppContext) -> String {
11110        self.buffer.read(cx).read(cx).text()
11111    }
11112
11113    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11114        let text = self.text(cx);
11115        let text = text.trim();
11116
11117        if text.is_empty() {
11118            return None;
11119        }
11120
11121        Some(text.to_string())
11122    }
11123
11124    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11125        self.transact(cx, |this, cx| {
11126            this.buffer
11127                .read(cx)
11128                .as_singleton()
11129                .expect("you can only call set_text on editors for singleton buffers")
11130                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11131        });
11132    }
11133
11134    pub fn display_text(&self, cx: &mut AppContext) -> String {
11135        self.display_map
11136            .update(cx, |map, cx| map.snapshot(cx))
11137            .text()
11138    }
11139
11140    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11141        let mut wrap_guides = smallvec::smallvec![];
11142
11143        if self.show_wrap_guides == Some(false) {
11144            return wrap_guides;
11145        }
11146
11147        let settings = self.buffer.read(cx).settings_at(0, cx);
11148        if settings.show_wrap_guides {
11149            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11150                wrap_guides.push((soft_wrap as usize, true));
11151            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11152                wrap_guides.push((soft_wrap as usize, true));
11153            }
11154            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11155        }
11156
11157        wrap_guides
11158    }
11159
11160    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11161        let settings = self.buffer.read(cx).settings_at(0, cx);
11162        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11163        match mode {
11164            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11165                SoftWrap::None
11166            }
11167            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11168            language_settings::SoftWrap::PreferredLineLength => {
11169                SoftWrap::Column(settings.preferred_line_length)
11170            }
11171            language_settings::SoftWrap::Bounded => {
11172                SoftWrap::Bounded(settings.preferred_line_length)
11173            }
11174        }
11175    }
11176
11177    pub fn set_soft_wrap_mode(
11178        &mut self,
11179        mode: language_settings::SoftWrap,
11180        cx: &mut ViewContext<Self>,
11181    ) {
11182        self.soft_wrap_mode_override = Some(mode);
11183        cx.notify();
11184    }
11185
11186    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11187        let rem_size = cx.rem_size();
11188        self.display_map.update(cx, |map, cx| {
11189            map.set_font(
11190                style.text.font(),
11191                style.text.font_size.to_pixels(rem_size),
11192                cx,
11193            )
11194        });
11195        self.style = Some(style);
11196    }
11197
11198    pub fn style(&self) -> Option<&EditorStyle> {
11199        self.style.as_ref()
11200    }
11201
11202    // Called by the element. This method is not designed to be called outside of the editor
11203    // element's layout code because it does not notify when rewrapping is computed synchronously.
11204    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11205        self.display_map
11206            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11207    }
11208
11209    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11210        if self.soft_wrap_mode_override.is_some() {
11211            self.soft_wrap_mode_override.take();
11212        } else {
11213            let soft_wrap = match self.soft_wrap_mode(cx) {
11214                SoftWrap::GitDiff => return,
11215                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11216                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11217                    language_settings::SoftWrap::None
11218                }
11219            };
11220            self.soft_wrap_mode_override = Some(soft_wrap);
11221        }
11222        cx.notify();
11223    }
11224
11225    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11226        let Some(workspace) = self.workspace() else {
11227            return;
11228        };
11229        let fs = workspace.read(cx).app_state().fs.clone();
11230        let current_show = TabBarSettings::get_global(cx).show;
11231        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11232            setting.show = Some(!current_show);
11233        });
11234    }
11235
11236    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11237        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11238            self.buffer
11239                .read(cx)
11240                .settings_at(0, cx)
11241                .indent_guides
11242                .enabled
11243        });
11244        self.show_indent_guides = Some(!currently_enabled);
11245        cx.notify();
11246    }
11247
11248    fn should_show_indent_guides(&self) -> Option<bool> {
11249        self.show_indent_guides
11250    }
11251
11252    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11253        let mut editor_settings = EditorSettings::get_global(cx).clone();
11254        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11255        EditorSettings::override_global(editor_settings, cx);
11256    }
11257
11258    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11259        self.use_relative_line_numbers
11260            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11261    }
11262
11263    pub fn toggle_relative_line_numbers(
11264        &mut self,
11265        _: &ToggleRelativeLineNumbers,
11266        cx: &mut ViewContext<Self>,
11267    ) {
11268        let is_relative = self.should_use_relative_line_numbers(cx);
11269        self.set_relative_line_number(Some(!is_relative), cx)
11270    }
11271
11272    pub fn set_relative_line_number(
11273        &mut self,
11274        is_relative: Option<bool>,
11275        cx: &mut ViewContext<Self>,
11276    ) {
11277        self.use_relative_line_numbers = is_relative;
11278        cx.notify();
11279    }
11280
11281    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11282        self.show_gutter = show_gutter;
11283        cx.notify();
11284    }
11285
11286    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11287        self.show_line_numbers = Some(show_line_numbers);
11288        cx.notify();
11289    }
11290
11291    pub fn set_show_git_diff_gutter(
11292        &mut self,
11293        show_git_diff_gutter: bool,
11294        cx: &mut ViewContext<Self>,
11295    ) {
11296        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11297        cx.notify();
11298    }
11299
11300    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11301        self.show_code_actions = Some(show_code_actions);
11302        cx.notify();
11303    }
11304
11305    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11306        self.show_runnables = Some(show_runnables);
11307        cx.notify();
11308    }
11309
11310    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11311        if self.display_map.read(cx).masked != masked {
11312            self.display_map.update(cx, |map, _| map.masked = masked);
11313        }
11314        cx.notify()
11315    }
11316
11317    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11318        self.show_wrap_guides = Some(show_wrap_guides);
11319        cx.notify();
11320    }
11321
11322    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11323        self.show_indent_guides = Some(show_indent_guides);
11324        cx.notify();
11325    }
11326
11327    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11328        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11329            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11330                if let Some(dir) = file.abs_path(cx).parent() {
11331                    return Some(dir.to_owned());
11332                }
11333            }
11334
11335            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11336                return Some(project_path.path.to_path_buf());
11337            }
11338        }
11339
11340        None
11341    }
11342
11343    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11344        self.active_excerpt(cx)?
11345            .1
11346            .read(cx)
11347            .file()
11348            .and_then(|f| f.as_local())
11349    }
11350
11351    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11352        if let Some(target) = self.target_file(cx) {
11353            cx.reveal_path(&target.abs_path(cx));
11354        }
11355    }
11356
11357    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11358        if let Some(file) = self.target_file(cx) {
11359            if let Some(path) = file.abs_path(cx).to_str() {
11360                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11361            }
11362        }
11363    }
11364
11365    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11366        if let Some(file) = self.target_file(cx) {
11367            if let Some(path) = file.path().to_str() {
11368                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11369            }
11370        }
11371    }
11372
11373    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11374        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11375
11376        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11377            self.start_git_blame(true, cx);
11378        }
11379
11380        cx.notify();
11381    }
11382
11383    pub fn toggle_git_blame_inline(
11384        &mut self,
11385        _: &ToggleGitBlameInline,
11386        cx: &mut ViewContext<Self>,
11387    ) {
11388        self.toggle_git_blame_inline_internal(true, cx);
11389        cx.notify();
11390    }
11391
11392    pub fn git_blame_inline_enabled(&self) -> bool {
11393        self.git_blame_inline_enabled
11394    }
11395
11396    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11397        self.show_selection_menu = self
11398            .show_selection_menu
11399            .map(|show_selections_menu| !show_selections_menu)
11400            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11401
11402        cx.notify();
11403    }
11404
11405    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11406        self.show_selection_menu
11407            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11408    }
11409
11410    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11411        if let Some(project) = self.project.as_ref() {
11412            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11413                return;
11414            };
11415
11416            if buffer.read(cx).file().is_none() {
11417                return;
11418            }
11419
11420            let focused = self.focus_handle(cx).contains_focused(cx);
11421
11422            let project = project.clone();
11423            let blame =
11424                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11425            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11426            self.blame = Some(blame);
11427        }
11428    }
11429
11430    fn toggle_git_blame_inline_internal(
11431        &mut self,
11432        user_triggered: bool,
11433        cx: &mut ViewContext<Self>,
11434    ) {
11435        if self.git_blame_inline_enabled {
11436            self.git_blame_inline_enabled = false;
11437            self.show_git_blame_inline = false;
11438            self.show_git_blame_inline_delay_task.take();
11439        } else {
11440            self.git_blame_inline_enabled = true;
11441            self.start_git_blame_inline(user_triggered, cx);
11442        }
11443
11444        cx.notify();
11445    }
11446
11447    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11448        self.start_git_blame(user_triggered, cx);
11449
11450        if ProjectSettings::get_global(cx)
11451            .git
11452            .inline_blame_delay()
11453            .is_some()
11454        {
11455            self.start_inline_blame_timer(cx);
11456        } else {
11457            self.show_git_blame_inline = true
11458        }
11459    }
11460
11461    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11462        self.blame.as_ref()
11463    }
11464
11465    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11466        self.show_git_blame_gutter && self.has_blame_entries(cx)
11467    }
11468
11469    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11470        self.show_git_blame_inline
11471            && self.focus_handle.is_focused(cx)
11472            && !self.newest_selection_head_on_empty_line(cx)
11473            && self.has_blame_entries(cx)
11474    }
11475
11476    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11477        self.blame()
11478            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11479    }
11480
11481    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11482        let cursor_anchor = self.selections.newest_anchor().head();
11483
11484        let snapshot = self.buffer.read(cx).snapshot(cx);
11485        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11486
11487        snapshot.line_len(buffer_row) == 0
11488    }
11489
11490    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11491        let buffer_and_selection = maybe!({
11492            let selection = self.selections.newest::<Point>(cx);
11493            let selection_range = selection.range();
11494
11495            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11496                (buffer, selection_range.start.row..selection_range.end.row)
11497            } else {
11498                let buffer_ranges = self
11499                    .buffer()
11500                    .read(cx)
11501                    .range_to_buffer_ranges(selection_range, cx);
11502
11503                let (buffer, range, _) = if selection.reversed {
11504                    buffer_ranges.first()
11505                } else {
11506                    buffer_ranges.last()
11507                }?;
11508
11509                let snapshot = buffer.read(cx).snapshot();
11510                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11511                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11512                (buffer.clone(), selection)
11513            };
11514
11515            Some((buffer, selection))
11516        });
11517
11518        let Some((buffer, selection)) = buffer_and_selection else {
11519            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11520        };
11521
11522        let Some(project) = self.project.as_ref() else {
11523            return Task::ready(Err(anyhow!("editor does not have project")));
11524        };
11525
11526        project.update(cx, |project, cx| {
11527            project.get_permalink_to_line(&buffer, selection, cx)
11528        })
11529    }
11530
11531    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11532        let permalink_task = self.get_permalink_to_line(cx);
11533        let workspace = self.workspace();
11534
11535        cx.spawn(|_, mut cx| async move {
11536            match permalink_task.await {
11537                Ok(permalink) => {
11538                    cx.update(|cx| {
11539                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11540                    })
11541                    .ok();
11542                }
11543                Err(err) => {
11544                    let message = format!("Failed to copy permalink: {err}");
11545
11546                    Err::<(), anyhow::Error>(err).log_err();
11547
11548                    if let Some(workspace) = workspace {
11549                        workspace
11550                            .update(&mut cx, |workspace, cx| {
11551                                struct CopyPermalinkToLine;
11552
11553                                workspace.show_toast(
11554                                    Toast::new(
11555                                        NotificationId::unique::<CopyPermalinkToLine>(),
11556                                        message,
11557                                    ),
11558                                    cx,
11559                                )
11560                            })
11561                            .ok();
11562                    }
11563                }
11564            }
11565        })
11566        .detach();
11567    }
11568
11569    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11570        if let Some(file) = self.target_file(cx) {
11571            if let Some(path) = file.path().to_str() {
11572                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11573                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11574            }
11575        }
11576    }
11577
11578    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11579        let permalink_task = self.get_permalink_to_line(cx);
11580        let workspace = self.workspace();
11581
11582        cx.spawn(|_, mut cx| async move {
11583            match permalink_task.await {
11584                Ok(permalink) => {
11585                    cx.update(|cx| {
11586                        cx.open_url(permalink.as_ref());
11587                    })
11588                    .ok();
11589                }
11590                Err(err) => {
11591                    let message = format!("Failed to open permalink: {err}");
11592
11593                    Err::<(), anyhow::Error>(err).log_err();
11594
11595                    if let Some(workspace) = workspace {
11596                        workspace
11597                            .update(&mut cx, |workspace, cx| {
11598                                struct OpenPermalinkToLine;
11599
11600                                workspace.show_toast(
11601                                    Toast::new(
11602                                        NotificationId::unique::<OpenPermalinkToLine>(),
11603                                        message,
11604                                    ),
11605                                    cx,
11606                                )
11607                            })
11608                            .ok();
11609                    }
11610                }
11611            }
11612        })
11613        .detach();
11614    }
11615
11616    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11617    /// last highlight added will be used.
11618    ///
11619    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11620    pub fn highlight_rows<T: 'static>(
11621        &mut self,
11622        range: Range<Anchor>,
11623        color: Hsla,
11624        should_autoscroll: bool,
11625        cx: &mut ViewContext<Self>,
11626    ) {
11627        let snapshot = self.buffer().read(cx).snapshot(cx);
11628        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11629        let ix = row_highlights.binary_search_by(|highlight| {
11630            Ordering::Equal
11631                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11632                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11633        });
11634
11635        if let Err(mut ix) = ix {
11636            let index = post_inc(&mut self.highlight_order);
11637
11638            // If this range intersects with the preceding highlight, then merge it with
11639            // the preceding highlight. Otherwise insert a new highlight.
11640            let mut merged = false;
11641            if ix > 0 {
11642                let prev_highlight = &mut row_highlights[ix - 1];
11643                if prev_highlight
11644                    .range
11645                    .end
11646                    .cmp(&range.start, &snapshot)
11647                    .is_ge()
11648                {
11649                    ix -= 1;
11650                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11651                        prev_highlight.range.end = range.end;
11652                    }
11653                    merged = true;
11654                    prev_highlight.index = index;
11655                    prev_highlight.color = color;
11656                    prev_highlight.should_autoscroll = should_autoscroll;
11657                }
11658            }
11659
11660            if !merged {
11661                row_highlights.insert(
11662                    ix,
11663                    RowHighlight {
11664                        range: range.clone(),
11665                        index,
11666                        color,
11667                        should_autoscroll,
11668                    },
11669                );
11670            }
11671
11672            // If any of the following highlights intersect with this one, merge them.
11673            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11674                let highlight = &row_highlights[ix];
11675                if next_highlight
11676                    .range
11677                    .start
11678                    .cmp(&highlight.range.end, &snapshot)
11679                    .is_le()
11680                {
11681                    if next_highlight
11682                        .range
11683                        .end
11684                        .cmp(&highlight.range.end, &snapshot)
11685                        .is_gt()
11686                    {
11687                        row_highlights[ix].range.end = next_highlight.range.end;
11688                    }
11689                    row_highlights.remove(ix + 1);
11690                } else {
11691                    break;
11692                }
11693            }
11694        }
11695    }
11696
11697    /// Remove any highlighted row ranges of the given type that intersect the
11698    /// given ranges.
11699    pub fn remove_highlighted_rows<T: 'static>(
11700        &mut self,
11701        ranges_to_remove: Vec<Range<Anchor>>,
11702        cx: &mut ViewContext<Self>,
11703    ) {
11704        let snapshot = self.buffer().read(cx).snapshot(cx);
11705        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11706        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11707        row_highlights.retain(|highlight| {
11708            while let Some(range_to_remove) = ranges_to_remove.peek() {
11709                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11710                    Ordering::Less | Ordering::Equal => {
11711                        ranges_to_remove.next();
11712                    }
11713                    Ordering::Greater => {
11714                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11715                            Ordering::Less | Ordering::Equal => {
11716                                return false;
11717                            }
11718                            Ordering::Greater => break,
11719                        }
11720                    }
11721                }
11722            }
11723
11724            true
11725        })
11726    }
11727
11728    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11729    pub fn clear_row_highlights<T: 'static>(&mut self) {
11730        self.highlighted_rows.remove(&TypeId::of::<T>());
11731    }
11732
11733    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11734    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11735        self.highlighted_rows
11736            .get(&TypeId::of::<T>())
11737            .map_or(&[] as &[_], |vec| vec.as_slice())
11738            .iter()
11739            .map(|highlight| (highlight.range.clone(), highlight.color))
11740    }
11741
11742    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11743    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11744    /// Allows to ignore certain kinds of highlights.
11745    pub fn highlighted_display_rows(
11746        &mut self,
11747        cx: &mut WindowContext,
11748    ) -> BTreeMap<DisplayRow, Hsla> {
11749        let snapshot = self.snapshot(cx);
11750        let mut used_highlight_orders = HashMap::default();
11751        self.highlighted_rows
11752            .iter()
11753            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11754            .fold(
11755                BTreeMap::<DisplayRow, Hsla>::new(),
11756                |mut unique_rows, highlight| {
11757                    let start = highlight.range.start.to_display_point(&snapshot);
11758                    let end = highlight.range.end.to_display_point(&snapshot);
11759                    let start_row = start.row().0;
11760                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11761                        && end.column() == 0
11762                    {
11763                        end.row().0.saturating_sub(1)
11764                    } else {
11765                        end.row().0
11766                    };
11767                    for row in start_row..=end_row {
11768                        let used_index =
11769                            used_highlight_orders.entry(row).or_insert(highlight.index);
11770                        if highlight.index >= *used_index {
11771                            *used_index = highlight.index;
11772                            unique_rows.insert(DisplayRow(row), highlight.color);
11773                        }
11774                    }
11775                    unique_rows
11776                },
11777            )
11778    }
11779
11780    pub fn highlighted_display_row_for_autoscroll(
11781        &self,
11782        snapshot: &DisplaySnapshot,
11783    ) -> Option<DisplayRow> {
11784        self.highlighted_rows
11785            .values()
11786            .flat_map(|highlighted_rows| highlighted_rows.iter())
11787            .filter_map(|highlight| {
11788                if highlight.should_autoscroll {
11789                    Some(highlight.range.start.to_display_point(snapshot).row())
11790                } else {
11791                    None
11792                }
11793            })
11794            .min()
11795    }
11796
11797    pub fn set_search_within_ranges(
11798        &mut self,
11799        ranges: &[Range<Anchor>],
11800        cx: &mut ViewContext<Self>,
11801    ) {
11802        self.highlight_background::<SearchWithinRange>(
11803            ranges,
11804            |colors| colors.editor_document_highlight_read_background,
11805            cx,
11806        )
11807    }
11808
11809    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11810        self.breadcrumb_header = Some(new_header);
11811    }
11812
11813    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11814        self.clear_background_highlights::<SearchWithinRange>(cx);
11815    }
11816
11817    pub fn highlight_background<T: 'static>(
11818        &mut self,
11819        ranges: &[Range<Anchor>],
11820        color_fetcher: fn(&ThemeColors) -> Hsla,
11821        cx: &mut ViewContext<Self>,
11822    ) {
11823        self.background_highlights
11824            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11825        self.scrollbar_marker_state.dirty = true;
11826        cx.notify();
11827    }
11828
11829    pub fn clear_background_highlights<T: 'static>(
11830        &mut self,
11831        cx: &mut ViewContext<Self>,
11832    ) -> Option<BackgroundHighlight> {
11833        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11834        if !text_highlights.1.is_empty() {
11835            self.scrollbar_marker_state.dirty = true;
11836            cx.notify();
11837        }
11838        Some(text_highlights)
11839    }
11840
11841    pub fn highlight_gutter<T: 'static>(
11842        &mut self,
11843        ranges: &[Range<Anchor>],
11844        color_fetcher: fn(&AppContext) -> Hsla,
11845        cx: &mut ViewContext<Self>,
11846    ) {
11847        self.gutter_highlights
11848            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11849        cx.notify();
11850    }
11851
11852    pub fn clear_gutter_highlights<T: 'static>(
11853        &mut self,
11854        cx: &mut ViewContext<Self>,
11855    ) -> Option<GutterHighlight> {
11856        cx.notify();
11857        self.gutter_highlights.remove(&TypeId::of::<T>())
11858    }
11859
11860    #[cfg(feature = "test-support")]
11861    pub fn all_text_background_highlights(
11862        &mut self,
11863        cx: &mut ViewContext<Self>,
11864    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11865        let snapshot = self.snapshot(cx);
11866        let buffer = &snapshot.buffer_snapshot;
11867        let start = buffer.anchor_before(0);
11868        let end = buffer.anchor_after(buffer.len());
11869        let theme = cx.theme().colors();
11870        self.background_highlights_in_range(start..end, &snapshot, theme)
11871    }
11872
11873    #[cfg(feature = "test-support")]
11874    pub fn search_background_highlights(
11875        &mut self,
11876        cx: &mut ViewContext<Self>,
11877    ) -> Vec<Range<Point>> {
11878        let snapshot = self.buffer().read(cx).snapshot(cx);
11879
11880        let highlights = self
11881            .background_highlights
11882            .get(&TypeId::of::<items::BufferSearchHighlights>());
11883
11884        if let Some((_color, ranges)) = highlights {
11885            ranges
11886                .iter()
11887                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11888                .collect_vec()
11889        } else {
11890            vec![]
11891        }
11892    }
11893
11894    fn document_highlights_for_position<'a>(
11895        &'a self,
11896        position: Anchor,
11897        buffer: &'a MultiBufferSnapshot,
11898    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11899        let read_highlights = self
11900            .background_highlights
11901            .get(&TypeId::of::<DocumentHighlightRead>())
11902            .map(|h| &h.1);
11903        let write_highlights = self
11904            .background_highlights
11905            .get(&TypeId::of::<DocumentHighlightWrite>())
11906            .map(|h| &h.1);
11907        let left_position = position.bias_left(buffer);
11908        let right_position = position.bias_right(buffer);
11909        read_highlights
11910            .into_iter()
11911            .chain(write_highlights)
11912            .flat_map(move |ranges| {
11913                let start_ix = match ranges.binary_search_by(|probe| {
11914                    let cmp = probe.end.cmp(&left_position, buffer);
11915                    if cmp.is_ge() {
11916                        Ordering::Greater
11917                    } else {
11918                        Ordering::Less
11919                    }
11920                }) {
11921                    Ok(i) | Err(i) => i,
11922                };
11923
11924                ranges[start_ix..]
11925                    .iter()
11926                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11927            })
11928    }
11929
11930    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11931        self.background_highlights
11932            .get(&TypeId::of::<T>())
11933            .map_or(false, |(_, highlights)| !highlights.is_empty())
11934    }
11935
11936    pub fn background_highlights_in_range(
11937        &self,
11938        search_range: Range<Anchor>,
11939        display_snapshot: &DisplaySnapshot,
11940        theme: &ThemeColors,
11941    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11942        let mut results = Vec::new();
11943        for (color_fetcher, ranges) in self.background_highlights.values() {
11944            let color = color_fetcher(theme);
11945            let start_ix = match ranges.binary_search_by(|probe| {
11946                let cmp = probe
11947                    .end
11948                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11949                if cmp.is_gt() {
11950                    Ordering::Greater
11951                } else {
11952                    Ordering::Less
11953                }
11954            }) {
11955                Ok(i) | Err(i) => i,
11956            };
11957            for range in &ranges[start_ix..] {
11958                if range
11959                    .start
11960                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11961                    .is_ge()
11962                {
11963                    break;
11964                }
11965
11966                let start = range.start.to_display_point(display_snapshot);
11967                let end = range.end.to_display_point(display_snapshot);
11968                results.push((start..end, color))
11969            }
11970        }
11971        results
11972    }
11973
11974    pub fn background_highlight_row_ranges<T: 'static>(
11975        &self,
11976        search_range: Range<Anchor>,
11977        display_snapshot: &DisplaySnapshot,
11978        count: usize,
11979    ) -> Vec<RangeInclusive<DisplayPoint>> {
11980        let mut results = Vec::new();
11981        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11982            return vec![];
11983        };
11984
11985        let start_ix = match ranges.binary_search_by(|probe| {
11986            let cmp = probe
11987                .end
11988                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11989            if cmp.is_gt() {
11990                Ordering::Greater
11991            } else {
11992                Ordering::Less
11993            }
11994        }) {
11995            Ok(i) | Err(i) => i,
11996        };
11997        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11998            if let (Some(start_display), Some(end_display)) = (start, end) {
11999                results.push(
12000                    start_display.to_display_point(display_snapshot)
12001                        ..=end_display.to_display_point(display_snapshot),
12002                );
12003            }
12004        };
12005        let mut start_row: Option<Point> = None;
12006        let mut end_row: Option<Point> = None;
12007        if ranges.len() > count {
12008            return Vec::new();
12009        }
12010        for range in &ranges[start_ix..] {
12011            if range
12012                .start
12013                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12014                .is_ge()
12015            {
12016                break;
12017            }
12018            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12019            if let Some(current_row) = &end_row {
12020                if end.row == current_row.row {
12021                    continue;
12022                }
12023            }
12024            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12025            if start_row.is_none() {
12026                assert_eq!(end_row, None);
12027                start_row = Some(start);
12028                end_row = Some(end);
12029                continue;
12030            }
12031            if let Some(current_end) = end_row.as_mut() {
12032                if start.row > current_end.row + 1 {
12033                    push_region(start_row, end_row);
12034                    start_row = Some(start);
12035                    end_row = Some(end);
12036                } else {
12037                    // Merge two hunks.
12038                    *current_end = end;
12039                }
12040            } else {
12041                unreachable!();
12042            }
12043        }
12044        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12045        push_region(start_row, end_row);
12046        results
12047    }
12048
12049    pub fn gutter_highlights_in_range(
12050        &self,
12051        search_range: Range<Anchor>,
12052        display_snapshot: &DisplaySnapshot,
12053        cx: &AppContext,
12054    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12055        let mut results = Vec::new();
12056        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12057            let color = color_fetcher(cx);
12058            let start_ix = match ranges.binary_search_by(|probe| {
12059                let cmp = probe
12060                    .end
12061                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12062                if cmp.is_gt() {
12063                    Ordering::Greater
12064                } else {
12065                    Ordering::Less
12066                }
12067            }) {
12068                Ok(i) | Err(i) => i,
12069            };
12070            for range in &ranges[start_ix..] {
12071                if range
12072                    .start
12073                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12074                    .is_ge()
12075                {
12076                    break;
12077                }
12078
12079                let start = range.start.to_display_point(display_snapshot);
12080                let end = range.end.to_display_point(display_snapshot);
12081                results.push((start..end, color))
12082            }
12083        }
12084        results
12085    }
12086
12087    /// Get the text ranges corresponding to the redaction query
12088    pub fn redacted_ranges(
12089        &self,
12090        search_range: Range<Anchor>,
12091        display_snapshot: &DisplaySnapshot,
12092        cx: &WindowContext,
12093    ) -> Vec<Range<DisplayPoint>> {
12094        display_snapshot
12095            .buffer_snapshot
12096            .redacted_ranges(search_range, |file| {
12097                if let Some(file) = file {
12098                    file.is_private()
12099                        && EditorSettings::get(
12100                            Some(SettingsLocation {
12101                                worktree_id: file.worktree_id(cx),
12102                                path: file.path().as_ref(),
12103                            }),
12104                            cx,
12105                        )
12106                        .redact_private_values
12107                } else {
12108                    false
12109                }
12110            })
12111            .map(|range| {
12112                range.start.to_display_point(display_snapshot)
12113                    ..range.end.to_display_point(display_snapshot)
12114            })
12115            .collect()
12116    }
12117
12118    pub fn highlight_text<T: 'static>(
12119        &mut self,
12120        ranges: Vec<Range<Anchor>>,
12121        style: HighlightStyle,
12122        cx: &mut ViewContext<Self>,
12123    ) {
12124        self.display_map.update(cx, |map, _| {
12125            map.highlight_text(TypeId::of::<T>(), ranges, style)
12126        });
12127        cx.notify();
12128    }
12129
12130    pub(crate) fn highlight_inlays<T: 'static>(
12131        &mut self,
12132        highlights: Vec<InlayHighlight>,
12133        style: HighlightStyle,
12134        cx: &mut ViewContext<Self>,
12135    ) {
12136        self.display_map.update(cx, |map, _| {
12137            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12138        });
12139        cx.notify();
12140    }
12141
12142    pub fn text_highlights<'a, T: 'static>(
12143        &'a self,
12144        cx: &'a AppContext,
12145    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12146        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12147    }
12148
12149    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12150        let cleared = self
12151            .display_map
12152            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12153        if cleared {
12154            cx.notify();
12155        }
12156    }
12157
12158    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12159        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12160            && self.focus_handle.is_focused(cx)
12161    }
12162
12163    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12164        self.show_cursor_when_unfocused = is_enabled;
12165        cx.notify();
12166    }
12167
12168    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12169        cx.notify();
12170    }
12171
12172    fn on_buffer_event(
12173        &mut self,
12174        multibuffer: Model<MultiBuffer>,
12175        event: &multi_buffer::Event,
12176        cx: &mut ViewContext<Self>,
12177    ) {
12178        match event {
12179            multi_buffer::Event::Edited {
12180                singleton_buffer_edited,
12181            } => {
12182                self.scrollbar_marker_state.dirty = true;
12183                self.active_indent_guides_state.dirty = true;
12184                self.refresh_active_diagnostics(cx);
12185                self.refresh_code_actions(cx);
12186                if self.has_active_inline_completion(cx) {
12187                    self.update_visible_inline_completion(cx);
12188                }
12189                cx.emit(EditorEvent::BufferEdited);
12190                cx.emit(SearchEvent::MatchesInvalidated);
12191                if *singleton_buffer_edited {
12192                    if let Some(project) = &self.project {
12193                        let project = project.read(cx);
12194                        #[allow(clippy::mutable_key_type)]
12195                        let languages_affected = multibuffer
12196                            .read(cx)
12197                            .all_buffers()
12198                            .into_iter()
12199                            .filter_map(|buffer| {
12200                                let buffer = buffer.read(cx);
12201                                let language = buffer.language()?;
12202                                if project.is_local()
12203                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12204                                {
12205                                    None
12206                                } else {
12207                                    Some(language)
12208                                }
12209                            })
12210                            .cloned()
12211                            .collect::<HashSet<_>>();
12212                        if !languages_affected.is_empty() {
12213                            self.refresh_inlay_hints(
12214                                InlayHintRefreshReason::BufferEdited(languages_affected),
12215                                cx,
12216                            );
12217                        }
12218                    }
12219                }
12220
12221                let Some(project) = &self.project else { return };
12222                let (telemetry, is_via_ssh) = {
12223                    let project = project.read(cx);
12224                    let telemetry = project.client().telemetry().clone();
12225                    let is_via_ssh = project.is_via_ssh();
12226                    (telemetry, is_via_ssh)
12227                };
12228                refresh_linked_ranges(self, cx);
12229                telemetry.log_edit_event("editor", is_via_ssh);
12230            }
12231            multi_buffer::Event::ExcerptsAdded {
12232                buffer,
12233                predecessor,
12234                excerpts,
12235            } => {
12236                self.tasks_update_task = Some(self.refresh_runnables(cx));
12237                cx.emit(EditorEvent::ExcerptsAdded {
12238                    buffer: buffer.clone(),
12239                    predecessor: *predecessor,
12240                    excerpts: excerpts.clone(),
12241                });
12242                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12243            }
12244            multi_buffer::Event::ExcerptsRemoved { ids } => {
12245                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12246                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12247            }
12248            multi_buffer::Event::ExcerptsEdited { ids } => {
12249                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12250            }
12251            multi_buffer::Event::ExcerptsExpanded { ids } => {
12252                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12253            }
12254            multi_buffer::Event::Reparsed(buffer_id) => {
12255                self.tasks_update_task = Some(self.refresh_runnables(cx));
12256
12257                cx.emit(EditorEvent::Reparsed(*buffer_id));
12258            }
12259            multi_buffer::Event::LanguageChanged(buffer_id) => {
12260                linked_editing_ranges::refresh_linked_ranges(self, cx);
12261                cx.emit(EditorEvent::Reparsed(*buffer_id));
12262                cx.notify();
12263            }
12264            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12265            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12266            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12267                cx.emit(EditorEvent::TitleChanged)
12268            }
12269            multi_buffer::Event::DiffBaseChanged => {
12270                self.scrollbar_marker_state.dirty = true;
12271                cx.emit(EditorEvent::DiffBaseChanged);
12272                cx.notify();
12273            }
12274            multi_buffer::Event::DiffUpdated { buffer } => {
12275                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12276                cx.notify();
12277            }
12278            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12279            multi_buffer::Event::DiagnosticsUpdated => {
12280                self.refresh_active_diagnostics(cx);
12281                self.scrollbar_marker_state.dirty = true;
12282                cx.notify();
12283            }
12284            _ => {}
12285        };
12286    }
12287
12288    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12289        cx.notify();
12290    }
12291
12292    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12293        self.tasks_update_task = Some(self.refresh_runnables(cx));
12294        self.refresh_inline_completion(true, false, cx);
12295        self.refresh_inlay_hints(
12296            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12297                self.selections.newest_anchor().head(),
12298                &self.buffer.read(cx).snapshot(cx),
12299                cx,
12300            )),
12301            cx,
12302        );
12303
12304        let old_cursor_shape = self.cursor_shape;
12305
12306        {
12307            let editor_settings = EditorSettings::get_global(cx);
12308            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12309            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12310            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12311        }
12312
12313        if old_cursor_shape != self.cursor_shape {
12314            cx.emit(EditorEvent::CursorShapeChanged);
12315        }
12316
12317        let project_settings = ProjectSettings::get_global(cx);
12318        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12319
12320        if self.mode == EditorMode::Full {
12321            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12322            if self.git_blame_inline_enabled != inline_blame_enabled {
12323                self.toggle_git_blame_inline_internal(false, cx);
12324            }
12325        }
12326
12327        cx.notify();
12328    }
12329
12330    pub fn set_searchable(&mut self, searchable: bool) {
12331        self.searchable = searchable;
12332    }
12333
12334    pub fn searchable(&self) -> bool {
12335        self.searchable
12336    }
12337
12338    fn open_proposed_changes_editor(
12339        &mut self,
12340        _: &OpenProposedChangesEditor,
12341        cx: &mut ViewContext<Self>,
12342    ) {
12343        let Some(workspace) = self.workspace() else {
12344            cx.propagate();
12345            return;
12346        };
12347
12348        let buffer = self.buffer.read(cx);
12349        let mut new_selections_by_buffer = HashMap::default();
12350        for selection in self.selections.all::<usize>(cx) {
12351            for (buffer, range, _) in
12352                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12353            {
12354                let mut range = range.to_point(buffer.read(cx));
12355                range.start.column = 0;
12356                range.end.column = buffer.read(cx).line_len(range.end.row);
12357                new_selections_by_buffer
12358                    .entry(buffer)
12359                    .or_insert(Vec::new())
12360                    .push(range)
12361            }
12362        }
12363
12364        let proposed_changes_buffers = new_selections_by_buffer
12365            .into_iter()
12366            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12367            .collect::<Vec<_>>();
12368        let proposed_changes_editor = cx.new_view(|cx| {
12369            ProposedChangesEditor::new(
12370                "Proposed changes",
12371                proposed_changes_buffers,
12372                self.project.clone(),
12373                cx,
12374            )
12375        });
12376
12377        cx.window_context().defer(move |cx| {
12378            workspace.update(cx, |workspace, cx| {
12379                workspace.active_pane().update(cx, |pane, cx| {
12380                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12381                });
12382            });
12383        });
12384    }
12385
12386    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12387        self.open_excerpts_common(true, cx)
12388    }
12389
12390    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12391        self.open_excerpts_common(false, cx)
12392    }
12393
12394    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12395        let buffer = self.buffer.read(cx);
12396        if buffer.is_singleton() {
12397            cx.propagate();
12398            return;
12399        }
12400
12401        let Some(workspace) = self.workspace() else {
12402            cx.propagate();
12403            return;
12404        };
12405
12406        let mut new_selections_by_buffer = HashMap::default();
12407        for selection in self.selections.all::<usize>(cx) {
12408            for (mut buffer_handle, mut range, _) in
12409                buffer.range_to_buffer_ranges(selection.range(), cx)
12410            {
12411                // When editing branch buffers, jump to the corresponding location
12412                // in their base buffer.
12413                let buffer = buffer_handle.read(cx);
12414                if let Some(base_buffer) = buffer.diff_base_buffer() {
12415                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12416                    buffer_handle = base_buffer;
12417                }
12418
12419                if selection.reversed {
12420                    mem::swap(&mut range.start, &mut range.end);
12421                }
12422                new_selections_by_buffer
12423                    .entry(buffer_handle)
12424                    .or_insert(Vec::new())
12425                    .push(range)
12426            }
12427        }
12428
12429        // We defer the pane interaction because we ourselves are a workspace item
12430        // and activating a new item causes the pane to call a method on us reentrantly,
12431        // which panics if we're on the stack.
12432        cx.window_context().defer(move |cx| {
12433            workspace.update(cx, |workspace, cx| {
12434                let pane = if split {
12435                    workspace.adjacent_pane(cx)
12436                } else {
12437                    workspace.active_pane().clone()
12438                };
12439
12440                for (buffer, ranges) in new_selections_by_buffer {
12441                    let editor =
12442                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12443                    editor.update(cx, |editor, cx| {
12444                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12445                            s.select_ranges(ranges);
12446                        });
12447                    });
12448                }
12449            })
12450        });
12451    }
12452
12453    fn jump(
12454        &mut self,
12455        path: ProjectPath,
12456        position: Point,
12457        anchor: language::Anchor,
12458        offset_from_top: u32,
12459        cx: &mut ViewContext<Self>,
12460    ) {
12461        let workspace = self.workspace();
12462        cx.spawn(|_, mut cx| async move {
12463            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12464            let editor = workspace.update(&mut cx, |workspace, cx| {
12465                // Reset the preview item id before opening the new item
12466                workspace.active_pane().update(cx, |pane, cx| {
12467                    pane.set_preview_item_id(None, cx);
12468                });
12469                workspace.open_path_preview(path, None, true, true, cx)
12470            })?;
12471            let editor = editor
12472                .await?
12473                .downcast::<Editor>()
12474                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12475                .downgrade();
12476            editor.update(&mut cx, |editor, cx| {
12477                let buffer = editor
12478                    .buffer()
12479                    .read(cx)
12480                    .as_singleton()
12481                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12482                let buffer = buffer.read(cx);
12483                let cursor = if buffer.can_resolve(&anchor) {
12484                    language::ToPoint::to_point(&anchor, buffer)
12485                } else {
12486                    buffer.clip_point(position, Bias::Left)
12487                };
12488
12489                let nav_history = editor.nav_history.take();
12490                editor.change_selections(
12491                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12492                    cx,
12493                    |s| {
12494                        s.select_ranges([cursor..cursor]);
12495                    },
12496                );
12497                editor.nav_history = nav_history;
12498
12499                anyhow::Ok(())
12500            })??;
12501
12502            anyhow::Ok(())
12503        })
12504        .detach_and_log_err(cx);
12505    }
12506
12507    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12508        let snapshot = self.buffer.read(cx).read(cx);
12509        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12510        Some(
12511            ranges
12512                .iter()
12513                .map(move |range| {
12514                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12515                })
12516                .collect(),
12517        )
12518    }
12519
12520    fn selection_replacement_ranges(
12521        &self,
12522        range: Range<OffsetUtf16>,
12523        cx: &AppContext,
12524    ) -> Vec<Range<OffsetUtf16>> {
12525        let selections = self.selections.all::<OffsetUtf16>(cx);
12526        let newest_selection = selections
12527            .iter()
12528            .max_by_key(|selection| selection.id)
12529            .unwrap();
12530        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12531        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12532        let snapshot = self.buffer.read(cx).read(cx);
12533        selections
12534            .into_iter()
12535            .map(|mut selection| {
12536                selection.start.0 =
12537                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12538                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12539                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12540                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12541            })
12542            .collect()
12543    }
12544
12545    fn report_editor_event(
12546        &self,
12547        operation: &'static str,
12548        file_extension: Option<String>,
12549        cx: &AppContext,
12550    ) {
12551        if cfg!(any(test, feature = "test-support")) {
12552            return;
12553        }
12554
12555        let Some(project) = &self.project else { return };
12556
12557        // If None, we are in a file without an extension
12558        let file = self
12559            .buffer
12560            .read(cx)
12561            .as_singleton()
12562            .and_then(|b| b.read(cx).file());
12563        let file_extension = file_extension.or(file
12564            .as_ref()
12565            .and_then(|file| Path::new(file.file_name(cx)).extension())
12566            .and_then(|e| e.to_str())
12567            .map(|a| a.to_string()));
12568
12569        let vim_mode = cx
12570            .global::<SettingsStore>()
12571            .raw_user_settings()
12572            .get("vim_mode")
12573            == Some(&serde_json::Value::Bool(true));
12574
12575        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12576            == language::language_settings::InlineCompletionProvider::Copilot;
12577        let copilot_enabled_for_language = self
12578            .buffer
12579            .read(cx)
12580            .settings_at(0, cx)
12581            .show_inline_completions;
12582
12583        let project = project.read(cx);
12584        let telemetry = project.client().telemetry().clone();
12585        telemetry.report_editor_event(
12586            file_extension,
12587            vim_mode,
12588            operation,
12589            copilot_enabled,
12590            copilot_enabled_for_language,
12591            project.is_via_ssh(),
12592        )
12593    }
12594
12595    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12596    /// with each line being an array of {text, highlight} objects.
12597    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12598        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12599            return;
12600        };
12601
12602        #[derive(Serialize)]
12603        struct Chunk<'a> {
12604            text: String,
12605            highlight: Option<&'a str>,
12606        }
12607
12608        let snapshot = buffer.read(cx).snapshot();
12609        let range = self
12610            .selected_text_range(false, cx)
12611            .and_then(|selection| {
12612                if selection.range.is_empty() {
12613                    None
12614                } else {
12615                    Some(selection.range)
12616                }
12617            })
12618            .unwrap_or_else(|| 0..snapshot.len());
12619
12620        let chunks = snapshot.chunks(range, true);
12621        let mut lines = Vec::new();
12622        let mut line: VecDeque<Chunk> = VecDeque::new();
12623
12624        let Some(style) = self.style.as_ref() else {
12625            return;
12626        };
12627
12628        for chunk in chunks {
12629            let highlight = chunk
12630                .syntax_highlight_id
12631                .and_then(|id| id.name(&style.syntax));
12632            let mut chunk_lines = chunk.text.split('\n').peekable();
12633            while let Some(text) = chunk_lines.next() {
12634                let mut merged_with_last_token = false;
12635                if let Some(last_token) = line.back_mut() {
12636                    if last_token.highlight == highlight {
12637                        last_token.text.push_str(text);
12638                        merged_with_last_token = true;
12639                    }
12640                }
12641
12642                if !merged_with_last_token {
12643                    line.push_back(Chunk {
12644                        text: text.into(),
12645                        highlight,
12646                    });
12647                }
12648
12649                if chunk_lines.peek().is_some() {
12650                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12651                        line.pop_front();
12652                    }
12653                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12654                        line.pop_back();
12655                    }
12656
12657                    lines.push(mem::take(&mut line));
12658                }
12659            }
12660        }
12661
12662        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12663            return;
12664        };
12665        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12666    }
12667
12668    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12669        &self.inlay_hint_cache
12670    }
12671
12672    pub fn replay_insert_event(
12673        &mut self,
12674        text: &str,
12675        relative_utf16_range: Option<Range<isize>>,
12676        cx: &mut ViewContext<Self>,
12677    ) {
12678        if !self.input_enabled {
12679            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12680            return;
12681        }
12682        if let Some(relative_utf16_range) = relative_utf16_range {
12683            let selections = self.selections.all::<OffsetUtf16>(cx);
12684            self.change_selections(None, cx, |s| {
12685                let new_ranges = selections.into_iter().map(|range| {
12686                    let start = OffsetUtf16(
12687                        range
12688                            .head()
12689                            .0
12690                            .saturating_add_signed(relative_utf16_range.start),
12691                    );
12692                    let end = OffsetUtf16(
12693                        range
12694                            .head()
12695                            .0
12696                            .saturating_add_signed(relative_utf16_range.end),
12697                    );
12698                    start..end
12699                });
12700                s.select_ranges(new_ranges);
12701            });
12702        }
12703
12704        self.handle_input(text, cx);
12705    }
12706
12707    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12708        let Some(provider) = self.semantics_provider.as_ref() else {
12709            return false;
12710        };
12711
12712        let mut supports = false;
12713        self.buffer().read(cx).for_each_buffer(|buffer| {
12714            supports |= provider.supports_inlay_hints(buffer, cx);
12715        });
12716        supports
12717    }
12718
12719    pub fn focus(&self, cx: &mut WindowContext) {
12720        cx.focus(&self.focus_handle)
12721    }
12722
12723    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12724        self.focus_handle.is_focused(cx)
12725    }
12726
12727    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12728        cx.emit(EditorEvent::Focused);
12729
12730        if let Some(descendant) = self
12731            .last_focused_descendant
12732            .take()
12733            .and_then(|descendant| descendant.upgrade())
12734        {
12735            cx.focus(&descendant);
12736        } else {
12737            if let Some(blame) = self.blame.as_ref() {
12738                blame.update(cx, GitBlame::focus)
12739            }
12740
12741            self.blink_manager.update(cx, BlinkManager::enable);
12742            self.show_cursor_names(cx);
12743            self.buffer.update(cx, |buffer, cx| {
12744                buffer.finalize_last_transaction(cx);
12745                if self.leader_peer_id.is_none() {
12746                    buffer.set_active_selections(
12747                        &self.selections.disjoint_anchors(),
12748                        self.selections.line_mode,
12749                        self.cursor_shape,
12750                        cx,
12751                    );
12752                }
12753            });
12754        }
12755    }
12756
12757    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12758        cx.emit(EditorEvent::FocusedIn)
12759    }
12760
12761    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12762        if event.blurred != self.focus_handle {
12763            self.last_focused_descendant = Some(event.blurred);
12764        }
12765    }
12766
12767    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12768        self.blink_manager.update(cx, BlinkManager::disable);
12769        self.buffer
12770            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12771
12772        if let Some(blame) = self.blame.as_ref() {
12773            blame.update(cx, GitBlame::blur)
12774        }
12775        if !self.hover_state.focused(cx) {
12776            hide_hover(self, cx);
12777        }
12778
12779        self.hide_context_menu(cx);
12780        cx.emit(EditorEvent::Blurred);
12781        cx.notify();
12782    }
12783
12784    pub fn register_action<A: Action>(
12785        &mut self,
12786        listener: impl Fn(&A, &mut WindowContext) + 'static,
12787    ) -> Subscription {
12788        let id = self.next_editor_action_id.post_inc();
12789        let listener = Arc::new(listener);
12790        self.editor_actions.borrow_mut().insert(
12791            id,
12792            Box::new(move |cx| {
12793                let cx = cx.window_context();
12794                let listener = listener.clone();
12795                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12796                    let action = action.downcast_ref().unwrap();
12797                    if phase == DispatchPhase::Bubble {
12798                        listener(action, cx)
12799                    }
12800                })
12801            }),
12802        );
12803
12804        let editor_actions = self.editor_actions.clone();
12805        Subscription::new(move || {
12806            editor_actions.borrow_mut().remove(&id);
12807        })
12808    }
12809
12810    pub fn file_header_size(&self) -> u32 {
12811        self.file_header_size
12812    }
12813
12814    pub fn revert(
12815        &mut self,
12816        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12817        cx: &mut ViewContext<Self>,
12818    ) {
12819        self.buffer().update(cx, |multi_buffer, cx| {
12820            for (buffer_id, changes) in revert_changes {
12821                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12822                    buffer.update(cx, |buffer, cx| {
12823                        buffer.edit(
12824                            changes.into_iter().map(|(range, text)| {
12825                                (range, text.to_string().map(Arc::<str>::from))
12826                            }),
12827                            None,
12828                            cx,
12829                        );
12830                    });
12831                }
12832            }
12833        });
12834        self.change_selections(None, cx, |selections| selections.refresh());
12835    }
12836
12837    pub fn to_pixel_point(
12838        &mut self,
12839        source: multi_buffer::Anchor,
12840        editor_snapshot: &EditorSnapshot,
12841        cx: &mut ViewContext<Self>,
12842    ) -> Option<gpui::Point<Pixels>> {
12843        let source_point = source.to_display_point(editor_snapshot);
12844        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12845    }
12846
12847    pub fn display_to_pixel_point(
12848        &mut self,
12849        source: DisplayPoint,
12850        editor_snapshot: &EditorSnapshot,
12851        cx: &mut ViewContext<Self>,
12852    ) -> Option<gpui::Point<Pixels>> {
12853        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12854        let text_layout_details = self.text_layout_details(cx);
12855        let scroll_top = text_layout_details
12856            .scroll_anchor
12857            .scroll_position(editor_snapshot)
12858            .y;
12859
12860        if source.row().as_f32() < scroll_top.floor() {
12861            return None;
12862        }
12863        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12864        let source_y = line_height * (source.row().as_f32() - scroll_top);
12865        Some(gpui::Point::new(source_x, source_y))
12866    }
12867
12868    pub fn has_active_completions_menu(&self) -> bool {
12869        self.context_menu.read().as_ref().map_or(false, |menu| {
12870            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12871        })
12872    }
12873
12874    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12875        self.addons
12876            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12877    }
12878
12879    pub fn unregister_addon<T: Addon>(&mut self) {
12880        self.addons.remove(&std::any::TypeId::of::<T>());
12881    }
12882
12883    pub fn addon<T: Addon>(&self) -> Option<&T> {
12884        let type_id = std::any::TypeId::of::<T>();
12885        self.addons
12886            .get(&type_id)
12887            .and_then(|item| item.to_any().downcast_ref::<T>())
12888    }
12889}
12890
12891fn hunks_for_selections(
12892    multi_buffer_snapshot: &MultiBufferSnapshot,
12893    selections: &[Selection<Anchor>],
12894) -> Vec<MultiBufferDiffHunk> {
12895    let buffer_rows_for_selections = selections.iter().map(|selection| {
12896        let head = selection.head();
12897        let tail = selection.tail();
12898        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12899        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12900        if start > end {
12901            end..start
12902        } else {
12903            start..end
12904        }
12905    });
12906
12907    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12908}
12909
12910pub fn hunks_for_rows(
12911    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12912    multi_buffer_snapshot: &MultiBufferSnapshot,
12913) -> Vec<MultiBufferDiffHunk> {
12914    let mut hunks = Vec::new();
12915    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12916        HashMap::default();
12917    for selected_multi_buffer_rows in rows {
12918        let query_rows =
12919            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12920        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12921            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12922            // when the caret is just above or just below the deleted hunk.
12923            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12924            let related_to_selection = if allow_adjacent {
12925                hunk.row_range.overlaps(&query_rows)
12926                    || hunk.row_range.start == query_rows.end
12927                    || hunk.row_range.end == query_rows.start
12928            } else {
12929                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12930                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12931                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12932                    || selected_multi_buffer_rows.end == hunk.row_range.start
12933            };
12934            if related_to_selection {
12935                if !processed_buffer_rows
12936                    .entry(hunk.buffer_id)
12937                    .or_default()
12938                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12939                {
12940                    continue;
12941                }
12942                hunks.push(hunk);
12943            }
12944        }
12945    }
12946
12947    hunks
12948}
12949
12950pub trait CollaborationHub {
12951    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12952    fn user_participant_indices<'a>(
12953        &self,
12954        cx: &'a AppContext,
12955    ) -> &'a HashMap<u64, ParticipantIndex>;
12956    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12957}
12958
12959impl CollaborationHub for Model<Project> {
12960    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12961        self.read(cx).collaborators()
12962    }
12963
12964    fn user_participant_indices<'a>(
12965        &self,
12966        cx: &'a AppContext,
12967    ) -> &'a HashMap<u64, ParticipantIndex> {
12968        self.read(cx).user_store().read(cx).participant_indices()
12969    }
12970
12971    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12972        let this = self.read(cx);
12973        let user_ids = this.collaborators().values().map(|c| c.user_id);
12974        this.user_store().read_with(cx, |user_store, cx| {
12975            user_store.participant_names(user_ids, cx)
12976        })
12977    }
12978}
12979
12980pub trait SemanticsProvider {
12981    fn hover(
12982        &self,
12983        buffer: &Model<Buffer>,
12984        position: text::Anchor,
12985        cx: &mut AppContext,
12986    ) -> Option<Task<Vec<project::Hover>>>;
12987
12988    fn inlay_hints(
12989        &self,
12990        buffer_handle: Model<Buffer>,
12991        range: Range<text::Anchor>,
12992        cx: &mut AppContext,
12993    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12994
12995    fn resolve_inlay_hint(
12996        &self,
12997        hint: InlayHint,
12998        buffer_handle: Model<Buffer>,
12999        server_id: LanguageServerId,
13000        cx: &mut AppContext,
13001    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13002
13003    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13004
13005    fn document_highlights(
13006        &self,
13007        buffer: &Model<Buffer>,
13008        position: text::Anchor,
13009        cx: &mut AppContext,
13010    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13011
13012    fn definitions(
13013        &self,
13014        buffer: &Model<Buffer>,
13015        position: text::Anchor,
13016        kind: GotoDefinitionKind,
13017        cx: &mut AppContext,
13018    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13019
13020    fn range_for_rename(
13021        &self,
13022        buffer: &Model<Buffer>,
13023        position: text::Anchor,
13024        cx: &mut AppContext,
13025    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13026
13027    fn perform_rename(
13028        &self,
13029        buffer: &Model<Buffer>,
13030        position: text::Anchor,
13031        new_name: String,
13032        cx: &mut AppContext,
13033    ) -> Option<Task<Result<ProjectTransaction>>>;
13034}
13035
13036pub trait CompletionProvider {
13037    fn completions(
13038        &self,
13039        buffer: &Model<Buffer>,
13040        buffer_position: text::Anchor,
13041        trigger: CompletionContext,
13042        cx: &mut ViewContext<Editor>,
13043    ) -> Task<Result<Vec<Completion>>>;
13044
13045    fn resolve_completions(
13046        &self,
13047        buffer: Model<Buffer>,
13048        completion_indices: Vec<usize>,
13049        completions: Arc<RwLock<Box<[Completion]>>>,
13050        cx: &mut ViewContext<Editor>,
13051    ) -> Task<Result<bool>>;
13052
13053    fn apply_additional_edits_for_completion(
13054        &self,
13055        buffer: Model<Buffer>,
13056        completion: Completion,
13057        push_to_history: bool,
13058        cx: &mut ViewContext<Editor>,
13059    ) -> Task<Result<Option<language::Transaction>>>;
13060
13061    fn is_completion_trigger(
13062        &self,
13063        buffer: &Model<Buffer>,
13064        position: language::Anchor,
13065        text: &str,
13066        trigger_in_words: bool,
13067        cx: &mut ViewContext<Editor>,
13068    ) -> bool;
13069
13070    fn sort_completions(&self) -> bool {
13071        true
13072    }
13073}
13074
13075pub trait CodeActionProvider {
13076    fn code_actions(
13077        &self,
13078        buffer: &Model<Buffer>,
13079        range: Range<text::Anchor>,
13080        cx: &mut WindowContext,
13081    ) -> Task<Result<Vec<CodeAction>>>;
13082
13083    fn apply_code_action(
13084        &self,
13085        buffer_handle: Model<Buffer>,
13086        action: CodeAction,
13087        excerpt_id: ExcerptId,
13088        push_to_history: bool,
13089        cx: &mut WindowContext,
13090    ) -> Task<Result<ProjectTransaction>>;
13091}
13092
13093impl CodeActionProvider for Model<Project> {
13094    fn code_actions(
13095        &self,
13096        buffer: &Model<Buffer>,
13097        range: Range<text::Anchor>,
13098        cx: &mut WindowContext,
13099    ) -> Task<Result<Vec<CodeAction>>> {
13100        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13101    }
13102
13103    fn apply_code_action(
13104        &self,
13105        buffer_handle: Model<Buffer>,
13106        action: CodeAction,
13107        _excerpt_id: ExcerptId,
13108        push_to_history: bool,
13109        cx: &mut WindowContext,
13110    ) -> Task<Result<ProjectTransaction>> {
13111        self.update(cx, |project, cx| {
13112            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13113        })
13114    }
13115}
13116
13117fn snippet_completions(
13118    project: &Project,
13119    buffer: &Model<Buffer>,
13120    buffer_position: text::Anchor,
13121    cx: &mut AppContext,
13122) -> Vec<Completion> {
13123    let language = buffer.read(cx).language_at(buffer_position);
13124    let language_name = language.as_ref().map(|language| language.lsp_id());
13125    let snippet_store = project.snippets().read(cx);
13126    let snippets = snippet_store.snippets_for(language_name, cx);
13127
13128    if snippets.is_empty() {
13129        return vec![];
13130    }
13131    let snapshot = buffer.read(cx).text_snapshot();
13132    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13133
13134    let scope = language.map(|language| language.default_scope());
13135    let classifier = CharClassifier::new(scope).for_completion(true);
13136    let mut last_word = chars
13137        .take_while(|c| classifier.is_word(*c))
13138        .collect::<String>();
13139    last_word = last_word.chars().rev().collect();
13140    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13141    let to_lsp = |point: &text::Anchor| {
13142        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13143        point_to_lsp(end)
13144    };
13145    let lsp_end = to_lsp(&buffer_position);
13146    snippets
13147        .into_iter()
13148        .filter_map(|snippet| {
13149            let matching_prefix = snippet
13150                .prefix
13151                .iter()
13152                .find(|prefix| prefix.starts_with(&last_word))?;
13153            let start = as_offset - last_word.len();
13154            let start = snapshot.anchor_before(start);
13155            let range = start..buffer_position;
13156            let lsp_start = to_lsp(&start);
13157            let lsp_range = lsp::Range {
13158                start: lsp_start,
13159                end: lsp_end,
13160            };
13161            Some(Completion {
13162                old_range: range,
13163                new_text: snippet.body.clone(),
13164                label: CodeLabel {
13165                    text: matching_prefix.clone(),
13166                    runs: vec![],
13167                    filter_range: 0..matching_prefix.len(),
13168                },
13169                server_id: LanguageServerId(usize::MAX),
13170                documentation: snippet.description.clone().map(Documentation::SingleLine),
13171                lsp_completion: lsp::CompletionItem {
13172                    label: snippet.prefix.first().unwrap().clone(),
13173                    kind: Some(CompletionItemKind::SNIPPET),
13174                    label_details: snippet.description.as_ref().map(|description| {
13175                        lsp::CompletionItemLabelDetails {
13176                            detail: Some(description.clone()),
13177                            description: None,
13178                        }
13179                    }),
13180                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13181                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13182                        lsp::InsertReplaceEdit {
13183                            new_text: snippet.body.clone(),
13184                            insert: lsp_range,
13185                            replace: lsp_range,
13186                        },
13187                    )),
13188                    filter_text: Some(snippet.body.clone()),
13189                    sort_text: Some(char::MAX.to_string()),
13190                    ..Default::default()
13191                },
13192                confirm: None,
13193            })
13194        })
13195        .collect()
13196}
13197
13198impl CompletionProvider for Model<Project> {
13199    fn completions(
13200        &self,
13201        buffer: &Model<Buffer>,
13202        buffer_position: text::Anchor,
13203        options: CompletionContext,
13204        cx: &mut ViewContext<Editor>,
13205    ) -> Task<Result<Vec<Completion>>> {
13206        self.update(cx, |project, cx| {
13207            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13208            let project_completions = project.completions(buffer, buffer_position, options, cx);
13209            cx.background_executor().spawn(async move {
13210                let mut completions = project_completions.await?;
13211                //let snippets = snippets.into_iter().;
13212                completions.extend(snippets);
13213                Ok(completions)
13214            })
13215        })
13216    }
13217
13218    fn resolve_completions(
13219        &self,
13220        buffer: Model<Buffer>,
13221        completion_indices: Vec<usize>,
13222        completions: Arc<RwLock<Box<[Completion]>>>,
13223        cx: &mut ViewContext<Editor>,
13224    ) -> Task<Result<bool>> {
13225        self.update(cx, |project, cx| {
13226            project.resolve_completions(buffer, completion_indices, completions, cx)
13227        })
13228    }
13229
13230    fn apply_additional_edits_for_completion(
13231        &self,
13232        buffer: Model<Buffer>,
13233        completion: Completion,
13234        push_to_history: bool,
13235        cx: &mut ViewContext<Editor>,
13236    ) -> Task<Result<Option<language::Transaction>>> {
13237        self.update(cx, |project, cx| {
13238            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13239        })
13240    }
13241
13242    fn is_completion_trigger(
13243        &self,
13244        buffer: &Model<Buffer>,
13245        position: language::Anchor,
13246        text: &str,
13247        trigger_in_words: bool,
13248        cx: &mut ViewContext<Editor>,
13249    ) -> bool {
13250        if !EditorSettings::get_global(cx).show_completions_on_input {
13251            return false;
13252        }
13253
13254        let mut chars = text.chars();
13255        let char = if let Some(char) = chars.next() {
13256            char
13257        } else {
13258            return false;
13259        };
13260        if chars.next().is_some() {
13261            return false;
13262        }
13263
13264        let buffer = buffer.read(cx);
13265        let classifier = buffer
13266            .snapshot()
13267            .char_classifier_at(position)
13268            .for_completion(true);
13269        if trigger_in_words && classifier.is_word(char) {
13270            return true;
13271        }
13272
13273        buffer
13274            .completion_triggers()
13275            .iter()
13276            .any(|string| string == text)
13277    }
13278}
13279
13280impl SemanticsProvider for Model<Project> {
13281    fn hover(
13282        &self,
13283        buffer: &Model<Buffer>,
13284        position: text::Anchor,
13285        cx: &mut AppContext,
13286    ) -> Option<Task<Vec<project::Hover>>> {
13287        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13288    }
13289
13290    fn document_highlights(
13291        &self,
13292        buffer: &Model<Buffer>,
13293        position: text::Anchor,
13294        cx: &mut AppContext,
13295    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13296        Some(self.update(cx, |project, cx| {
13297            project.document_highlights(buffer, position, cx)
13298        }))
13299    }
13300
13301    fn definitions(
13302        &self,
13303        buffer: &Model<Buffer>,
13304        position: text::Anchor,
13305        kind: GotoDefinitionKind,
13306        cx: &mut AppContext,
13307    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13308        Some(self.update(cx, |project, cx| match kind {
13309            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13310            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13311            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13312            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13313        }))
13314    }
13315
13316    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13317        // TODO: make this work for remote projects
13318        self.read(cx)
13319            .language_servers_for_buffer(buffer.read(cx), cx)
13320            .any(
13321                |(_, server)| match server.capabilities().inlay_hint_provider {
13322                    Some(lsp::OneOf::Left(enabled)) => enabled,
13323                    Some(lsp::OneOf::Right(_)) => true,
13324                    None => false,
13325                },
13326            )
13327    }
13328
13329    fn inlay_hints(
13330        &self,
13331        buffer_handle: Model<Buffer>,
13332        range: Range<text::Anchor>,
13333        cx: &mut AppContext,
13334    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13335        Some(self.update(cx, |project, cx| {
13336            project.inlay_hints(buffer_handle, range, cx)
13337        }))
13338    }
13339
13340    fn resolve_inlay_hint(
13341        &self,
13342        hint: InlayHint,
13343        buffer_handle: Model<Buffer>,
13344        server_id: LanguageServerId,
13345        cx: &mut AppContext,
13346    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13347        Some(self.update(cx, |project, cx| {
13348            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13349        }))
13350    }
13351
13352    fn range_for_rename(
13353        &self,
13354        buffer: &Model<Buffer>,
13355        position: text::Anchor,
13356        cx: &mut AppContext,
13357    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13358        Some(self.update(cx, |project, cx| {
13359            project.prepare_rename(buffer.clone(), position, cx)
13360        }))
13361    }
13362
13363    fn perform_rename(
13364        &self,
13365        buffer: &Model<Buffer>,
13366        position: text::Anchor,
13367        new_name: String,
13368        cx: &mut AppContext,
13369    ) -> Option<Task<Result<ProjectTransaction>>> {
13370        Some(self.update(cx, |project, cx| {
13371            project.perform_rename(buffer.clone(), position, new_name, cx)
13372        }))
13373    }
13374}
13375
13376fn inlay_hint_settings(
13377    location: Anchor,
13378    snapshot: &MultiBufferSnapshot,
13379    cx: &mut ViewContext<'_, Editor>,
13380) -> InlayHintSettings {
13381    let file = snapshot.file_at(location);
13382    let language = snapshot.language_at(location);
13383    let settings = all_language_settings(file, cx);
13384    settings
13385        .language(language.map(|l| l.name()).as_ref())
13386        .inlay_hints
13387}
13388
13389fn consume_contiguous_rows(
13390    contiguous_row_selections: &mut Vec<Selection<Point>>,
13391    selection: &Selection<Point>,
13392    display_map: &DisplaySnapshot,
13393    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13394) -> (MultiBufferRow, MultiBufferRow) {
13395    contiguous_row_selections.push(selection.clone());
13396    let start_row = MultiBufferRow(selection.start.row);
13397    let mut end_row = ending_row(selection, display_map);
13398
13399    while let Some(next_selection) = selections.peek() {
13400        if next_selection.start.row <= end_row.0 {
13401            end_row = ending_row(next_selection, display_map);
13402            contiguous_row_selections.push(selections.next().unwrap().clone());
13403        } else {
13404            break;
13405        }
13406    }
13407    (start_row, end_row)
13408}
13409
13410fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13411    if next_selection.end.column > 0 || next_selection.is_empty() {
13412        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13413    } else {
13414        MultiBufferRow(next_selection.end.row)
13415    }
13416}
13417
13418impl EditorSnapshot {
13419    pub fn remote_selections_in_range<'a>(
13420        &'a self,
13421        range: &'a Range<Anchor>,
13422        collaboration_hub: &dyn CollaborationHub,
13423        cx: &'a AppContext,
13424    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13425        let participant_names = collaboration_hub.user_names(cx);
13426        let participant_indices = collaboration_hub.user_participant_indices(cx);
13427        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13428        let collaborators_by_replica_id = collaborators_by_peer_id
13429            .iter()
13430            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13431            .collect::<HashMap<_, _>>();
13432        self.buffer_snapshot
13433            .selections_in_range(range, false)
13434            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13435                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13436                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13437                let user_name = participant_names.get(&collaborator.user_id).cloned();
13438                Some(RemoteSelection {
13439                    replica_id,
13440                    selection,
13441                    cursor_shape,
13442                    line_mode,
13443                    participant_index,
13444                    peer_id: collaborator.peer_id,
13445                    user_name,
13446                })
13447            })
13448    }
13449
13450    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13451        self.display_snapshot.buffer_snapshot.language_at(position)
13452    }
13453
13454    pub fn is_focused(&self) -> bool {
13455        self.is_focused
13456    }
13457
13458    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13459        self.placeholder_text.as_ref()
13460    }
13461
13462    pub fn scroll_position(&self) -> gpui::Point<f32> {
13463        self.scroll_anchor.scroll_position(&self.display_snapshot)
13464    }
13465
13466    fn gutter_dimensions(
13467        &self,
13468        font_id: FontId,
13469        font_size: Pixels,
13470        em_width: Pixels,
13471        em_advance: Pixels,
13472        max_line_number_width: Pixels,
13473        cx: &AppContext,
13474    ) -> GutterDimensions {
13475        if !self.show_gutter {
13476            return GutterDimensions::default();
13477        }
13478        let descent = cx.text_system().descent(font_id, font_size);
13479
13480        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13481            matches!(
13482                ProjectSettings::get_global(cx).git.git_gutter,
13483                Some(GitGutterSetting::TrackedFiles)
13484            )
13485        });
13486        let gutter_settings = EditorSettings::get_global(cx).gutter;
13487        let show_line_numbers = self
13488            .show_line_numbers
13489            .unwrap_or(gutter_settings.line_numbers);
13490        let line_gutter_width = if show_line_numbers {
13491            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13492            let min_width_for_number_on_gutter = em_advance * 4.0;
13493            max_line_number_width.max(min_width_for_number_on_gutter)
13494        } else {
13495            0.0.into()
13496        };
13497
13498        let show_code_actions = self
13499            .show_code_actions
13500            .unwrap_or(gutter_settings.code_actions);
13501
13502        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13503
13504        let git_blame_entries_width =
13505            self.git_blame_gutter_max_author_length
13506                .map(|max_author_length| {
13507                    // Length of the author name, but also space for the commit hash,
13508                    // the spacing and the timestamp.
13509                    let max_char_count = max_author_length
13510                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13511                        + 7 // length of commit sha
13512                        + 14 // length of max relative timestamp ("60 minutes ago")
13513                        + 4; // gaps and margins
13514
13515                    em_advance * max_char_count
13516                });
13517
13518        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13519        left_padding += if show_code_actions || show_runnables {
13520            em_width * 3.0
13521        } else if show_git_gutter && show_line_numbers {
13522            em_width * 2.0
13523        } else if show_git_gutter || show_line_numbers {
13524            em_width
13525        } else {
13526            px(0.)
13527        };
13528
13529        let right_padding = if gutter_settings.folds && show_line_numbers {
13530            em_width * 4.0
13531        } else if gutter_settings.folds {
13532            em_width * 3.0
13533        } else if show_line_numbers {
13534            em_width
13535        } else {
13536            px(0.)
13537        };
13538
13539        GutterDimensions {
13540            left_padding,
13541            right_padding,
13542            width: line_gutter_width + left_padding + right_padding,
13543            margin: -descent,
13544            git_blame_entries_width,
13545        }
13546    }
13547
13548    pub fn render_fold_toggle(
13549        &self,
13550        buffer_row: MultiBufferRow,
13551        row_contains_cursor: bool,
13552        editor: View<Editor>,
13553        cx: &mut WindowContext,
13554    ) -> Option<AnyElement> {
13555        let folded = self.is_line_folded(buffer_row);
13556
13557        if let Some(crease) = self
13558            .crease_snapshot
13559            .query_row(buffer_row, &self.buffer_snapshot)
13560        {
13561            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13562                if folded {
13563                    editor.update(cx, |editor, cx| {
13564                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13565                    });
13566                } else {
13567                    editor.update(cx, |editor, cx| {
13568                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13569                    });
13570                }
13571            });
13572
13573            Some((crease.render_toggle)(
13574                buffer_row,
13575                folded,
13576                toggle_callback,
13577                cx,
13578            ))
13579        } else if folded
13580            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13581        {
13582            Some(
13583                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13584                    .selected(folded)
13585                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13586                        if folded {
13587                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13588                        } else {
13589                            this.fold_at(&FoldAt { buffer_row }, cx);
13590                        }
13591                    }))
13592                    .into_any_element(),
13593            )
13594        } else {
13595            None
13596        }
13597    }
13598
13599    pub fn render_crease_trailer(
13600        &self,
13601        buffer_row: MultiBufferRow,
13602        cx: &mut WindowContext,
13603    ) -> Option<AnyElement> {
13604        let folded = self.is_line_folded(buffer_row);
13605        let crease = self
13606            .crease_snapshot
13607            .query_row(buffer_row, &self.buffer_snapshot)?;
13608        Some((crease.render_trailer)(buffer_row, folded, cx))
13609    }
13610}
13611
13612impl Deref for EditorSnapshot {
13613    type Target = DisplaySnapshot;
13614
13615    fn deref(&self) -> &Self::Target {
13616        &self.display_snapshot
13617    }
13618}
13619
13620#[derive(Clone, Debug, PartialEq, Eq)]
13621pub enum EditorEvent {
13622    InputIgnored {
13623        text: Arc<str>,
13624    },
13625    InputHandled {
13626        utf16_range_to_replace: Option<Range<isize>>,
13627        text: Arc<str>,
13628    },
13629    ExcerptsAdded {
13630        buffer: Model<Buffer>,
13631        predecessor: ExcerptId,
13632        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13633    },
13634    ExcerptsRemoved {
13635        ids: Vec<ExcerptId>,
13636    },
13637    ExcerptsEdited {
13638        ids: Vec<ExcerptId>,
13639    },
13640    ExcerptsExpanded {
13641        ids: Vec<ExcerptId>,
13642    },
13643    BufferEdited,
13644    Edited {
13645        transaction_id: clock::Lamport,
13646    },
13647    Reparsed(BufferId),
13648    Focused,
13649    FocusedIn,
13650    Blurred,
13651    DirtyChanged,
13652    Saved,
13653    TitleChanged,
13654    DiffBaseChanged,
13655    SelectionsChanged {
13656        local: bool,
13657    },
13658    ScrollPositionChanged {
13659        local: bool,
13660        autoscroll: bool,
13661    },
13662    Closed,
13663    TransactionUndone {
13664        transaction_id: clock::Lamport,
13665    },
13666    TransactionBegun {
13667        transaction_id: clock::Lamport,
13668    },
13669    Reloaded,
13670    CursorShapeChanged,
13671}
13672
13673impl EventEmitter<EditorEvent> for Editor {}
13674
13675impl FocusableView for Editor {
13676    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13677        self.focus_handle.clone()
13678    }
13679}
13680
13681impl Render for Editor {
13682    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13683        let settings = ThemeSettings::get_global(cx);
13684
13685        let text_style = match self.mode {
13686            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13687                color: cx.theme().colors().editor_foreground,
13688                font_family: settings.ui_font.family.clone(),
13689                font_features: settings.ui_font.features.clone(),
13690                font_fallbacks: settings.ui_font.fallbacks.clone(),
13691                font_size: rems(0.875).into(),
13692                font_weight: settings.ui_font.weight,
13693                line_height: relative(settings.buffer_line_height.value()),
13694                ..Default::default()
13695            },
13696            EditorMode::Full => TextStyle {
13697                color: cx.theme().colors().editor_foreground,
13698                font_family: settings.buffer_font.family.clone(),
13699                font_features: settings.buffer_font.features.clone(),
13700                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13701                font_size: settings.buffer_font_size(cx).into(),
13702                font_weight: settings.buffer_font.weight,
13703                line_height: relative(settings.buffer_line_height.value()),
13704                ..Default::default()
13705            },
13706        };
13707
13708        let background = match self.mode {
13709            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13710            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13711            EditorMode::Full => cx.theme().colors().editor_background,
13712        };
13713
13714        EditorElement::new(
13715            cx.view(),
13716            EditorStyle {
13717                background,
13718                local_player: cx.theme().players().local(),
13719                text: text_style,
13720                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13721                syntax: cx.theme().syntax().clone(),
13722                status: cx.theme().status().clone(),
13723                inlay_hints_style: make_inlay_hints_style(cx),
13724                suggestions_style: HighlightStyle {
13725                    color: Some(cx.theme().status().predictive),
13726                    ..HighlightStyle::default()
13727                },
13728                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13729            },
13730        )
13731    }
13732}
13733
13734impl ViewInputHandler for Editor {
13735    fn text_for_range(
13736        &mut self,
13737        range_utf16: Range<usize>,
13738        cx: &mut ViewContext<Self>,
13739    ) -> Option<String> {
13740        Some(
13741            self.buffer
13742                .read(cx)
13743                .read(cx)
13744                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13745                .collect(),
13746        )
13747    }
13748
13749    fn selected_text_range(
13750        &mut self,
13751        ignore_disabled_input: bool,
13752        cx: &mut ViewContext<Self>,
13753    ) -> Option<UTF16Selection> {
13754        // Prevent the IME menu from appearing when holding down an alphabetic key
13755        // while input is disabled.
13756        if !ignore_disabled_input && !self.input_enabled {
13757            return None;
13758        }
13759
13760        let selection = self.selections.newest::<OffsetUtf16>(cx);
13761        let range = selection.range();
13762
13763        Some(UTF16Selection {
13764            range: range.start.0..range.end.0,
13765            reversed: selection.reversed,
13766        })
13767    }
13768
13769    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13770        let snapshot = self.buffer.read(cx).read(cx);
13771        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13772        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13773    }
13774
13775    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13776        self.clear_highlights::<InputComposition>(cx);
13777        self.ime_transaction.take();
13778    }
13779
13780    fn replace_text_in_range(
13781        &mut self,
13782        range_utf16: Option<Range<usize>>,
13783        text: &str,
13784        cx: &mut ViewContext<Self>,
13785    ) {
13786        if !self.input_enabled {
13787            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13788            return;
13789        }
13790
13791        self.transact(cx, |this, cx| {
13792            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13793                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13794                Some(this.selection_replacement_ranges(range_utf16, cx))
13795            } else {
13796                this.marked_text_ranges(cx)
13797            };
13798
13799            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13800                let newest_selection_id = this.selections.newest_anchor().id;
13801                this.selections
13802                    .all::<OffsetUtf16>(cx)
13803                    .iter()
13804                    .zip(ranges_to_replace.iter())
13805                    .find_map(|(selection, range)| {
13806                        if selection.id == newest_selection_id {
13807                            Some(
13808                                (range.start.0 as isize - selection.head().0 as isize)
13809                                    ..(range.end.0 as isize - selection.head().0 as isize),
13810                            )
13811                        } else {
13812                            None
13813                        }
13814                    })
13815            });
13816
13817            cx.emit(EditorEvent::InputHandled {
13818                utf16_range_to_replace: range_to_replace,
13819                text: text.into(),
13820            });
13821
13822            if let Some(new_selected_ranges) = new_selected_ranges {
13823                this.change_selections(None, cx, |selections| {
13824                    selections.select_ranges(new_selected_ranges)
13825                });
13826                this.backspace(&Default::default(), cx);
13827            }
13828
13829            this.handle_input(text, cx);
13830        });
13831
13832        if let Some(transaction) = self.ime_transaction {
13833            self.buffer.update(cx, |buffer, cx| {
13834                buffer.group_until_transaction(transaction, cx);
13835            });
13836        }
13837
13838        self.unmark_text(cx);
13839    }
13840
13841    fn replace_and_mark_text_in_range(
13842        &mut self,
13843        range_utf16: Option<Range<usize>>,
13844        text: &str,
13845        new_selected_range_utf16: Option<Range<usize>>,
13846        cx: &mut ViewContext<Self>,
13847    ) {
13848        if !self.input_enabled {
13849            return;
13850        }
13851
13852        let transaction = self.transact(cx, |this, cx| {
13853            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13854                let snapshot = this.buffer.read(cx).read(cx);
13855                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13856                    for marked_range in &mut marked_ranges {
13857                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13858                        marked_range.start.0 += relative_range_utf16.start;
13859                        marked_range.start =
13860                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13861                        marked_range.end =
13862                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13863                    }
13864                }
13865                Some(marked_ranges)
13866            } else if let Some(range_utf16) = range_utf16 {
13867                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13868                Some(this.selection_replacement_ranges(range_utf16, cx))
13869            } else {
13870                None
13871            };
13872
13873            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13874                let newest_selection_id = this.selections.newest_anchor().id;
13875                this.selections
13876                    .all::<OffsetUtf16>(cx)
13877                    .iter()
13878                    .zip(ranges_to_replace.iter())
13879                    .find_map(|(selection, range)| {
13880                        if selection.id == newest_selection_id {
13881                            Some(
13882                                (range.start.0 as isize - selection.head().0 as isize)
13883                                    ..(range.end.0 as isize - selection.head().0 as isize),
13884                            )
13885                        } else {
13886                            None
13887                        }
13888                    })
13889            });
13890
13891            cx.emit(EditorEvent::InputHandled {
13892                utf16_range_to_replace: range_to_replace,
13893                text: text.into(),
13894            });
13895
13896            if let Some(ranges) = ranges_to_replace {
13897                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13898            }
13899
13900            let marked_ranges = {
13901                let snapshot = this.buffer.read(cx).read(cx);
13902                this.selections
13903                    .disjoint_anchors()
13904                    .iter()
13905                    .map(|selection| {
13906                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13907                    })
13908                    .collect::<Vec<_>>()
13909            };
13910
13911            if text.is_empty() {
13912                this.unmark_text(cx);
13913            } else {
13914                this.highlight_text::<InputComposition>(
13915                    marked_ranges.clone(),
13916                    HighlightStyle {
13917                        underline: Some(UnderlineStyle {
13918                            thickness: px(1.),
13919                            color: None,
13920                            wavy: false,
13921                        }),
13922                        ..Default::default()
13923                    },
13924                    cx,
13925                );
13926            }
13927
13928            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13929            let use_autoclose = this.use_autoclose;
13930            let use_auto_surround = this.use_auto_surround;
13931            this.set_use_autoclose(false);
13932            this.set_use_auto_surround(false);
13933            this.handle_input(text, cx);
13934            this.set_use_autoclose(use_autoclose);
13935            this.set_use_auto_surround(use_auto_surround);
13936
13937            if let Some(new_selected_range) = new_selected_range_utf16 {
13938                let snapshot = this.buffer.read(cx).read(cx);
13939                let new_selected_ranges = marked_ranges
13940                    .into_iter()
13941                    .map(|marked_range| {
13942                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13943                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13944                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13945                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13946                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13947                    })
13948                    .collect::<Vec<_>>();
13949
13950                drop(snapshot);
13951                this.change_selections(None, cx, |selections| {
13952                    selections.select_ranges(new_selected_ranges)
13953                });
13954            }
13955        });
13956
13957        self.ime_transaction = self.ime_transaction.or(transaction);
13958        if let Some(transaction) = self.ime_transaction {
13959            self.buffer.update(cx, |buffer, cx| {
13960                buffer.group_until_transaction(transaction, cx);
13961            });
13962        }
13963
13964        if self.text_highlights::<InputComposition>(cx).is_none() {
13965            self.ime_transaction.take();
13966        }
13967    }
13968
13969    fn bounds_for_range(
13970        &mut self,
13971        range_utf16: Range<usize>,
13972        element_bounds: gpui::Bounds<Pixels>,
13973        cx: &mut ViewContext<Self>,
13974    ) -> Option<gpui::Bounds<Pixels>> {
13975        let text_layout_details = self.text_layout_details(cx);
13976        let style = &text_layout_details.editor_style;
13977        let font_id = cx.text_system().resolve_font(&style.text.font());
13978        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13979        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13980
13981        let em_width = cx
13982            .text_system()
13983            .typographic_bounds(font_id, font_size, 'm')
13984            .unwrap()
13985            .size
13986            .width;
13987
13988        let snapshot = self.snapshot(cx);
13989        let scroll_position = snapshot.scroll_position();
13990        let scroll_left = scroll_position.x * em_width;
13991
13992        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13993        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13994            + self.gutter_dimensions.width;
13995        let y = line_height * (start.row().as_f32() - scroll_position.y);
13996
13997        Some(Bounds {
13998            origin: element_bounds.origin + point(x, y),
13999            size: size(em_width, line_height),
14000        })
14001    }
14002}
14003
14004trait SelectionExt {
14005    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14006    fn spanned_rows(
14007        &self,
14008        include_end_if_at_line_start: bool,
14009        map: &DisplaySnapshot,
14010    ) -> Range<MultiBufferRow>;
14011}
14012
14013impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14014    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14015        let start = self
14016            .start
14017            .to_point(&map.buffer_snapshot)
14018            .to_display_point(map);
14019        let end = self
14020            .end
14021            .to_point(&map.buffer_snapshot)
14022            .to_display_point(map);
14023        if self.reversed {
14024            end..start
14025        } else {
14026            start..end
14027        }
14028    }
14029
14030    fn spanned_rows(
14031        &self,
14032        include_end_if_at_line_start: bool,
14033        map: &DisplaySnapshot,
14034    ) -> Range<MultiBufferRow> {
14035        let start = self.start.to_point(&map.buffer_snapshot);
14036        let mut end = self.end.to_point(&map.buffer_snapshot);
14037        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14038            end.row -= 1;
14039        }
14040
14041        let buffer_start = map.prev_line_boundary(start).0;
14042        let buffer_end = map.next_line_boundary(end).0;
14043        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14044    }
14045}
14046
14047impl<T: InvalidationRegion> InvalidationStack<T> {
14048    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14049    where
14050        S: Clone + ToOffset,
14051    {
14052        while let Some(region) = self.last() {
14053            let all_selections_inside_invalidation_ranges =
14054                if selections.len() == region.ranges().len() {
14055                    selections
14056                        .iter()
14057                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14058                        .all(|(selection, invalidation_range)| {
14059                            let head = selection.head().to_offset(buffer);
14060                            invalidation_range.start <= head && invalidation_range.end >= head
14061                        })
14062                } else {
14063                    false
14064                };
14065
14066            if all_selections_inside_invalidation_ranges {
14067                break;
14068            } else {
14069                self.pop();
14070            }
14071        }
14072    }
14073}
14074
14075impl<T> Default for InvalidationStack<T> {
14076    fn default() -> Self {
14077        Self(Default::default())
14078    }
14079}
14080
14081impl<T> Deref for InvalidationStack<T> {
14082    type Target = Vec<T>;
14083
14084    fn deref(&self) -> &Self::Target {
14085        &self.0
14086    }
14087}
14088
14089impl<T> DerefMut for InvalidationStack<T> {
14090    fn deref_mut(&mut self) -> &mut Self::Target {
14091        &mut self.0
14092    }
14093}
14094
14095impl InvalidationRegion for SnippetState {
14096    fn ranges(&self) -> &[Range<Anchor>] {
14097        &self.ranges[self.active_index]
14098    }
14099}
14100
14101pub fn diagnostic_block_renderer(
14102    diagnostic: Diagnostic,
14103    max_message_rows: Option<u8>,
14104    allow_closing: bool,
14105    _is_valid: bool,
14106) -> RenderBlock {
14107    let (text_without_backticks, code_ranges) =
14108        highlight_diagnostic_message(&diagnostic, max_message_rows);
14109
14110    Box::new(move |cx: &mut BlockContext| {
14111        let group_id: SharedString = cx.block_id.to_string().into();
14112
14113        let mut text_style = cx.text_style().clone();
14114        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14115        let theme_settings = ThemeSettings::get_global(cx);
14116        text_style.font_family = theme_settings.buffer_font.family.clone();
14117        text_style.font_style = theme_settings.buffer_font.style;
14118        text_style.font_features = theme_settings.buffer_font.features.clone();
14119        text_style.font_weight = theme_settings.buffer_font.weight;
14120
14121        let multi_line_diagnostic = diagnostic.message.contains('\n');
14122
14123        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
14124            if multi_line_diagnostic {
14125                v_flex()
14126            } else {
14127                h_flex()
14128            }
14129            .when(allow_closing, |div| {
14130                div.children(diagnostic.is_primary.then(|| {
14131                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
14132                        .icon_color(Color::Muted)
14133                        .size(ButtonSize::Compact)
14134                        .style(ButtonStyle::Transparent)
14135                        .visible_on_hover(group_id.clone())
14136                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14137                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14138                }))
14139            })
14140            .child(
14141                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
14142                    .icon_color(Color::Muted)
14143                    .size(ButtonSize::Compact)
14144                    .style(ButtonStyle::Transparent)
14145                    .visible_on_hover(group_id.clone())
14146                    .on_click({
14147                        let message = diagnostic.message.clone();
14148                        move |_click, cx| {
14149                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14150                        }
14151                    })
14152                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14153            )
14154        };
14155
14156        let icon_size = buttons(&diagnostic, cx.block_id)
14157            .into_any_element()
14158            .layout_as_root(AvailableSpace::min_size(), cx);
14159
14160        h_flex()
14161            .id(cx.block_id)
14162            .group(group_id.clone())
14163            .relative()
14164            .size_full()
14165            .pl(cx.gutter_dimensions.width)
14166            .w(cx.max_width + cx.gutter_dimensions.width)
14167            .child(
14168                div()
14169                    .flex()
14170                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14171                    .flex_shrink(),
14172            )
14173            .child(buttons(&diagnostic, cx.block_id))
14174            .child(div().flex().flex_shrink_0().child(
14175                StyledText::new(text_without_backticks.clone()).with_highlights(
14176                    &text_style,
14177                    code_ranges.iter().map(|range| {
14178                        (
14179                            range.clone(),
14180                            HighlightStyle {
14181                                font_weight: Some(FontWeight::BOLD),
14182                                ..Default::default()
14183                            },
14184                        )
14185                    }),
14186                ),
14187            ))
14188            .into_any_element()
14189    })
14190}
14191
14192pub fn highlight_diagnostic_message(
14193    diagnostic: &Diagnostic,
14194    mut max_message_rows: Option<u8>,
14195) -> (SharedString, Vec<Range<usize>>) {
14196    let mut text_without_backticks = String::new();
14197    let mut code_ranges = Vec::new();
14198
14199    if let Some(source) = &diagnostic.source {
14200        text_without_backticks.push_str(source);
14201        code_ranges.push(0..source.len());
14202        text_without_backticks.push_str(": ");
14203    }
14204
14205    let mut prev_offset = 0;
14206    let mut in_code_block = false;
14207    let has_row_limit = max_message_rows.is_some();
14208    let mut newline_indices = diagnostic
14209        .message
14210        .match_indices('\n')
14211        .filter(|_| has_row_limit)
14212        .map(|(ix, _)| ix)
14213        .fuse()
14214        .peekable();
14215
14216    for (quote_ix, _) in diagnostic
14217        .message
14218        .match_indices('`')
14219        .chain([(diagnostic.message.len(), "")])
14220    {
14221        let mut first_newline_ix = None;
14222        let mut last_newline_ix = None;
14223        while let Some(newline_ix) = newline_indices.peek() {
14224            if *newline_ix < quote_ix {
14225                if first_newline_ix.is_none() {
14226                    first_newline_ix = Some(*newline_ix);
14227                }
14228                last_newline_ix = Some(*newline_ix);
14229
14230                if let Some(rows_left) = &mut max_message_rows {
14231                    if *rows_left == 0 {
14232                        break;
14233                    } else {
14234                        *rows_left -= 1;
14235                    }
14236                }
14237                let _ = newline_indices.next();
14238            } else {
14239                break;
14240            }
14241        }
14242        let prev_len = text_without_backticks.len();
14243        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14244        text_without_backticks.push_str(new_text);
14245        if in_code_block {
14246            code_ranges.push(prev_len..text_without_backticks.len());
14247        }
14248        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14249        in_code_block = !in_code_block;
14250        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14251            text_without_backticks.push_str("...");
14252            break;
14253        }
14254    }
14255
14256    (text_without_backticks.into(), code_ranges)
14257}
14258
14259fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14260    match severity {
14261        DiagnosticSeverity::ERROR => colors.error,
14262        DiagnosticSeverity::WARNING => colors.warning,
14263        DiagnosticSeverity::INFORMATION => colors.info,
14264        DiagnosticSeverity::HINT => colors.info,
14265        _ => colors.ignored,
14266    }
14267}
14268
14269pub fn styled_runs_for_code_label<'a>(
14270    label: &'a CodeLabel,
14271    syntax_theme: &'a theme::SyntaxTheme,
14272) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14273    let fade_out = HighlightStyle {
14274        fade_out: Some(0.35),
14275        ..Default::default()
14276    };
14277
14278    let mut prev_end = label.filter_range.end;
14279    label
14280        .runs
14281        .iter()
14282        .enumerate()
14283        .flat_map(move |(ix, (range, highlight_id))| {
14284            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14285                style
14286            } else {
14287                return Default::default();
14288            };
14289            let mut muted_style = style;
14290            muted_style.highlight(fade_out);
14291
14292            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14293            if range.start >= label.filter_range.end {
14294                if range.start > prev_end {
14295                    runs.push((prev_end..range.start, fade_out));
14296                }
14297                runs.push((range.clone(), muted_style));
14298            } else if range.end <= label.filter_range.end {
14299                runs.push((range.clone(), style));
14300            } else {
14301                runs.push((range.start..label.filter_range.end, style));
14302                runs.push((label.filter_range.end..range.end, muted_style));
14303            }
14304            prev_end = cmp::max(prev_end, range.end);
14305
14306            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14307                runs.push((prev_end..label.text.len(), fade_out));
14308            }
14309
14310            runs
14311        })
14312}
14313
14314pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14315    let mut prev_index = 0;
14316    let mut prev_codepoint: Option<char> = None;
14317    text.char_indices()
14318        .chain([(text.len(), '\0')])
14319        .filter_map(move |(index, codepoint)| {
14320            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14321            let is_boundary = index == text.len()
14322                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14323                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14324            if is_boundary {
14325                let chunk = &text[prev_index..index];
14326                prev_index = index;
14327                Some(chunk)
14328            } else {
14329                None
14330            }
14331        })
14332}
14333
14334pub trait RangeToAnchorExt: Sized {
14335    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14336
14337    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14338        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14339        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14340    }
14341}
14342
14343impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14344    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14345        let start_offset = self.start.to_offset(snapshot);
14346        let end_offset = self.end.to_offset(snapshot);
14347        if start_offset == end_offset {
14348            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14349        } else {
14350            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14351        }
14352    }
14353}
14354
14355pub trait RowExt {
14356    fn as_f32(&self) -> f32;
14357
14358    fn next_row(&self) -> Self;
14359
14360    fn previous_row(&self) -> Self;
14361
14362    fn minus(&self, other: Self) -> u32;
14363}
14364
14365impl RowExt for DisplayRow {
14366    fn as_f32(&self) -> f32 {
14367        self.0 as f32
14368    }
14369
14370    fn next_row(&self) -> Self {
14371        Self(self.0 + 1)
14372    }
14373
14374    fn previous_row(&self) -> Self {
14375        Self(self.0.saturating_sub(1))
14376    }
14377
14378    fn minus(&self, other: Self) -> u32 {
14379        self.0 - other.0
14380    }
14381}
14382
14383impl RowExt for MultiBufferRow {
14384    fn as_f32(&self) -> f32 {
14385        self.0 as f32
14386    }
14387
14388    fn next_row(&self) -> Self {
14389        Self(self.0 + 1)
14390    }
14391
14392    fn previous_row(&self) -> Self {
14393        Self(self.0.saturating_sub(1))
14394    }
14395
14396    fn minus(&self, other: Self) -> u32 {
14397        self.0 - other.0
14398    }
14399}
14400
14401trait RowRangeExt {
14402    type Row;
14403
14404    fn len(&self) -> usize;
14405
14406    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14407}
14408
14409impl RowRangeExt for Range<MultiBufferRow> {
14410    type Row = MultiBufferRow;
14411
14412    fn len(&self) -> usize {
14413        (self.end.0 - self.start.0) as usize
14414    }
14415
14416    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14417        (self.start.0..self.end.0).map(MultiBufferRow)
14418    }
14419}
14420
14421impl RowRangeExt for Range<DisplayRow> {
14422    type Row = DisplayRow;
14423
14424    fn len(&self) -> usize {
14425        (self.end.0 - self.start.0) as usize
14426    }
14427
14428    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14429        (self.start.0..self.end.0).map(DisplayRow)
14430    }
14431}
14432
14433fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14434    if hunk.diff_base_byte_range.is_empty() {
14435        DiffHunkStatus::Added
14436    } else if hunk.row_range.is_empty() {
14437        DiffHunkStatus::Removed
14438    } else {
14439        DiffHunkStatus::Modified
14440    }
14441}
14442
14443/// If select range has more than one line, we
14444/// just point the cursor to range.start.
14445fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14446    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14447        range
14448    } else {
14449        range.start..range.start
14450    }
14451}