editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   52pub(crate) use actions::*;
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use task::{ResolvedTask, TaskTemplate, TaskVariables};
  106
  107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  108pub use lsp::CompletionContext;
  109use lsp::{
  110    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  111    LanguageServerId,
  112};
  113use mouse_context_menu::MouseContextMenu;
  114use movement::TextLayoutDetails;
  115pub use multi_buffer::{
  116    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  117    ToPoint,
  118};
  119use multi_buffer::{
  120    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  121};
  122use ordered_float::OrderedFloat;
  123use parking_lot::{Mutex, RwLock};
  124use project::{
  125    lsp_store::FormatTrigger,
  126    project_settings::{GitGutterSetting, ProjectSettings},
  127    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  128    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  129};
  130use rand::prelude::*;
  131use rpc::{proto::*, ErrorExt};
  132use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  133use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  134use serde::{Deserialize, Serialize};
  135use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  136use smallvec::SmallVec;
  137use snippet::Snippet;
  138use std::{
  139    any::TypeId,
  140    borrow::Cow,
  141    cell::RefCell,
  142    cmp::{self, Ordering, Reverse},
  143    mem,
  144    num::NonZeroU32,
  145    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  146    path::{Path, PathBuf},
  147    rc::Rc,
  148    sync::Arc,
  149    time::{Duration, Instant},
  150};
  151pub use sum_tree::Bias;
  152use sum_tree::TreeMap;
  153use text::{BufferId, OffsetUtf16, Rope};
  154use theme::{
  155    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  156    ThemeColors, ThemeSettings,
  157};
  158use ui::{
  159    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  160    ListItem, Popover, PopoverMenuHandle, Tooltip,
  161};
  162use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  163use workspace::item::{ItemHandle, PreviewTabsSettings};
  164use workspace::notifications::{DetachAndPromptErr, NotificationId};
  165use workspace::{
  166    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  167};
  168use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  169
  170use crate::hover_links::find_url;
  171use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  172
  173pub const FILE_HEADER_HEIGHT: u32 = 1;
  174pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  175pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  176pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  177const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  178const MAX_LINE_LEN: usize = 1024;
  179const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  180const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  181pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  182#[doc(hidden)]
  183pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  184#[doc(hidden)]
  185pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  186
  187pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  188pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  189
  190pub fn render_parsed_markdown(
  191    element_id: impl Into<ElementId>,
  192    parsed: &language::ParsedMarkdown,
  193    editor_style: &EditorStyle,
  194    workspace: Option<WeakView<Workspace>>,
  195    cx: &mut WindowContext,
  196) -> InteractiveText {
  197    let code_span_background_color = cx
  198        .theme()
  199        .colors()
  200        .editor_document_highlight_read_background;
  201
  202    let highlights = gpui::combine_highlights(
  203        parsed.highlights.iter().filter_map(|(range, highlight)| {
  204            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  205            Some((range.clone(), highlight))
  206        }),
  207        parsed
  208            .regions
  209            .iter()
  210            .zip(&parsed.region_ranges)
  211            .filter_map(|(region, range)| {
  212                if region.code {
  213                    Some((
  214                        range.clone(),
  215                        HighlightStyle {
  216                            background_color: Some(code_span_background_color),
  217                            ..Default::default()
  218                        },
  219                    ))
  220                } else {
  221                    None
  222                }
  223            }),
  224    );
  225
  226    let mut links = Vec::new();
  227    let mut link_ranges = Vec::new();
  228    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  229        if let Some(link) = region.link.clone() {
  230            links.push(link);
  231            link_ranges.push(range.clone());
  232        }
  233    }
  234
  235    InteractiveText::new(
  236        element_id,
  237        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  238    )
  239    .on_click(link_ranges, move |clicked_range_ix, cx| {
  240        match &links[clicked_range_ix] {
  241            markdown::Link::Web { url } => cx.open_url(url),
  242            markdown::Link::Path { path } => {
  243                if let Some(workspace) = &workspace {
  244                    _ = workspace.update(cx, |workspace, cx| {
  245                        workspace.open_abs_path(path.clone(), false, cx).detach();
  246                    });
  247                }
  248            }
  249        }
  250    })
  251}
  252
  253#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  254pub(crate) enum InlayId {
  255    Suggestion(usize),
  256    Hint(usize),
  257}
  258
  259impl InlayId {
  260    fn id(&self) -> usize {
  261        match self {
  262            Self::Suggestion(id) => *id,
  263            Self::Hint(id) => *id,
  264        }
  265    }
  266}
  267
  268enum DiffRowHighlight {}
  269enum DocumentHighlightRead {}
  270enum DocumentHighlightWrite {}
  271enum InputComposition {}
  272
  273#[derive(Copy, Clone, PartialEq, Eq)]
  274pub enum Direction {
  275    Prev,
  276    Next,
  277}
  278
  279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  280pub enum Navigated {
  281    Yes,
  282    No,
  283}
  284
  285impl Navigated {
  286    pub fn from_bool(yes: bool) -> Navigated {
  287        if yes {
  288            Navigated::Yes
  289        } else {
  290            Navigated::No
  291        }
  292    }
  293}
  294
  295pub fn init_settings(cx: &mut AppContext) {
  296    EditorSettings::register(cx);
  297}
  298
  299pub fn init(cx: &mut AppContext) {
  300    init_settings(cx);
  301
  302    workspace::register_project_item::<Editor>(cx);
  303    workspace::FollowableViewRegistry::register::<Editor>(cx);
  304    workspace::register_serializable_item::<Editor>(cx);
  305
  306    cx.observe_new_views(
  307        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  308            workspace.register_action(Editor::new_file);
  309            workspace.register_action(Editor::new_file_vertical);
  310            workspace.register_action(Editor::new_file_horizontal);
  311        },
  312    )
  313    .detach();
  314
  315    cx.on_action(move |_: &workspace::NewFile, cx| {
  316        let app_state = workspace::AppState::global(cx);
  317        if let Some(app_state) = app_state.upgrade() {
  318            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  319                Editor::new_file(workspace, &Default::default(), cx)
  320            })
  321            .detach();
  322        }
  323    });
  324    cx.on_action(move |_: &workspace::NewWindow, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  328                Editor::new_file(workspace, &Default::default(), cx)
  329            })
  330            .detach();
  331        }
  332    });
  333}
  334
  335pub struct SearchWithinRange;
  336
  337trait InvalidationRegion {
  338    fn ranges(&self) -> &[Range<Anchor>];
  339}
  340
  341#[derive(Clone, Debug, PartialEq)]
  342pub enum SelectPhase {
  343    Begin {
  344        position: DisplayPoint,
  345        add: bool,
  346        click_count: usize,
  347    },
  348    BeginColumnar {
  349        position: DisplayPoint,
  350        reset: bool,
  351        goal_column: u32,
  352    },
  353    Extend {
  354        position: DisplayPoint,
  355        click_count: usize,
  356    },
  357    Update {
  358        position: DisplayPoint,
  359        goal_column: u32,
  360        scroll_delta: gpui::Point<f32>,
  361    },
  362    End,
  363}
  364
  365#[derive(Clone, Debug)]
  366pub enum SelectMode {
  367    Character,
  368    Word(Range<Anchor>),
  369    Line(Range<Anchor>),
  370    All,
  371}
  372
  373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  374pub enum EditorMode {
  375    SingleLine { auto_width: bool },
  376    AutoHeight { max_lines: usize },
  377    Full,
  378}
  379
  380#[derive(Copy, Clone, Debug)]
  381pub enum SoftWrap {
  382    /// Prefer not to wrap at all.
  383    ///
  384    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  385    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  386    GitDiff,
  387    /// Prefer a single line generally, unless an overly long line is encountered.
  388    None,
  389    /// Soft wrap lines that exceed the editor width.
  390    EditorWidth,
  391    /// Soft wrap lines at the preferred line length.
  392    Column(u32),
  393    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  394    Bounded(u32),
  395}
  396
  397#[derive(Clone)]
  398pub struct EditorStyle {
  399    pub background: Hsla,
  400    pub local_player: PlayerColor,
  401    pub text: TextStyle,
  402    pub scrollbar_width: Pixels,
  403    pub syntax: Arc<SyntaxTheme>,
  404    pub status: StatusColors,
  405    pub inlay_hints_style: HighlightStyle,
  406    pub suggestions_style: HighlightStyle,
  407    pub unnecessary_code_fade: f32,
  408}
  409
  410impl Default for EditorStyle {
  411    fn default() -> Self {
  412        Self {
  413            background: Hsla::default(),
  414            local_player: PlayerColor::default(),
  415            text: TextStyle::default(),
  416            scrollbar_width: Pixels::default(),
  417            syntax: Default::default(),
  418            // HACK: Status colors don't have a real default.
  419            // We should look into removing the status colors from the editor
  420            // style and retrieve them directly from the theme.
  421            status: StatusColors::dark(),
  422            inlay_hints_style: HighlightStyle::default(),
  423            suggestions_style: HighlightStyle::default(),
  424            unnecessary_code_fade: Default::default(),
  425        }
  426    }
  427}
  428
  429pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  430    let show_background = all_language_settings(None, cx)
  431        .language(None)
  432        .inlay_hints
  433        .show_background;
  434
  435    HighlightStyle {
  436        color: Some(cx.theme().status().hint),
  437        background_color: show_background.then(|| cx.theme().status().hint_background),
  438        ..HighlightStyle::default()
  439    }
  440}
  441
  442type CompletionId = usize;
  443
  444#[derive(Clone, Debug)]
  445struct CompletionState {
  446    // render_inlay_ids represents the inlay hints that are inserted
  447    // for rendering the inline completions. They may be discontinuous
  448    // in the event that the completion provider returns some intersection
  449    // with the existing content.
  450    render_inlay_ids: Vec<InlayId>,
  451    // text is the resulting rope that is inserted when the user accepts a completion.
  452    text: Rope,
  453    // position is the position of the cursor when the completion was triggered.
  454    position: multi_buffer::Anchor,
  455    // delete_range is the range of text that this completion state covers.
  456    // if the completion is accepted, this range should be deleted.
  457    delete_range: Option<Range<multi_buffer::Anchor>>,
  458}
  459
  460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  461struct EditorActionId(usize);
  462
  463impl EditorActionId {
  464    pub fn post_inc(&mut self) -> Self {
  465        let answer = self.0;
  466
  467        *self = Self(answer + 1);
  468
  469        Self(answer)
  470    }
  471}
  472
  473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  475
  476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  478
  479#[derive(Default)]
  480struct ScrollbarMarkerState {
  481    scrollbar_size: Size<Pixels>,
  482    dirty: bool,
  483    markers: Arc<[PaintQuad]>,
  484    pending_refresh: Option<Task<Result<()>>>,
  485}
  486
  487impl ScrollbarMarkerState {
  488    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  489        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  490    }
  491}
  492
  493#[derive(Clone, Debug)]
  494struct RunnableTasks {
  495    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  496    offset: MultiBufferOffset,
  497    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  498    column: u32,
  499    // Values of all named captures, including those starting with '_'
  500    extra_variables: HashMap<String, String>,
  501    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  502    context_range: Range<BufferOffset>,
  503}
  504
  505#[derive(Clone)]
  506struct ResolvedTasks {
  507    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  508    position: Anchor,
  509}
  510#[derive(Copy, Clone, Debug)]
  511struct MultiBufferOffset(usize);
  512#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  513struct BufferOffset(usize);
  514
  515// Addons allow storing per-editor state in other crates (e.g. Vim)
  516pub trait Addon: 'static {
  517    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  518
  519    fn to_any(&self) -> &dyn std::any::Any;
  520}
  521
  522/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  523///
  524/// See the [module level documentation](self) for more information.
  525pub struct Editor {
  526    focus_handle: FocusHandle,
  527    last_focused_descendant: Option<WeakFocusHandle>,
  528    /// The text buffer being edited
  529    buffer: Model<MultiBuffer>,
  530    /// Map of how text in the buffer should be displayed.
  531    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  532    pub display_map: Model<DisplayMap>,
  533    pub selections: SelectionsCollection,
  534    pub scroll_manager: ScrollManager,
  535    /// When inline assist editors are linked, they all render cursors because
  536    /// typing enters text into each of them, even the ones that aren't focused.
  537    pub(crate) show_cursor_when_unfocused: bool,
  538    columnar_selection_tail: Option<Anchor>,
  539    add_selections_state: Option<AddSelectionsState>,
  540    select_next_state: Option<SelectNextState>,
  541    select_prev_state: Option<SelectNextState>,
  542    selection_history: SelectionHistory,
  543    autoclose_regions: Vec<AutocloseRegion>,
  544    snippet_stack: InvalidationStack<SnippetState>,
  545    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  546    ime_transaction: Option<TransactionId>,
  547    active_diagnostics: Option<ActiveDiagnosticGroup>,
  548    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  549    project: Option<Model<Project>>,
  550    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  551    completion_provider: Option<Box<dyn CompletionProvider>>,
  552    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  553    blink_manager: Model<BlinkManager>,
  554    show_cursor_names: bool,
  555    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  556    pub show_local_selections: bool,
  557    mode: EditorMode,
  558    show_breadcrumbs: bool,
  559    show_gutter: bool,
  560    show_line_numbers: Option<bool>,
  561    use_relative_line_numbers: Option<bool>,
  562    show_git_diff_gutter: Option<bool>,
  563    show_code_actions: Option<bool>,
  564    show_runnables: Option<bool>,
  565    show_wrap_guides: Option<bool>,
  566    show_indent_guides: Option<bool>,
  567    placeholder_text: Option<Arc<str>>,
  568    highlight_order: usize,
  569    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  570    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  571    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  572    scrollbar_marker_state: ScrollbarMarkerState,
  573    active_indent_guides_state: ActiveIndentGuidesState,
  574    nav_history: Option<ItemNavHistory>,
  575    context_menu: RwLock<Option<ContextMenu>>,
  576    mouse_context_menu: Option<MouseContextMenu>,
  577    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  578    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  579    signature_help_state: SignatureHelpState,
  580    auto_signature_help: Option<bool>,
  581    find_all_references_task_sources: Vec<Anchor>,
  582    next_completion_id: CompletionId,
  583    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  584    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  585    code_actions_task: Option<Task<Result<()>>>,
  586    document_highlights_task: Option<Task<()>>,
  587    linked_editing_range_task: Option<Task<Option<()>>>,
  588    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  589    pending_rename: Option<RenameState>,
  590    searchable: bool,
  591    cursor_shape: CursorShape,
  592    current_line_highlight: Option<CurrentLineHighlight>,
  593    collapse_matches: bool,
  594    autoindent_mode: Option<AutoindentMode>,
  595    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  596    input_enabled: bool,
  597    use_modal_editing: bool,
  598    read_only: bool,
  599    leader_peer_id: Option<PeerId>,
  600    remote_id: Option<ViewId>,
  601    hover_state: HoverState,
  602    gutter_hovered: bool,
  603    hovered_link_state: Option<HoveredLinkState>,
  604    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  605    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  606    active_inline_completion: Option<CompletionState>,
  607    // enable_inline_completions is a switch that Vim can use to disable
  608    // inline completions based on its mode.
  609    enable_inline_completions: bool,
  610    show_inline_completions_override: Option<bool>,
  611    inlay_hint_cache: InlayHintCache,
  612    expanded_hunks: ExpandedHunks,
  613    next_inlay_id: usize,
  614    _subscriptions: Vec<Subscription>,
  615    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  616    gutter_dimensions: GutterDimensions,
  617    style: Option<EditorStyle>,
  618    next_editor_action_id: EditorActionId,
  619    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  620    use_autoclose: bool,
  621    use_auto_surround: bool,
  622    auto_replace_emoji_shortcode: bool,
  623    show_git_blame_gutter: bool,
  624    show_git_blame_inline: bool,
  625    show_git_blame_inline_delay_task: Option<Task<()>>,
  626    git_blame_inline_enabled: bool,
  627    serialize_dirty_buffers: bool,
  628    show_selection_menu: Option<bool>,
  629    blame: Option<Model<GitBlame>>,
  630    blame_subscription: Option<Subscription>,
  631    custom_context_menu: Option<
  632        Box<
  633            dyn 'static
  634                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  635        >,
  636    >,
  637    last_bounds: Option<Bounds<Pixels>>,
  638    expect_bounds_change: Option<Bounds<Pixels>>,
  639    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  640    tasks_update_task: Option<Task<()>>,
  641    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  642    file_header_size: u32,
  643    breadcrumb_header: Option<String>,
  644    focused_block: Option<FocusedBlock>,
  645    next_scroll_position: NextScrollCursorCenterTopBottom,
  646    addons: HashMap<TypeId, Box<dyn Addon>>,
  647    _scroll_cursor_center_top_bottom_task: Task<()>,
  648}
  649
  650#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  651enum NextScrollCursorCenterTopBottom {
  652    #[default]
  653    Center,
  654    Top,
  655    Bottom,
  656}
  657
  658impl NextScrollCursorCenterTopBottom {
  659    fn next(&self) -> Self {
  660        match self {
  661            Self::Center => Self::Top,
  662            Self::Top => Self::Bottom,
  663            Self::Bottom => Self::Center,
  664        }
  665    }
  666}
  667
  668#[derive(Clone)]
  669pub struct EditorSnapshot {
  670    pub mode: EditorMode,
  671    show_gutter: bool,
  672    show_line_numbers: Option<bool>,
  673    show_git_diff_gutter: Option<bool>,
  674    show_code_actions: Option<bool>,
  675    show_runnables: Option<bool>,
  676    git_blame_gutter_max_author_length: Option<usize>,
  677    pub display_snapshot: DisplaySnapshot,
  678    pub placeholder_text: Option<Arc<str>>,
  679    is_focused: bool,
  680    scroll_anchor: ScrollAnchor,
  681    ongoing_scroll: OngoingScroll,
  682    current_line_highlight: CurrentLineHighlight,
  683    gutter_hovered: bool,
  684}
  685
  686const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  687
  688#[derive(Default, Debug, Clone, Copy)]
  689pub struct GutterDimensions {
  690    pub left_padding: Pixels,
  691    pub right_padding: Pixels,
  692    pub width: Pixels,
  693    pub margin: Pixels,
  694    pub git_blame_entries_width: Option<Pixels>,
  695}
  696
  697impl GutterDimensions {
  698    /// The full width of the space taken up by the gutter.
  699    pub fn full_width(&self) -> Pixels {
  700        self.margin + self.width
  701    }
  702
  703    /// The width of the space reserved for the fold indicators,
  704    /// use alongside 'justify_end' and `gutter_width` to
  705    /// right align content with the line numbers
  706    pub fn fold_area_width(&self) -> Pixels {
  707        self.margin + self.right_padding
  708    }
  709}
  710
  711#[derive(Debug)]
  712pub struct RemoteSelection {
  713    pub replica_id: ReplicaId,
  714    pub selection: Selection<Anchor>,
  715    pub cursor_shape: CursorShape,
  716    pub peer_id: PeerId,
  717    pub line_mode: bool,
  718    pub participant_index: Option<ParticipantIndex>,
  719    pub user_name: Option<SharedString>,
  720}
  721
  722#[derive(Clone, Debug)]
  723struct SelectionHistoryEntry {
  724    selections: Arc<[Selection<Anchor>]>,
  725    select_next_state: Option<SelectNextState>,
  726    select_prev_state: Option<SelectNextState>,
  727    add_selections_state: Option<AddSelectionsState>,
  728}
  729
  730enum SelectionHistoryMode {
  731    Normal,
  732    Undoing,
  733    Redoing,
  734}
  735
  736#[derive(Clone, PartialEq, Eq, Hash)]
  737struct HoveredCursor {
  738    replica_id: u16,
  739    selection_id: usize,
  740}
  741
  742impl Default for SelectionHistoryMode {
  743    fn default() -> Self {
  744        Self::Normal
  745    }
  746}
  747
  748#[derive(Default)]
  749struct SelectionHistory {
  750    #[allow(clippy::type_complexity)]
  751    selections_by_transaction:
  752        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  753    mode: SelectionHistoryMode,
  754    undo_stack: VecDeque<SelectionHistoryEntry>,
  755    redo_stack: VecDeque<SelectionHistoryEntry>,
  756}
  757
  758impl SelectionHistory {
  759    fn insert_transaction(
  760        &mut self,
  761        transaction_id: TransactionId,
  762        selections: Arc<[Selection<Anchor>]>,
  763    ) {
  764        self.selections_by_transaction
  765            .insert(transaction_id, (selections, None));
  766    }
  767
  768    #[allow(clippy::type_complexity)]
  769    fn transaction(
  770        &self,
  771        transaction_id: TransactionId,
  772    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  773        self.selections_by_transaction.get(&transaction_id)
  774    }
  775
  776    #[allow(clippy::type_complexity)]
  777    fn transaction_mut(
  778        &mut self,
  779        transaction_id: TransactionId,
  780    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  781        self.selections_by_transaction.get_mut(&transaction_id)
  782    }
  783
  784    fn push(&mut self, entry: SelectionHistoryEntry) {
  785        if !entry.selections.is_empty() {
  786            match self.mode {
  787                SelectionHistoryMode::Normal => {
  788                    self.push_undo(entry);
  789                    self.redo_stack.clear();
  790                }
  791                SelectionHistoryMode::Undoing => self.push_redo(entry),
  792                SelectionHistoryMode::Redoing => self.push_undo(entry),
  793            }
  794        }
  795    }
  796
  797    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  798        if self
  799            .undo_stack
  800            .back()
  801            .map_or(true, |e| e.selections != entry.selections)
  802        {
  803            self.undo_stack.push_back(entry);
  804            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  805                self.undo_stack.pop_front();
  806            }
  807        }
  808    }
  809
  810    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  811        if self
  812            .redo_stack
  813            .back()
  814            .map_or(true, |e| e.selections != entry.selections)
  815        {
  816            self.redo_stack.push_back(entry);
  817            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  818                self.redo_stack.pop_front();
  819            }
  820        }
  821    }
  822}
  823
  824struct RowHighlight {
  825    index: usize,
  826    range: Range<Anchor>,
  827    color: Hsla,
  828    should_autoscroll: bool,
  829}
  830
  831#[derive(Clone, Debug)]
  832struct AddSelectionsState {
  833    above: bool,
  834    stack: Vec<usize>,
  835}
  836
  837#[derive(Clone)]
  838struct SelectNextState {
  839    query: AhoCorasick,
  840    wordwise: bool,
  841    done: bool,
  842}
  843
  844impl std::fmt::Debug for SelectNextState {
  845    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  846        f.debug_struct(std::any::type_name::<Self>())
  847            .field("wordwise", &self.wordwise)
  848            .field("done", &self.done)
  849            .finish()
  850    }
  851}
  852
  853#[derive(Debug)]
  854struct AutocloseRegion {
  855    selection_id: usize,
  856    range: Range<Anchor>,
  857    pair: BracketPair,
  858}
  859
  860#[derive(Debug)]
  861struct SnippetState {
  862    ranges: Vec<Vec<Range<Anchor>>>,
  863    active_index: usize,
  864}
  865
  866#[doc(hidden)]
  867pub struct RenameState {
  868    pub range: Range<Anchor>,
  869    pub old_name: Arc<str>,
  870    pub editor: View<Editor>,
  871    block_id: CustomBlockId,
  872}
  873
  874struct InvalidationStack<T>(Vec<T>);
  875
  876struct RegisteredInlineCompletionProvider {
  877    provider: Arc<dyn InlineCompletionProviderHandle>,
  878    _subscription: Subscription,
  879}
  880
  881enum ContextMenu {
  882    Completions(CompletionsMenu),
  883    CodeActions(CodeActionsMenu),
  884}
  885
  886impl ContextMenu {
  887    fn select_first(
  888        &mut self,
  889        provider: Option<&dyn CompletionProvider>,
  890        cx: &mut ViewContext<Editor>,
  891    ) -> bool {
  892        if self.visible() {
  893            match self {
  894                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  895                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  896            }
  897            true
  898        } else {
  899            false
  900        }
  901    }
  902
  903    fn select_prev(
  904        &mut self,
  905        provider: Option<&dyn CompletionProvider>,
  906        cx: &mut ViewContext<Editor>,
  907    ) -> bool {
  908        if self.visible() {
  909            match self {
  910                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_next(
  920        &mut self,
  921        provider: Option<&dyn CompletionProvider>,
  922        cx: &mut ViewContext<Editor>,
  923    ) -> bool {
  924        if self.visible() {
  925            match self {
  926                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_last(
  936        &mut self,
  937        provider: Option<&dyn CompletionProvider>,
  938        cx: &mut ViewContext<Editor>,
  939    ) -> bool {
  940        if self.visible() {
  941            match self {
  942                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn visible(&self) -> bool {
  952        match self {
  953            ContextMenu::Completions(menu) => menu.visible(),
  954            ContextMenu::CodeActions(menu) => menu.visible(),
  955        }
  956    }
  957
  958    fn render(
  959        &self,
  960        cursor_position: DisplayPoint,
  961        style: &EditorStyle,
  962        max_height: Pixels,
  963        workspace: Option<WeakView<Workspace>>,
  964        cx: &mut ViewContext<Editor>,
  965    ) -> (ContextMenuOrigin, AnyElement) {
  966        match self {
  967            ContextMenu::Completions(menu) => (
  968                ContextMenuOrigin::EditorPoint(cursor_position),
  969                menu.render(style, max_height, workspace, cx),
  970            ),
  971            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  972        }
  973    }
  974}
  975
  976enum ContextMenuOrigin {
  977    EditorPoint(DisplayPoint),
  978    GutterIndicator(DisplayRow),
  979}
  980
  981#[derive(Clone)]
  982struct CompletionsMenu {
  983    id: CompletionId,
  984    sort_completions: bool,
  985    initial_position: Anchor,
  986    buffer: Model<Buffer>,
  987    completions: Arc<RwLock<Box<[Completion]>>>,
  988    match_candidates: Arc<[StringMatchCandidate]>,
  989    matches: Arc<[StringMatch]>,
  990    selected_item: usize,
  991    scroll_handle: UniformListScrollHandle,
  992    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  993}
  994
  995impl CompletionsMenu {
  996    fn select_first(
  997        &mut self,
  998        provider: Option<&dyn CompletionProvider>,
  999        cx: &mut ViewContext<Editor>,
 1000    ) {
 1001        self.selected_item = 0;
 1002        self.scroll_handle.scroll_to_item(self.selected_item);
 1003        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1004        cx.notify();
 1005    }
 1006
 1007    fn select_prev(
 1008        &mut self,
 1009        provider: Option<&dyn CompletionProvider>,
 1010        cx: &mut ViewContext<Editor>,
 1011    ) {
 1012        if self.selected_item > 0 {
 1013            self.selected_item -= 1;
 1014        } else {
 1015            self.selected_item = self.matches.len() - 1;
 1016        }
 1017        self.scroll_handle.scroll_to_item(self.selected_item);
 1018        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1019        cx.notify();
 1020    }
 1021
 1022    fn select_next(
 1023        &mut self,
 1024        provider: Option<&dyn CompletionProvider>,
 1025        cx: &mut ViewContext<Editor>,
 1026    ) {
 1027        if self.selected_item + 1 < self.matches.len() {
 1028            self.selected_item += 1;
 1029        } else {
 1030            self.selected_item = 0;
 1031        }
 1032        self.scroll_handle.scroll_to_item(self.selected_item);
 1033        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1034        cx.notify();
 1035    }
 1036
 1037    fn select_last(
 1038        &mut self,
 1039        provider: Option<&dyn CompletionProvider>,
 1040        cx: &mut ViewContext<Editor>,
 1041    ) {
 1042        self.selected_item = self.matches.len() - 1;
 1043        self.scroll_handle.scroll_to_item(self.selected_item);
 1044        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1045        cx.notify();
 1046    }
 1047
 1048    fn pre_resolve_completion_documentation(
 1049        buffer: Model<Buffer>,
 1050        completions: Arc<RwLock<Box<[Completion]>>>,
 1051        matches: Arc<[StringMatch]>,
 1052        editor: &Editor,
 1053        cx: &mut ViewContext<Editor>,
 1054    ) -> Task<()> {
 1055        let settings = EditorSettings::get_global(cx);
 1056        if !settings.show_completion_documentation {
 1057            return Task::ready(());
 1058        }
 1059
 1060        let Some(provider) = editor.completion_provider.as_ref() else {
 1061            return Task::ready(());
 1062        };
 1063
 1064        let resolve_task = provider.resolve_completions(
 1065            buffer,
 1066            matches.iter().map(|m| m.candidate_id).collect(),
 1067            completions.clone(),
 1068            cx,
 1069        );
 1070
 1071        cx.spawn(move |this, mut cx| async move {
 1072            if let Some(true) = resolve_task.await.log_err() {
 1073                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1074            }
 1075        })
 1076    }
 1077
 1078    fn attempt_resolve_selected_completion_documentation(
 1079        &mut self,
 1080        provider: Option<&dyn CompletionProvider>,
 1081        cx: &mut ViewContext<Editor>,
 1082    ) {
 1083        let settings = EditorSettings::get_global(cx);
 1084        if !settings.show_completion_documentation {
 1085            return;
 1086        }
 1087
 1088        let completion_index = self.matches[self.selected_item].candidate_id;
 1089        let Some(provider) = provider else {
 1090            return;
 1091        };
 1092
 1093        let resolve_task = provider.resolve_completions(
 1094            self.buffer.clone(),
 1095            vec![completion_index],
 1096            self.completions.clone(),
 1097            cx,
 1098        );
 1099
 1100        let delay_ms =
 1101            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1102        let delay = Duration::from_millis(delay_ms);
 1103
 1104        self.selected_completion_documentation_resolve_debounce
 1105            .lock()
 1106            .fire_new(delay, cx, |_, cx| {
 1107                cx.spawn(move |this, mut cx| async move {
 1108                    if let Some(true) = resolve_task.await.log_err() {
 1109                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1110                    }
 1111                })
 1112            });
 1113    }
 1114
 1115    fn visible(&self) -> bool {
 1116        !self.matches.is_empty()
 1117    }
 1118
 1119    fn render(
 1120        &self,
 1121        style: &EditorStyle,
 1122        max_height: Pixels,
 1123        workspace: Option<WeakView<Workspace>>,
 1124        cx: &mut ViewContext<Editor>,
 1125    ) -> AnyElement {
 1126        let settings = EditorSettings::get_global(cx);
 1127        let show_completion_documentation = settings.show_completion_documentation;
 1128
 1129        let widest_completion_ix = self
 1130            .matches
 1131            .iter()
 1132            .enumerate()
 1133            .max_by_key(|(_, mat)| {
 1134                let completions = self.completions.read();
 1135                let completion = &completions[mat.candidate_id];
 1136                let documentation = &completion.documentation;
 1137
 1138                let mut len = completion.label.text.chars().count();
 1139                if let Some(Documentation::SingleLine(text)) = documentation {
 1140                    if show_completion_documentation {
 1141                        len += text.chars().count();
 1142                    }
 1143                }
 1144
 1145                len
 1146            })
 1147            .map(|(ix, _)| ix);
 1148
 1149        let completions = self.completions.clone();
 1150        let matches = self.matches.clone();
 1151        let selected_item = self.selected_item;
 1152        let style = style.clone();
 1153
 1154        let multiline_docs = if show_completion_documentation {
 1155            let mat = &self.matches[selected_item];
 1156            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1157                Some(Documentation::MultiLinePlainText(text)) => {
 1158                    Some(div().child(SharedString::from(text.clone())))
 1159                }
 1160                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1161                    Some(div().child(render_parsed_markdown(
 1162                        "completions_markdown",
 1163                        parsed,
 1164                        &style,
 1165                        workspace,
 1166                        cx,
 1167                    )))
 1168                }
 1169                _ => None,
 1170            };
 1171            multiline_docs.map(|div| {
 1172                div.id("multiline_docs")
 1173                    .max_h(max_height)
 1174                    .flex_1()
 1175                    .px_1p5()
 1176                    .py_1()
 1177                    .min_w(px(260.))
 1178                    .max_w(px(640.))
 1179                    .w(px(500.))
 1180                    .overflow_y_scroll()
 1181                    .occlude()
 1182            })
 1183        } else {
 1184            None
 1185        };
 1186
 1187        let list = uniform_list(
 1188            cx.view().clone(),
 1189            "completions",
 1190            matches.len(),
 1191            move |_editor, range, cx| {
 1192                let start_ix = range.start;
 1193                let completions_guard = completions.read();
 1194
 1195                matches[range]
 1196                    .iter()
 1197                    .enumerate()
 1198                    .map(|(ix, mat)| {
 1199                        let item_ix = start_ix + ix;
 1200                        let candidate_id = mat.candidate_id;
 1201                        let completion = &completions_guard[candidate_id];
 1202
 1203                        let documentation = if show_completion_documentation {
 1204                            &completion.documentation
 1205                        } else {
 1206                            &None
 1207                        };
 1208
 1209                        let highlights = gpui::combine_highlights(
 1210                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1211                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1212                                |(range, mut highlight)| {
 1213                                    // Ignore font weight for syntax highlighting, as we'll use it
 1214                                    // for fuzzy matches.
 1215                                    highlight.font_weight = None;
 1216
 1217                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1218                                        highlight.strikethrough = Some(StrikethroughStyle {
 1219                                            thickness: 1.0.into(),
 1220                                            ..Default::default()
 1221                                        });
 1222                                        highlight.color = Some(cx.theme().colors().text_muted);
 1223                                    }
 1224
 1225                                    (range, highlight)
 1226                                },
 1227                            ),
 1228                        );
 1229                        let completion_label = StyledText::new(completion.label.text.clone())
 1230                            .with_highlights(&style.text, highlights);
 1231                        let documentation_label =
 1232                            if let Some(Documentation::SingleLine(text)) = documentation {
 1233                                if text.trim().is_empty() {
 1234                                    None
 1235                                } else {
 1236                                    Some(
 1237                                        Label::new(text.clone())
 1238                                            .ml_4()
 1239                                            .size(LabelSize::Small)
 1240                                            .color(Color::Muted),
 1241                                    )
 1242                                }
 1243                            } else {
 1244                                None
 1245                            };
 1246
 1247                        let color_swatch = completion
 1248                            .color()
 1249                            .map(|color| div().size_4().bg(color).rounded_sm());
 1250
 1251                        div().min_w(px(220.)).max_w(px(540.)).child(
 1252                            ListItem::new(mat.candidate_id)
 1253                                .inset(true)
 1254                                .selected(item_ix == selected_item)
 1255                                .on_click(cx.listener(move |editor, _event, cx| {
 1256                                    cx.stop_propagation();
 1257                                    if let Some(task) = editor.confirm_completion(
 1258                                        &ConfirmCompletion {
 1259                                            item_ix: Some(item_ix),
 1260                                        },
 1261                                        cx,
 1262                                    ) {
 1263                                        task.detach_and_log_err(cx)
 1264                                    }
 1265                                }))
 1266                                .start_slot::<Div>(color_swatch)
 1267                                .child(h_flex().overflow_hidden().child(completion_label))
 1268                                .end_slot::<Label>(documentation_label),
 1269                        )
 1270                    })
 1271                    .collect()
 1272            },
 1273        )
 1274        .occlude()
 1275        .max_h(max_height)
 1276        .track_scroll(self.scroll_handle.clone())
 1277        .with_width_from_item(widest_completion_ix)
 1278        .with_sizing_behavior(ListSizingBehavior::Infer);
 1279
 1280        Popover::new()
 1281            .child(list)
 1282            .when_some(multiline_docs, |popover, multiline_docs| {
 1283                popover.aside(multiline_docs)
 1284            })
 1285            .into_any_element()
 1286    }
 1287
 1288    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1289        let mut matches = if let Some(query) = query {
 1290            fuzzy::match_strings(
 1291                &self.match_candidates,
 1292                query,
 1293                query.chars().any(|c| c.is_uppercase()),
 1294                100,
 1295                &Default::default(),
 1296                executor,
 1297            )
 1298            .await
 1299        } else {
 1300            self.match_candidates
 1301                .iter()
 1302                .enumerate()
 1303                .map(|(candidate_id, candidate)| StringMatch {
 1304                    candidate_id,
 1305                    score: Default::default(),
 1306                    positions: Default::default(),
 1307                    string: candidate.string.clone(),
 1308                })
 1309                .collect()
 1310        };
 1311
 1312        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1313        if let Some(query) = query {
 1314            if let Some(query_start) = query.chars().next() {
 1315                matches.retain(|string_match| {
 1316                    split_words(&string_match.string).any(|word| {
 1317                        // Check that the first codepoint of the word as lowercase matches the first
 1318                        // codepoint of the query as lowercase
 1319                        word.chars()
 1320                            .flat_map(|codepoint| codepoint.to_lowercase())
 1321                            .zip(query_start.to_lowercase())
 1322                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1323                    })
 1324                });
 1325            }
 1326        }
 1327
 1328        let completions = self.completions.read();
 1329        if self.sort_completions {
 1330            matches.sort_unstable_by_key(|mat| {
 1331                // We do want to strike a balance here between what the language server tells us
 1332                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1333                // `Creat` and there is a local variable called `CreateComponent`).
 1334                // So what we do is: we bucket all matches into two buckets
 1335                // - Strong matches
 1336                // - Weak matches
 1337                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1338                // and the Weak matches are the rest.
 1339                //
 1340                // For the strong matches, we sort by the language-servers score first and for the weak
 1341                // matches, we prefer our fuzzy finder first.
 1342                //
 1343                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1344                // us into account when it's obviously a bad match.
 1345
 1346                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1347                enum MatchScore<'a> {
 1348                    Strong {
 1349                        sort_text: Option<&'a str>,
 1350                        score: Reverse<OrderedFloat<f64>>,
 1351                        sort_key: (usize, &'a str),
 1352                    },
 1353                    Weak {
 1354                        score: Reverse<OrderedFloat<f64>>,
 1355                        sort_text: Option<&'a str>,
 1356                        sort_key: (usize, &'a str),
 1357                    },
 1358                }
 1359
 1360                let completion = &completions[mat.candidate_id];
 1361                let sort_key = completion.sort_key();
 1362                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1363                let score = Reverse(OrderedFloat(mat.score));
 1364
 1365                if mat.score >= 0.2 {
 1366                    MatchScore::Strong {
 1367                        sort_text,
 1368                        score,
 1369                        sort_key,
 1370                    }
 1371                } else {
 1372                    MatchScore::Weak {
 1373                        score,
 1374                        sort_text,
 1375                        sort_key,
 1376                    }
 1377                }
 1378            });
 1379        }
 1380
 1381        for mat in &mut matches {
 1382            let completion = &completions[mat.candidate_id];
 1383            mat.string.clone_from(&completion.label.text);
 1384            for position in &mut mat.positions {
 1385                *position += completion.label.filter_range.start;
 1386            }
 1387        }
 1388        drop(completions);
 1389
 1390        self.matches = matches.into();
 1391        self.selected_item = 0;
 1392    }
 1393}
 1394
 1395struct AvailableCodeAction {
 1396    excerpt_id: ExcerptId,
 1397    action: CodeAction,
 1398    provider: Arc<dyn CodeActionProvider>,
 1399}
 1400
 1401#[derive(Clone)]
 1402struct CodeActionContents {
 1403    tasks: Option<Arc<ResolvedTasks>>,
 1404    actions: Option<Arc<[AvailableCodeAction]>>,
 1405}
 1406
 1407impl CodeActionContents {
 1408    fn len(&self) -> usize {
 1409        match (&self.tasks, &self.actions) {
 1410            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1411            (Some(tasks), None) => tasks.templates.len(),
 1412            (None, Some(actions)) => actions.len(),
 1413            (None, None) => 0,
 1414        }
 1415    }
 1416
 1417    fn is_empty(&self) -> bool {
 1418        match (&self.tasks, &self.actions) {
 1419            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1420            (Some(tasks), None) => tasks.templates.is_empty(),
 1421            (None, Some(actions)) => actions.is_empty(),
 1422            (None, None) => true,
 1423        }
 1424    }
 1425
 1426    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1427        self.tasks
 1428            .iter()
 1429            .flat_map(|tasks| {
 1430                tasks
 1431                    .templates
 1432                    .iter()
 1433                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1434            })
 1435            .chain(self.actions.iter().flat_map(|actions| {
 1436                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1437                    excerpt_id: available.excerpt_id,
 1438                    action: available.action.clone(),
 1439                    provider: available.provider.clone(),
 1440                })
 1441            }))
 1442    }
 1443    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1444        match (&self.tasks, &self.actions) {
 1445            (Some(tasks), Some(actions)) => {
 1446                if index < tasks.templates.len() {
 1447                    tasks
 1448                        .templates
 1449                        .get(index)
 1450                        .cloned()
 1451                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1452                } else {
 1453                    actions.get(index - tasks.templates.len()).map(|available| {
 1454                        CodeActionsItem::CodeAction {
 1455                            excerpt_id: available.excerpt_id,
 1456                            action: available.action.clone(),
 1457                            provider: available.provider.clone(),
 1458                        }
 1459                    })
 1460                }
 1461            }
 1462            (Some(tasks), None) => tasks
 1463                .templates
 1464                .get(index)
 1465                .cloned()
 1466                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1467            (None, Some(actions)) => {
 1468                actions
 1469                    .get(index)
 1470                    .map(|available| CodeActionsItem::CodeAction {
 1471                        excerpt_id: available.excerpt_id,
 1472                        action: available.action.clone(),
 1473                        provider: available.provider.clone(),
 1474                    })
 1475            }
 1476            (None, None) => None,
 1477        }
 1478    }
 1479}
 1480
 1481#[allow(clippy::large_enum_variant)]
 1482#[derive(Clone)]
 1483enum CodeActionsItem {
 1484    Task(TaskSourceKind, ResolvedTask),
 1485    CodeAction {
 1486        excerpt_id: ExcerptId,
 1487        action: CodeAction,
 1488        provider: Arc<dyn CodeActionProvider>,
 1489    },
 1490}
 1491
 1492impl CodeActionsItem {
 1493    fn as_task(&self) -> Option<&ResolvedTask> {
 1494        let Self::Task(_, task) = self else {
 1495            return None;
 1496        };
 1497        Some(task)
 1498    }
 1499    fn as_code_action(&self) -> Option<&CodeAction> {
 1500        let Self::CodeAction { action, .. } = self else {
 1501            return None;
 1502        };
 1503        Some(action)
 1504    }
 1505    fn label(&self) -> String {
 1506        match self {
 1507            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1508            Self::Task(_, task) => task.resolved_label.clone(),
 1509        }
 1510    }
 1511}
 1512
 1513struct CodeActionsMenu {
 1514    actions: CodeActionContents,
 1515    buffer: Model<Buffer>,
 1516    selected_item: usize,
 1517    scroll_handle: UniformListScrollHandle,
 1518    deployed_from_indicator: Option<DisplayRow>,
 1519}
 1520
 1521impl CodeActionsMenu {
 1522    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1523        self.selected_item = 0;
 1524        self.scroll_handle.scroll_to_item(self.selected_item);
 1525        cx.notify()
 1526    }
 1527
 1528    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1529        if self.selected_item > 0 {
 1530            self.selected_item -= 1;
 1531        } else {
 1532            self.selected_item = self.actions.len() - 1;
 1533        }
 1534        self.scroll_handle.scroll_to_item(self.selected_item);
 1535        cx.notify();
 1536    }
 1537
 1538    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1539        if self.selected_item + 1 < self.actions.len() {
 1540            self.selected_item += 1;
 1541        } else {
 1542            self.selected_item = 0;
 1543        }
 1544        self.scroll_handle.scroll_to_item(self.selected_item);
 1545        cx.notify();
 1546    }
 1547
 1548    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1549        self.selected_item = self.actions.len() - 1;
 1550        self.scroll_handle.scroll_to_item(self.selected_item);
 1551        cx.notify()
 1552    }
 1553
 1554    fn visible(&self) -> bool {
 1555        !self.actions.is_empty()
 1556    }
 1557
 1558    fn render(
 1559        &self,
 1560        cursor_position: DisplayPoint,
 1561        _style: &EditorStyle,
 1562        max_height: Pixels,
 1563        cx: &mut ViewContext<Editor>,
 1564    ) -> (ContextMenuOrigin, AnyElement) {
 1565        let actions = self.actions.clone();
 1566        let selected_item = self.selected_item;
 1567        let element = uniform_list(
 1568            cx.view().clone(),
 1569            "code_actions_menu",
 1570            self.actions.len(),
 1571            move |_this, range, cx| {
 1572                actions
 1573                    .iter()
 1574                    .skip(range.start)
 1575                    .take(range.end - range.start)
 1576                    .enumerate()
 1577                    .map(|(ix, action)| {
 1578                        let item_ix = range.start + ix;
 1579                        let selected = selected_item == item_ix;
 1580                        let colors = cx.theme().colors();
 1581                        div()
 1582                            .px_1()
 1583                            .rounded_md()
 1584                            .text_color(colors.text)
 1585                            .when(selected, |style| {
 1586                                style
 1587                                    .bg(colors.element_active)
 1588                                    .text_color(colors.text_accent)
 1589                            })
 1590                            .hover(|style| {
 1591                                style
 1592                                    .bg(colors.element_hover)
 1593                                    .text_color(colors.text_accent)
 1594                            })
 1595                            .whitespace_nowrap()
 1596                            .when_some(action.as_code_action(), |this, action| {
 1597                                this.on_mouse_down(
 1598                                    MouseButton::Left,
 1599                                    cx.listener(move |editor, _, cx| {
 1600                                        cx.stop_propagation();
 1601                                        if let Some(task) = editor.confirm_code_action(
 1602                                            &ConfirmCodeAction {
 1603                                                item_ix: Some(item_ix),
 1604                                            },
 1605                                            cx,
 1606                                        ) {
 1607                                            task.detach_and_log_err(cx)
 1608                                        }
 1609                                    }),
 1610                                )
 1611                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1612                                .child(SharedString::from(action.lsp_action.title.clone()))
 1613                            })
 1614                            .when_some(action.as_task(), |this, task| {
 1615                                this.on_mouse_down(
 1616                                    MouseButton::Left,
 1617                                    cx.listener(move |editor, _, cx| {
 1618                                        cx.stop_propagation();
 1619                                        if let Some(task) = editor.confirm_code_action(
 1620                                            &ConfirmCodeAction {
 1621                                                item_ix: Some(item_ix),
 1622                                            },
 1623                                            cx,
 1624                                        ) {
 1625                                            task.detach_and_log_err(cx)
 1626                                        }
 1627                                    }),
 1628                                )
 1629                                .child(SharedString::from(task.resolved_label.clone()))
 1630                            })
 1631                    })
 1632                    .collect()
 1633            },
 1634        )
 1635        .elevation_1(cx)
 1636        .p_1()
 1637        .max_h(max_height)
 1638        .occlude()
 1639        .track_scroll(self.scroll_handle.clone())
 1640        .with_width_from_item(
 1641            self.actions
 1642                .iter()
 1643                .enumerate()
 1644                .max_by_key(|(_, action)| match action {
 1645                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1646                    CodeActionsItem::CodeAction { action, .. } => {
 1647                        action.lsp_action.title.chars().count()
 1648                    }
 1649                })
 1650                .map(|(ix, _)| ix),
 1651        )
 1652        .with_sizing_behavior(ListSizingBehavior::Infer)
 1653        .into_any_element();
 1654
 1655        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1656            ContextMenuOrigin::GutterIndicator(row)
 1657        } else {
 1658            ContextMenuOrigin::EditorPoint(cursor_position)
 1659        };
 1660
 1661        (cursor_position, element)
 1662    }
 1663}
 1664
 1665#[derive(Debug)]
 1666struct ActiveDiagnosticGroup {
 1667    primary_range: Range<Anchor>,
 1668    primary_message: String,
 1669    group_id: usize,
 1670    blocks: HashMap<CustomBlockId, Diagnostic>,
 1671    is_valid: bool,
 1672}
 1673
 1674#[derive(Serialize, Deserialize, Clone, Debug)]
 1675pub struct ClipboardSelection {
 1676    pub len: usize,
 1677    pub is_entire_line: bool,
 1678    pub first_line_indent: u32,
 1679}
 1680
 1681#[derive(Debug)]
 1682pub(crate) struct NavigationData {
 1683    cursor_anchor: Anchor,
 1684    cursor_position: Point,
 1685    scroll_anchor: ScrollAnchor,
 1686    scroll_top_row: u32,
 1687}
 1688
 1689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1690pub enum GotoDefinitionKind {
 1691    Symbol,
 1692    Declaration,
 1693    Type,
 1694    Implementation,
 1695}
 1696
 1697#[derive(Debug, Clone)]
 1698enum InlayHintRefreshReason {
 1699    Toggle(bool),
 1700    SettingsChange(InlayHintSettings),
 1701    NewLinesShown,
 1702    BufferEdited(HashSet<Arc<Language>>),
 1703    RefreshRequested,
 1704    ExcerptsRemoved(Vec<ExcerptId>),
 1705}
 1706
 1707impl InlayHintRefreshReason {
 1708    fn description(&self) -> &'static str {
 1709        match self {
 1710            Self::Toggle(_) => "toggle",
 1711            Self::SettingsChange(_) => "settings change",
 1712            Self::NewLinesShown => "new lines shown",
 1713            Self::BufferEdited(_) => "buffer edited",
 1714            Self::RefreshRequested => "refresh requested",
 1715            Self::ExcerptsRemoved(_) => "excerpts removed",
 1716        }
 1717    }
 1718}
 1719
 1720pub(crate) struct FocusedBlock {
 1721    id: BlockId,
 1722    focus_handle: WeakFocusHandle,
 1723}
 1724
 1725impl Editor {
 1726    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1727        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1728        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1729        Self::new(
 1730            EditorMode::SingleLine { auto_width: false },
 1731            buffer,
 1732            None,
 1733            false,
 1734            cx,
 1735        )
 1736    }
 1737
 1738    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1739        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1740        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1741        Self::new(EditorMode::Full, buffer, None, false, cx)
 1742    }
 1743
 1744    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1745        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1746        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1747        Self::new(
 1748            EditorMode::SingleLine { auto_width: true },
 1749            buffer,
 1750            None,
 1751            false,
 1752            cx,
 1753        )
 1754    }
 1755
 1756    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1757        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1758        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1759        Self::new(
 1760            EditorMode::AutoHeight { max_lines },
 1761            buffer,
 1762            None,
 1763            false,
 1764            cx,
 1765        )
 1766    }
 1767
 1768    pub fn for_buffer(
 1769        buffer: Model<Buffer>,
 1770        project: Option<Model<Project>>,
 1771        cx: &mut ViewContext<Self>,
 1772    ) -> Self {
 1773        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1774        Self::new(EditorMode::Full, buffer, project, false, cx)
 1775    }
 1776
 1777    pub fn for_multibuffer(
 1778        buffer: Model<MultiBuffer>,
 1779        project: Option<Model<Project>>,
 1780        show_excerpt_controls: bool,
 1781        cx: &mut ViewContext<Self>,
 1782    ) -> Self {
 1783        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1784    }
 1785
 1786    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1787        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1788        let mut clone = Self::new(
 1789            self.mode,
 1790            self.buffer.clone(),
 1791            self.project.clone(),
 1792            show_excerpt_controls,
 1793            cx,
 1794        );
 1795        self.display_map.update(cx, |display_map, cx| {
 1796            let snapshot = display_map.snapshot(cx);
 1797            clone.display_map.update(cx, |display_map, cx| {
 1798                display_map.set_state(&snapshot, cx);
 1799            });
 1800        });
 1801        clone.selections.clone_state(&self.selections);
 1802        clone.scroll_manager.clone_state(&self.scroll_manager);
 1803        clone.searchable = self.searchable;
 1804        clone
 1805    }
 1806
 1807    pub fn new(
 1808        mode: EditorMode,
 1809        buffer: Model<MultiBuffer>,
 1810        project: Option<Model<Project>>,
 1811        show_excerpt_controls: bool,
 1812        cx: &mut ViewContext<Self>,
 1813    ) -> Self {
 1814        let style = cx.text_style();
 1815        let font_size = style.font_size.to_pixels(cx.rem_size());
 1816        let editor = cx.view().downgrade();
 1817        let fold_placeholder = FoldPlaceholder {
 1818            constrain_width: true,
 1819            render: Arc::new(move |fold_id, fold_range, cx| {
 1820                let editor = editor.clone();
 1821                div()
 1822                    .id(fold_id)
 1823                    .bg(cx.theme().colors().ghost_element_background)
 1824                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1825                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1826                    .rounded_sm()
 1827                    .size_full()
 1828                    .cursor_pointer()
 1829                    .child("")
 1830                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1831                    .on_click(move |_, cx| {
 1832                        editor
 1833                            .update(cx, |editor, cx| {
 1834                                editor.unfold_ranges(
 1835                                    [fold_range.start..fold_range.end],
 1836                                    true,
 1837                                    false,
 1838                                    cx,
 1839                                );
 1840                                cx.stop_propagation();
 1841                            })
 1842                            .ok();
 1843                    })
 1844                    .into_any()
 1845            }),
 1846            merge_adjacent: true,
 1847        };
 1848        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1849        let display_map = cx.new_model(|cx| {
 1850            DisplayMap::new(
 1851                buffer.clone(),
 1852                style.font(),
 1853                font_size,
 1854                None,
 1855                show_excerpt_controls,
 1856                file_header_size,
 1857                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1858                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1859                fold_placeholder,
 1860                cx,
 1861            )
 1862        });
 1863
 1864        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1865
 1866        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1867
 1868        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1869            .then(|| language_settings::SoftWrap::None);
 1870
 1871        let mut project_subscriptions = Vec::new();
 1872        if mode == EditorMode::Full {
 1873            if let Some(project) = project.as_ref() {
 1874                if buffer.read(cx).is_singleton() {
 1875                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1876                        cx.emit(EditorEvent::TitleChanged);
 1877                    }));
 1878                }
 1879                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1880                    if let project::Event::RefreshInlayHints = event {
 1881                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1882                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1883                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1884                            let focus_handle = editor.focus_handle(cx);
 1885                            if focus_handle.is_focused(cx) {
 1886                                let snapshot = buffer.read(cx).snapshot();
 1887                                for (range, snippet) in snippet_edits {
 1888                                    let editor_range =
 1889                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1890                                    editor
 1891                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1892                                        .ok();
 1893                                }
 1894                            }
 1895                        }
 1896                    }
 1897                }));
 1898                if let Some(task_inventory) = project
 1899                    .read(cx)
 1900                    .task_store()
 1901                    .read(cx)
 1902                    .task_inventory()
 1903                    .cloned()
 1904                {
 1905                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1906                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1907                    }));
 1908                }
 1909            }
 1910        }
 1911
 1912        let inlay_hint_settings = inlay_hint_settings(
 1913            selections.newest_anchor().head(),
 1914            &buffer.read(cx).snapshot(cx),
 1915            cx,
 1916        );
 1917        let focus_handle = cx.focus_handle();
 1918        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1919        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1920            .detach();
 1921        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1922            .detach();
 1923        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1924
 1925        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1926            Some(false)
 1927        } else {
 1928            None
 1929        };
 1930
 1931        let mut code_action_providers = Vec::new();
 1932        if let Some(project) = project.clone() {
 1933            code_action_providers.push(Arc::new(project) as Arc<_>);
 1934        }
 1935
 1936        let mut this = Self {
 1937            focus_handle,
 1938            show_cursor_when_unfocused: false,
 1939            last_focused_descendant: None,
 1940            buffer: buffer.clone(),
 1941            display_map: display_map.clone(),
 1942            selections,
 1943            scroll_manager: ScrollManager::new(cx),
 1944            columnar_selection_tail: None,
 1945            add_selections_state: None,
 1946            select_next_state: None,
 1947            select_prev_state: None,
 1948            selection_history: Default::default(),
 1949            autoclose_regions: Default::default(),
 1950            snippet_stack: Default::default(),
 1951            select_larger_syntax_node_stack: Vec::new(),
 1952            ime_transaction: Default::default(),
 1953            active_diagnostics: None,
 1954            soft_wrap_mode_override,
 1955            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1956            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1957            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1958            project,
 1959            blink_manager: blink_manager.clone(),
 1960            show_local_selections: true,
 1961            mode,
 1962            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1963            show_gutter: mode == EditorMode::Full,
 1964            show_line_numbers: None,
 1965            use_relative_line_numbers: None,
 1966            show_git_diff_gutter: None,
 1967            show_code_actions: None,
 1968            show_runnables: None,
 1969            show_wrap_guides: None,
 1970            show_indent_guides,
 1971            placeholder_text: None,
 1972            highlight_order: 0,
 1973            highlighted_rows: HashMap::default(),
 1974            background_highlights: Default::default(),
 1975            gutter_highlights: TreeMap::default(),
 1976            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1977            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1978            nav_history: None,
 1979            context_menu: RwLock::new(None),
 1980            mouse_context_menu: None,
 1981            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1982            completion_tasks: Default::default(),
 1983            signature_help_state: SignatureHelpState::default(),
 1984            auto_signature_help: None,
 1985            find_all_references_task_sources: Vec::new(),
 1986            next_completion_id: 0,
 1987            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1988            next_inlay_id: 0,
 1989            code_action_providers,
 1990            available_code_actions: Default::default(),
 1991            code_actions_task: Default::default(),
 1992            document_highlights_task: Default::default(),
 1993            linked_editing_range_task: Default::default(),
 1994            pending_rename: Default::default(),
 1995            searchable: true,
 1996            cursor_shape: EditorSettings::get_global(cx)
 1997                .cursor_shape
 1998                .unwrap_or_default(),
 1999            current_line_highlight: None,
 2000            autoindent_mode: Some(AutoindentMode::EachLine),
 2001            collapse_matches: false,
 2002            workspace: None,
 2003            input_enabled: true,
 2004            use_modal_editing: mode == EditorMode::Full,
 2005            read_only: false,
 2006            use_autoclose: true,
 2007            use_auto_surround: true,
 2008            auto_replace_emoji_shortcode: false,
 2009            leader_peer_id: None,
 2010            remote_id: None,
 2011            hover_state: Default::default(),
 2012            hovered_link_state: Default::default(),
 2013            inline_completion_provider: None,
 2014            active_inline_completion: None,
 2015            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2016            expanded_hunks: ExpandedHunks::default(),
 2017            gutter_hovered: false,
 2018            pixel_position_of_newest_cursor: None,
 2019            last_bounds: None,
 2020            expect_bounds_change: None,
 2021            gutter_dimensions: GutterDimensions::default(),
 2022            style: None,
 2023            show_cursor_names: false,
 2024            hovered_cursors: Default::default(),
 2025            next_editor_action_id: EditorActionId::default(),
 2026            editor_actions: Rc::default(),
 2027            show_inline_completions_override: None,
 2028            enable_inline_completions: true,
 2029            custom_context_menu: None,
 2030            show_git_blame_gutter: false,
 2031            show_git_blame_inline: false,
 2032            show_selection_menu: None,
 2033            show_git_blame_inline_delay_task: None,
 2034            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2035            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2036                .session
 2037                .restore_unsaved_buffers,
 2038            blame: None,
 2039            blame_subscription: None,
 2040            file_header_size,
 2041            tasks: Default::default(),
 2042            _subscriptions: vec![
 2043                cx.observe(&buffer, Self::on_buffer_changed),
 2044                cx.subscribe(&buffer, Self::on_buffer_event),
 2045                cx.observe(&display_map, Self::on_display_map_changed),
 2046                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2047                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2048                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2049                cx.observe_window_activation(|editor, cx| {
 2050                    let active = cx.is_window_active();
 2051                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2052                        if active {
 2053                            blink_manager.enable(cx);
 2054                        } else {
 2055                            blink_manager.disable(cx);
 2056                        }
 2057                    });
 2058                }),
 2059            ],
 2060            tasks_update_task: None,
 2061            linked_edit_ranges: Default::default(),
 2062            previous_search_ranges: None,
 2063            breadcrumb_header: None,
 2064            focused_block: None,
 2065            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2066            addons: HashMap::default(),
 2067            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2068        };
 2069        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2070        this._subscriptions.extend(project_subscriptions);
 2071
 2072        this.end_selection(cx);
 2073        this.scroll_manager.show_scrollbar(cx);
 2074
 2075        if mode == EditorMode::Full {
 2076            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2077            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2078
 2079            if this.git_blame_inline_enabled {
 2080                this.git_blame_inline_enabled = true;
 2081                this.start_git_blame_inline(false, cx);
 2082            }
 2083        }
 2084
 2085        this.report_editor_event("open", None, cx);
 2086        this
 2087    }
 2088
 2089    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2090        self.mouse_context_menu
 2091            .as_ref()
 2092            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2093    }
 2094
 2095    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2096        let mut key_context = KeyContext::new_with_defaults();
 2097        key_context.add("Editor");
 2098        let mode = match self.mode {
 2099            EditorMode::SingleLine { .. } => "single_line",
 2100            EditorMode::AutoHeight { .. } => "auto_height",
 2101            EditorMode::Full => "full",
 2102        };
 2103
 2104        if EditorSettings::jupyter_enabled(cx) {
 2105            key_context.add("jupyter");
 2106        }
 2107
 2108        key_context.set("mode", mode);
 2109        if self.pending_rename.is_some() {
 2110            key_context.add("renaming");
 2111        }
 2112        if self.context_menu_visible() {
 2113            match self.context_menu.read().as_ref() {
 2114                Some(ContextMenu::Completions(_)) => {
 2115                    key_context.add("menu");
 2116                    key_context.add("showing_completions")
 2117                }
 2118                Some(ContextMenu::CodeActions(_)) => {
 2119                    key_context.add("menu");
 2120                    key_context.add("showing_code_actions")
 2121                }
 2122                None => {}
 2123            }
 2124        }
 2125
 2126        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2127        if !self.focus_handle(cx).contains_focused(cx)
 2128            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2129        {
 2130            for addon in self.addons.values() {
 2131                addon.extend_key_context(&mut key_context, cx)
 2132            }
 2133        }
 2134
 2135        if let Some(extension) = self
 2136            .buffer
 2137            .read(cx)
 2138            .as_singleton()
 2139            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2140        {
 2141            key_context.set("extension", extension.to_string());
 2142        }
 2143
 2144        if self.has_active_inline_completion(cx) {
 2145            key_context.add("copilot_suggestion");
 2146            key_context.add("inline_completion");
 2147        }
 2148
 2149        key_context
 2150    }
 2151
 2152    pub fn new_file(
 2153        workspace: &mut Workspace,
 2154        _: &workspace::NewFile,
 2155        cx: &mut ViewContext<Workspace>,
 2156    ) {
 2157        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2158            "Failed to create buffer",
 2159            cx,
 2160            |e, _| match e.error_code() {
 2161                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2162                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2163                e.error_tag("required").unwrap_or("the latest version")
 2164            )),
 2165                _ => None,
 2166            },
 2167        );
 2168    }
 2169
 2170    pub fn new_in_workspace(
 2171        workspace: &mut Workspace,
 2172        cx: &mut ViewContext<Workspace>,
 2173    ) -> Task<Result<View<Editor>>> {
 2174        let project = workspace.project().clone();
 2175        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2176
 2177        cx.spawn(|workspace, mut cx| async move {
 2178            let buffer = create.await?;
 2179            workspace.update(&mut cx, |workspace, cx| {
 2180                let editor =
 2181                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2182                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2183                editor
 2184            })
 2185        })
 2186    }
 2187
 2188    fn new_file_vertical(
 2189        workspace: &mut Workspace,
 2190        _: &workspace::NewFileSplitVertical,
 2191        cx: &mut ViewContext<Workspace>,
 2192    ) {
 2193        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2194    }
 2195
 2196    fn new_file_horizontal(
 2197        workspace: &mut Workspace,
 2198        _: &workspace::NewFileSplitHorizontal,
 2199        cx: &mut ViewContext<Workspace>,
 2200    ) {
 2201        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2202    }
 2203
 2204    fn new_file_in_direction(
 2205        workspace: &mut Workspace,
 2206        direction: SplitDirection,
 2207        cx: &mut ViewContext<Workspace>,
 2208    ) {
 2209        let project = workspace.project().clone();
 2210        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2211
 2212        cx.spawn(|workspace, mut cx| async move {
 2213            let buffer = create.await?;
 2214            workspace.update(&mut cx, move |workspace, cx| {
 2215                workspace.split_item(
 2216                    direction,
 2217                    Box::new(
 2218                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2219                    ),
 2220                    cx,
 2221                )
 2222            })?;
 2223            anyhow::Ok(())
 2224        })
 2225        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2226            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2227                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2228                e.error_tag("required").unwrap_or("the latest version")
 2229            )),
 2230            _ => None,
 2231        });
 2232    }
 2233
 2234    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2235        self.leader_peer_id
 2236    }
 2237
 2238    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2239        &self.buffer
 2240    }
 2241
 2242    pub fn workspace(&self) -> Option<View<Workspace>> {
 2243        self.workspace.as_ref()?.0.upgrade()
 2244    }
 2245
 2246    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2247        self.buffer().read(cx).title(cx)
 2248    }
 2249
 2250    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2251        let git_blame_gutter_max_author_length = self
 2252            .render_git_blame_gutter(cx)
 2253            .then(|| {
 2254                if let Some(blame) = self.blame.as_ref() {
 2255                    let max_author_length =
 2256                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2257                    Some(max_author_length)
 2258                } else {
 2259                    None
 2260                }
 2261            })
 2262            .flatten();
 2263
 2264        EditorSnapshot {
 2265            mode: self.mode,
 2266            show_gutter: self.show_gutter,
 2267            show_line_numbers: self.show_line_numbers,
 2268            show_git_diff_gutter: self.show_git_diff_gutter,
 2269            show_code_actions: self.show_code_actions,
 2270            show_runnables: self.show_runnables,
 2271            git_blame_gutter_max_author_length,
 2272            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2273            scroll_anchor: self.scroll_manager.anchor(),
 2274            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2275            placeholder_text: self.placeholder_text.clone(),
 2276            is_focused: self.focus_handle.is_focused(cx),
 2277            current_line_highlight: self
 2278                .current_line_highlight
 2279                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2280            gutter_hovered: self.gutter_hovered,
 2281        }
 2282    }
 2283
 2284    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2285        self.buffer.read(cx).language_at(point, cx)
 2286    }
 2287
 2288    pub fn file_at<T: ToOffset>(
 2289        &self,
 2290        point: T,
 2291        cx: &AppContext,
 2292    ) -> Option<Arc<dyn language::File>> {
 2293        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2294    }
 2295
 2296    pub fn active_excerpt(
 2297        &self,
 2298        cx: &AppContext,
 2299    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2300        self.buffer
 2301            .read(cx)
 2302            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2303    }
 2304
 2305    pub fn mode(&self) -> EditorMode {
 2306        self.mode
 2307    }
 2308
 2309    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2310        self.collaboration_hub.as_deref()
 2311    }
 2312
 2313    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2314        self.collaboration_hub = Some(hub);
 2315    }
 2316
 2317    pub fn set_custom_context_menu(
 2318        &mut self,
 2319        f: impl 'static
 2320            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2321    ) {
 2322        self.custom_context_menu = Some(Box::new(f))
 2323    }
 2324
 2325    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2326        self.completion_provider = provider;
 2327    }
 2328
 2329    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2330        self.semantics_provider.clone()
 2331    }
 2332
 2333    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2334        self.semantics_provider = provider;
 2335    }
 2336
 2337    pub fn set_inline_completion_provider<T>(
 2338        &mut self,
 2339        provider: Option<Model<T>>,
 2340        cx: &mut ViewContext<Self>,
 2341    ) where
 2342        T: InlineCompletionProvider,
 2343    {
 2344        self.inline_completion_provider =
 2345            provider.map(|provider| RegisteredInlineCompletionProvider {
 2346                _subscription: cx.observe(&provider, |this, _, cx| {
 2347                    if this.focus_handle.is_focused(cx) {
 2348                        this.update_visible_inline_completion(cx);
 2349                    }
 2350                }),
 2351                provider: Arc::new(provider),
 2352            });
 2353        self.refresh_inline_completion(false, false, cx);
 2354    }
 2355
 2356    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2357        self.placeholder_text.as_deref()
 2358    }
 2359
 2360    pub fn set_placeholder_text(
 2361        &mut self,
 2362        placeholder_text: impl Into<Arc<str>>,
 2363        cx: &mut ViewContext<Self>,
 2364    ) {
 2365        let placeholder_text = Some(placeholder_text.into());
 2366        if self.placeholder_text != placeholder_text {
 2367            self.placeholder_text = placeholder_text;
 2368            cx.notify();
 2369        }
 2370    }
 2371
 2372    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2373        self.cursor_shape = cursor_shape;
 2374
 2375        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2376        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2377
 2378        cx.notify();
 2379    }
 2380
 2381    pub fn set_current_line_highlight(
 2382        &mut self,
 2383        current_line_highlight: Option<CurrentLineHighlight>,
 2384    ) {
 2385        self.current_line_highlight = current_line_highlight;
 2386    }
 2387
 2388    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2389        self.collapse_matches = collapse_matches;
 2390    }
 2391
 2392    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2393        if self.collapse_matches {
 2394            return range.start..range.start;
 2395        }
 2396        range.clone()
 2397    }
 2398
 2399    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2400        if self.display_map.read(cx).clip_at_line_ends != clip {
 2401            self.display_map
 2402                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2403        }
 2404    }
 2405
 2406    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2407        self.input_enabled = input_enabled;
 2408    }
 2409
 2410    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2411        self.enable_inline_completions = enabled;
 2412    }
 2413
 2414    pub fn set_autoindent(&mut self, autoindent: bool) {
 2415        if autoindent {
 2416            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2417        } else {
 2418            self.autoindent_mode = None;
 2419        }
 2420    }
 2421
 2422    pub fn read_only(&self, cx: &AppContext) -> bool {
 2423        self.read_only || self.buffer.read(cx).read_only()
 2424    }
 2425
 2426    pub fn set_read_only(&mut self, read_only: bool) {
 2427        self.read_only = read_only;
 2428    }
 2429
 2430    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2431        self.use_autoclose = autoclose;
 2432    }
 2433
 2434    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2435        self.use_auto_surround = auto_surround;
 2436    }
 2437
 2438    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2439        self.auto_replace_emoji_shortcode = auto_replace;
 2440    }
 2441
 2442    pub fn toggle_inline_completions(
 2443        &mut self,
 2444        _: &ToggleInlineCompletions,
 2445        cx: &mut ViewContext<Self>,
 2446    ) {
 2447        if self.show_inline_completions_override.is_some() {
 2448            self.set_show_inline_completions(None, cx);
 2449        } else {
 2450            let cursor = self.selections.newest_anchor().head();
 2451            if let Some((buffer, cursor_buffer_position)) =
 2452                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2453            {
 2454                let show_inline_completions =
 2455                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2456                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2457            }
 2458        }
 2459    }
 2460
 2461    pub fn set_show_inline_completions(
 2462        &mut self,
 2463        show_inline_completions: Option<bool>,
 2464        cx: &mut ViewContext<Self>,
 2465    ) {
 2466        self.show_inline_completions_override = show_inline_completions;
 2467        self.refresh_inline_completion(false, true, cx);
 2468    }
 2469
 2470    fn should_show_inline_completions(
 2471        &self,
 2472        buffer: &Model<Buffer>,
 2473        buffer_position: language::Anchor,
 2474        cx: &AppContext,
 2475    ) -> bool {
 2476        if let Some(provider) = self.inline_completion_provider() {
 2477            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2478                show_inline_completions
 2479            } else {
 2480                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2481            }
 2482        } else {
 2483            false
 2484        }
 2485    }
 2486
 2487    pub fn set_use_modal_editing(&mut self, to: bool) {
 2488        self.use_modal_editing = to;
 2489    }
 2490
 2491    pub fn use_modal_editing(&self) -> bool {
 2492        self.use_modal_editing
 2493    }
 2494
 2495    fn selections_did_change(
 2496        &mut self,
 2497        local: bool,
 2498        old_cursor_position: &Anchor,
 2499        show_completions: bool,
 2500        cx: &mut ViewContext<Self>,
 2501    ) {
 2502        cx.invalidate_character_coordinates();
 2503
 2504        // Copy selections to primary selection buffer
 2505        #[cfg(target_os = "linux")]
 2506        if local {
 2507            let selections = self.selections.all::<usize>(cx);
 2508            let buffer_handle = self.buffer.read(cx).read(cx);
 2509
 2510            let mut text = String::new();
 2511            for (index, selection) in selections.iter().enumerate() {
 2512                let text_for_selection = buffer_handle
 2513                    .text_for_range(selection.start..selection.end)
 2514                    .collect::<String>();
 2515
 2516                text.push_str(&text_for_selection);
 2517                if index != selections.len() - 1 {
 2518                    text.push('\n');
 2519                }
 2520            }
 2521
 2522            if !text.is_empty() {
 2523                cx.write_to_primary(ClipboardItem::new_string(text));
 2524            }
 2525        }
 2526
 2527        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2528            self.buffer.update(cx, |buffer, cx| {
 2529                buffer.set_active_selections(
 2530                    &self.selections.disjoint_anchors(),
 2531                    self.selections.line_mode,
 2532                    self.cursor_shape,
 2533                    cx,
 2534                )
 2535            });
 2536        }
 2537        let display_map = self
 2538            .display_map
 2539            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2540        let buffer = &display_map.buffer_snapshot;
 2541        self.add_selections_state = None;
 2542        self.select_next_state = None;
 2543        self.select_prev_state = None;
 2544        self.select_larger_syntax_node_stack.clear();
 2545        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2546        self.snippet_stack
 2547            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2548        self.take_rename(false, cx);
 2549
 2550        let new_cursor_position = self.selections.newest_anchor().head();
 2551
 2552        self.push_to_nav_history(
 2553            *old_cursor_position,
 2554            Some(new_cursor_position.to_point(buffer)),
 2555            cx,
 2556        );
 2557
 2558        if local {
 2559            let new_cursor_position = self.selections.newest_anchor().head();
 2560            let mut context_menu = self.context_menu.write();
 2561            let completion_menu = match context_menu.as_ref() {
 2562                Some(ContextMenu::Completions(menu)) => Some(menu),
 2563
 2564                _ => {
 2565                    *context_menu = None;
 2566                    None
 2567                }
 2568            };
 2569
 2570            if let Some(completion_menu) = completion_menu {
 2571                let cursor_position = new_cursor_position.to_offset(buffer);
 2572                let (word_range, kind) =
 2573                    buffer.surrounding_word(completion_menu.initial_position, true);
 2574                if kind == Some(CharKind::Word)
 2575                    && word_range.to_inclusive().contains(&cursor_position)
 2576                {
 2577                    let mut completion_menu = completion_menu.clone();
 2578                    drop(context_menu);
 2579
 2580                    let query = Self::completion_query(buffer, cursor_position);
 2581                    cx.spawn(move |this, mut cx| async move {
 2582                        completion_menu
 2583                            .filter(query.as_deref(), cx.background_executor().clone())
 2584                            .await;
 2585
 2586                        this.update(&mut cx, |this, cx| {
 2587                            let mut context_menu = this.context_menu.write();
 2588                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2589                                return;
 2590                            };
 2591
 2592                            if menu.id > completion_menu.id {
 2593                                return;
 2594                            }
 2595
 2596                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2597                            drop(context_menu);
 2598                            cx.notify();
 2599                        })
 2600                    })
 2601                    .detach();
 2602
 2603                    if show_completions {
 2604                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2605                    }
 2606                } else {
 2607                    drop(context_menu);
 2608                    self.hide_context_menu(cx);
 2609                }
 2610            } else {
 2611                drop(context_menu);
 2612            }
 2613
 2614            hide_hover(self, cx);
 2615
 2616            if old_cursor_position.to_display_point(&display_map).row()
 2617                != new_cursor_position.to_display_point(&display_map).row()
 2618            {
 2619                self.available_code_actions.take();
 2620            }
 2621            self.refresh_code_actions(cx);
 2622            self.refresh_document_highlights(cx);
 2623            refresh_matching_bracket_highlights(self, cx);
 2624            self.discard_inline_completion(false, cx);
 2625            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2626            if self.git_blame_inline_enabled {
 2627                self.start_inline_blame_timer(cx);
 2628            }
 2629        }
 2630
 2631        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2632        cx.emit(EditorEvent::SelectionsChanged { local });
 2633
 2634        if self.selections.disjoint_anchors().len() == 1 {
 2635            cx.emit(SearchEvent::ActiveMatchChanged)
 2636        }
 2637        cx.notify();
 2638    }
 2639
 2640    pub fn change_selections<R>(
 2641        &mut self,
 2642        autoscroll: Option<Autoscroll>,
 2643        cx: &mut ViewContext<Self>,
 2644        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2645    ) -> R {
 2646        self.change_selections_inner(autoscroll, true, cx, change)
 2647    }
 2648
 2649    pub fn change_selections_inner<R>(
 2650        &mut self,
 2651        autoscroll: Option<Autoscroll>,
 2652        request_completions: bool,
 2653        cx: &mut ViewContext<Self>,
 2654        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2655    ) -> R {
 2656        let old_cursor_position = self.selections.newest_anchor().head();
 2657        self.push_to_selection_history();
 2658
 2659        let (changed, result) = self.selections.change_with(cx, change);
 2660
 2661        if changed {
 2662            if let Some(autoscroll) = autoscroll {
 2663                self.request_autoscroll(autoscroll, cx);
 2664            }
 2665            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2666
 2667            if self.should_open_signature_help_automatically(
 2668                &old_cursor_position,
 2669                self.signature_help_state.backspace_pressed(),
 2670                cx,
 2671            ) {
 2672                self.show_signature_help(&ShowSignatureHelp, cx);
 2673            }
 2674            self.signature_help_state.set_backspace_pressed(false);
 2675        }
 2676
 2677        result
 2678    }
 2679
 2680    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2681    where
 2682        I: IntoIterator<Item = (Range<S>, T)>,
 2683        S: ToOffset,
 2684        T: Into<Arc<str>>,
 2685    {
 2686        if self.read_only(cx) {
 2687            return;
 2688        }
 2689
 2690        self.buffer
 2691            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2692    }
 2693
 2694    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2695    where
 2696        I: IntoIterator<Item = (Range<S>, T)>,
 2697        S: ToOffset,
 2698        T: Into<Arc<str>>,
 2699    {
 2700        if self.read_only(cx) {
 2701            return;
 2702        }
 2703
 2704        self.buffer.update(cx, |buffer, cx| {
 2705            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2706        });
 2707    }
 2708
 2709    pub fn edit_with_block_indent<I, S, T>(
 2710        &mut self,
 2711        edits: I,
 2712        original_indent_columns: Vec<u32>,
 2713        cx: &mut ViewContext<Self>,
 2714    ) where
 2715        I: IntoIterator<Item = (Range<S>, T)>,
 2716        S: ToOffset,
 2717        T: Into<Arc<str>>,
 2718    {
 2719        if self.read_only(cx) {
 2720            return;
 2721        }
 2722
 2723        self.buffer.update(cx, |buffer, cx| {
 2724            buffer.edit(
 2725                edits,
 2726                Some(AutoindentMode::Block {
 2727                    original_indent_columns,
 2728                }),
 2729                cx,
 2730            )
 2731        });
 2732    }
 2733
 2734    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2735        self.hide_context_menu(cx);
 2736
 2737        match phase {
 2738            SelectPhase::Begin {
 2739                position,
 2740                add,
 2741                click_count,
 2742            } => self.begin_selection(position, add, click_count, cx),
 2743            SelectPhase::BeginColumnar {
 2744                position,
 2745                goal_column,
 2746                reset,
 2747            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2748            SelectPhase::Extend {
 2749                position,
 2750                click_count,
 2751            } => self.extend_selection(position, click_count, cx),
 2752            SelectPhase::Update {
 2753                position,
 2754                goal_column,
 2755                scroll_delta,
 2756            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2757            SelectPhase::End => self.end_selection(cx),
 2758        }
 2759    }
 2760
 2761    fn extend_selection(
 2762        &mut self,
 2763        position: DisplayPoint,
 2764        click_count: usize,
 2765        cx: &mut ViewContext<Self>,
 2766    ) {
 2767        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2768        let tail = self.selections.newest::<usize>(cx).tail();
 2769        self.begin_selection(position, false, click_count, cx);
 2770
 2771        let position = position.to_offset(&display_map, Bias::Left);
 2772        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2773
 2774        let mut pending_selection = self
 2775            .selections
 2776            .pending_anchor()
 2777            .expect("extend_selection not called with pending selection");
 2778        if position >= tail {
 2779            pending_selection.start = tail_anchor;
 2780        } else {
 2781            pending_selection.end = tail_anchor;
 2782            pending_selection.reversed = true;
 2783        }
 2784
 2785        let mut pending_mode = self.selections.pending_mode().unwrap();
 2786        match &mut pending_mode {
 2787            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2788            _ => {}
 2789        }
 2790
 2791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2792            s.set_pending(pending_selection, pending_mode)
 2793        });
 2794    }
 2795
 2796    fn begin_selection(
 2797        &mut self,
 2798        position: DisplayPoint,
 2799        add: bool,
 2800        click_count: usize,
 2801        cx: &mut ViewContext<Self>,
 2802    ) {
 2803        if !self.focus_handle.is_focused(cx) {
 2804            self.last_focused_descendant = None;
 2805            cx.focus(&self.focus_handle);
 2806        }
 2807
 2808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2809        let buffer = &display_map.buffer_snapshot;
 2810        let newest_selection = self.selections.newest_anchor().clone();
 2811        let position = display_map.clip_point(position, Bias::Left);
 2812
 2813        let start;
 2814        let end;
 2815        let mode;
 2816        let auto_scroll;
 2817        match click_count {
 2818            1 => {
 2819                start = buffer.anchor_before(position.to_point(&display_map));
 2820                end = start;
 2821                mode = SelectMode::Character;
 2822                auto_scroll = true;
 2823            }
 2824            2 => {
 2825                let range = movement::surrounding_word(&display_map, position);
 2826                start = buffer.anchor_before(range.start.to_point(&display_map));
 2827                end = buffer.anchor_before(range.end.to_point(&display_map));
 2828                mode = SelectMode::Word(start..end);
 2829                auto_scroll = true;
 2830            }
 2831            3 => {
 2832                let position = display_map
 2833                    .clip_point(position, Bias::Left)
 2834                    .to_point(&display_map);
 2835                let line_start = display_map.prev_line_boundary(position).0;
 2836                let next_line_start = buffer.clip_point(
 2837                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2838                    Bias::Left,
 2839                );
 2840                start = buffer.anchor_before(line_start);
 2841                end = buffer.anchor_before(next_line_start);
 2842                mode = SelectMode::Line(start..end);
 2843                auto_scroll = true;
 2844            }
 2845            _ => {
 2846                start = buffer.anchor_before(0);
 2847                end = buffer.anchor_before(buffer.len());
 2848                mode = SelectMode::All;
 2849                auto_scroll = false;
 2850            }
 2851        }
 2852
 2853        let point_to_delete: Option<usize> = {
 2854            let selected_points: Vec<Selection<Point>> =
 2855                self.selections.disjoint_in_range(start..end, cx);
 2856
 2857            if !add || click_count > 1 {
 2858                None
 2859            } else if !selected_points.is_empty() {
 2860                Some(selected_points[0].id)
 2861            } else {
 2862                let clicked_point_already_selected =
 2863                    self.selections.disjoint.iter().find(|selection| {
 2864                        selection.start.to_point(buffer) == start.to_point(buffer)
 2865                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2866                    });
 2867
 2868                clicked_point_already_selected.map(|selection| selection.id)
 2869            }
 2870        };
 2871
 2872        let selections_count = self.selections.count();
 2873
 2874        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2875            if let Some(point_to_delete) = point_to_delete {
 2876                s.delete(point_to_delete);
 2877
 2878                if selections_count == 1 {
 2879                    s.set_pending_anchor_range(start..end, mode);
 2880                }
 2881            } else {
 2882                if !add {
 2883                    s.clear_disjoint();
 2884                } else if click_count > 1 {
 2885                    s.delete(newest_selection.id)
 2886                }
 2887
 2888                s.set_pending_anchor_range(start..end, mode);
 2889            }
 2890        });
 2891    }
 2892
 2893    fn begin_columnar_selection(
 2894        &mut self,
 2895        position: DisplayPoint,
 2896        goal_column: u32,
 2897        reset: bool,
 2898        cx: &mut ViewContext<Self>,
 2899    ) {
 2900        if !self.focus_handle.is_focused(cx) {
 2901            self.last_focused_descendant = None;
 2902            cx.focus(&self.focus_handle);
 2903        }
 2904
 2905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2906
 2907        if reset {
 2908            let pointer_position = display_map
 2909                .buffer_snapshot
 2910                .anchor_before(position.to_point(&display_map));
 2911
 2912            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2913                s.clear_disjoint();
 2914                s.set_pending_anchor_range(
 2915                    pointer_position..pointer_position,
 2916                    SelectMode::Character,
 2917                );
 2918            });
 2919        }
 2920
 2921        let tail = self.selections.newest::<Point>(cx).tail();
 2922        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2923
 2924        if !reset {
 2925            self.select_columns(
 2926                tail.to_display_point(&display_map),
 2927                position,
 2928                goal_column,
 2929                &display_map,
 2930                cx,
 2931            );
 2932        }
 2933    }
 2934
 2935    fn update_selection(
 2936        &mut self,
 2937        position: DisplayPoint,
 2938        goal_column: u32,
 2939        scroll_delta: gpui::Point<f32>,
 2940        cx: &mut ViewContext<Self>,
 2941    ) {
 2942        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2943
 2944        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2945            let tail = tail.to_display_point(&display_map);
 2946            self.select_columns(tail, position, goal_column, &display_map, cx);
 2947        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2948            let buffer = self.buffer.read(cx).snapshot(cx);
 2949            let head;
 2950            let tail;
 2951            let mode = self.selections.pending_mode().unwrap();
 2952            match &mode {
 2953                SelectMode::Character => {
 2954                    head = position.to_point(&display_map);
 2955                    tail = pending.tail().to_point(&buffer);
 2956                }
 2957                SelectMode::Word(original_range) => {
 2958                    let original_display_range = original_range.start.to_display_point(&display_map)
 2959                        ..original_range.end.to_display_point(&display_map);
 2960                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2961                        ..original_display_range.end.to_point(&display_map);
 2962                    if movement::is_inside_word(&display_map, position)
 2963                        || original_display_range.contains(&position)
 2964                    {
 2965                        let word_range = movement::surrounding_word(&display_map, position);
 2966                        if word_range.start < original_display_range.start {
 2967                            head = word_range.start.to_point(&display_map);
 2968                        } else {
 2969                            head = word_range.end.to_point(&display_map);
 2970                        }
 2971                    } else {
 2972                        head = position.to_point(&display_map);
 2973                    }
 2974
 2975                    if head <= original_buffer_range.start {
 2976                        tail = original_buffer_range.end;
 2977                    } else {
 2978                        tail = original_buffer_range.start;
 2979                    }
 2980                }
 2981                SelectMode::Line(original_range) => {
 2982                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2983
 2984                    let position = display_map
 2985                        .clip_point(position, Bias::Left)
 2986                        .to_point(&display_map);
 2987                    let line_start = display_map.prev_line_boundary(position).0;
 2988                    let next_line_start = buffer.clip_point(
 2989                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2990                        Bias::Left,
 2991                    );
 2992
 2993                    if line_start < original_range.start {
 2994                        head = line_start
 2995                    } else {
 2996                        head = next_line_start
 2997                    }
 2998
 2999                    if head <= original_range.start {
 3000                        tail = original_range.end;
 3001                    } else {
 3002                        tail = original_range.start;
 3003                    }
 3004                }
 3005                SelectMode::All => {
 3006                    return;
 3007                }
 3008            };
 3009
 3010            if head < tail {
 3011                pending.start = buffer.anchor_before(head);
 3012                pending.end = buffer.anchor_before(tail);
 3013                pending.reversed = true;
 3014            } else {
 3015                pending.start = buffer.anchor_before(tail);
 3016                pending.end = buffer.anchor_before(head);
 3017                pending.reversed = false;
 3018            }
 3019
 3020            self.change_selections(None, cx, |s| {
 3021                s.set_pending(pending, mode);
 3022            });
 3023        } else {
 3024            log::error!("update_selection dispatched with no pending selection");
 3025            return;
 3026        }
 3027
 3028        self.apply_scroll_delta(scroll_delta, cx);
 3029        cx.notify();
 3030    }
 3031
 3032    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3033        self.columnar_selection_tail.take();
 3034        if self.selections.pending_anchor().is_some() {
 3035            let selections = self.selections.all::<usize>(cx);
 3036            self.change_selections(None, cx, |s| {
 3037                s.select(selections);
 3038                s.clear_pending();
 3039            });
 3040        }
 3041    }
 3042
 3043    fn select_columns(
 3044        &mut self,
 3045        tail: DisplayPoint,
 3046        head: DisplayPoint,
 3047        goal_column: u32,
 3048        display_map: &DisplaySnapshot,
 3049        cx: &mut ViewContext<Self>,
 3050    ) {
 3051        let start_row = cmp::min(tail.row(), head.row());
 3052        let end_row = cmp::max(tail.row(), head.row());
 3053        let start_column = cmp::min(tail.column(), goal_column);
 3054        let end_column = cmp::max(tail.column(), goal_column);
 3055        let reversed = start_column < tail.column();
 3056
 3057        let selection_ranges = (start_row.0..=end_row.0)
 3058            .map(DisplayRow)
 3059            .filter_map(|row| {
 3060                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3061                    let start = display_map
 3062                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3063                        .to_point(display_map);
 3064                    let end = display_map
 3065                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3066                        .to_point(display_map);
 3067                    if reversed {
 3068                        Some(end..start)
 3069                    } else {
 3070                        Some(start..end)
 3071                    }
 3072                } else {
 3073                    None
 3074                }
 3075            })
 3076            .collect::<Vec<_>>();
 3077
 3078        self.change_selections(None, cx, |s| {
 3079            s.select_ranges(selection_ranges);
 3080        });
 3081        cx.notify();
 3082    }
 3083
 3084    pub fn has_pending_nonempty_selection(&self) -> bool {
 3085        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3086            Some(Selection { start, end, .. }) => start != end,
 3087            None => false,
 3088        };
 3089
 3090        pending_nonempty_selection
 3091            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3092    }
 3093
 3094    pub fn has_pending_selection(&self) -> bool {
 3095        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3096    }
 3097
 3098    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3099        if self.clear_expanded_diff_hunks(cx) {
 3100            cx.notify();
 3101            return;
 3102        }
 3103        if self.dismiss_menus_and_popups(true, cx) {
 3104            return;
 3105        }
 3106
 3107        if self.mode == EditorMode::Full
 3108            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3109        {
 3110            return;
 3111        }
 3112
 3113        cx.propagate();
 3114    }
 3115
 3116    pub fn dismiss_menus_and_popups(
 3117        &mut self,
 3118        should_report_inline_completion_event: bool,
 3119        cx: &mut ViewContext<Self>,
 3120    ) -> bool {
 3121        if self.take_rename(false, cx).is_some() {
 3122            return true;
 3123        }
 3124
 3125        if hide_hover(self, cx) {
 3126            return true;
 3127        }
 3128
 3129        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3130            return true;
 3131        }
 3132
 3133        if self.hide_context_menu(cx).is_some() {
 3134            return true;
 3135        }
 3136
 3137        if self.mouse_context_menu.take().is_some() {
 3138            return true;
 3139        }
 3140
 3141        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3142            return true;
 3143        }
 3144
 3145        if self.snippet_stack.pop().is_some() {
 3146            return true;
 3147        }
 3148
 3149        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3150            self.dismiss_diagnostics(cx);
 3151            return true;
 3152        }
 3153
 3154        false
 3155    }
 3156
 3157    fn linked_editing_ranges_for(
 3158        &self,
 3159        selection: Range<text::Anchor>,
 3160        cx: &AppContext,
 3161    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3162        if self.linked_edit_ranges.is_empty() {
 3163            return None;
 3164        }
 3165        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3166            selection.end.buffer_id.and_then(|end_buffer_id| {
 3167                if selection.start.buffer_id != Some(end_buffer_id) {
 3168                    return None;
 3169                }
 3170                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3171                let snapshot = buffer.read(cx).snapshot();
 3172                self.linked_edit_ranges
 3173                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3174                    .map(|ranges| (ranges, snapshot, buffer))
 3175            })?;
 3176        use text::ToOffset as TO;
 3177        // find offset from the start of current range to current cursor position
 3178        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3179
 3180        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3181        let start_difference = start_offset - start_byte_offset;
 3182        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3183        let end_difference = end_offset - start_byte_offset;
 3184        // Current range has associated linked ranges.
 3185        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3186        for range in linked_ranges.iter() {
 3187            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3188            let end_offset = start_offset + end_difference;
 3189            let start_offset = start_offset + start_difference;
 3190            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3191                continue;
 3192            }
 3193            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3194                if s.start.buffer_id != selection.start.buffer_id
 3195                    || s.end.buffer_id != selection.end.buffer_id
 3196                {
 3197                    return false;
 3198                }
 3199                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3200                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3201            }) {
 3202                continue;
 3203            }
 3204            let start = buffer_snapshot.anchor_after(start_offset);
 3205            let end = buffer_snapshot.anchor_after(end_offset);
 3206            linked_edits
 3207                .entry(buffer.clone())
 3208                .or_default()
 3209                .push(start..end);
 3210        }
 3211        Some(linked_edits)
 3212    }
 3213
 3214    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3215        let text: Arc<str> = text.into();
 3216
 3217        if self.read_only(cx) {
 3218            return;
 3219        }
 3220
 3221        let selections = self.selections.all_adjusted(cx);
 3222        let mut bracket_inserted = false;
 3223        let mut edits = Vec::new();
 3224        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3225        let mut new_selections = Vec::with_capacity(selections.len());
 3226        let mut new_autoclose_regions = Vec::new();
 3227        let snapshot = self.buffer.read(cx).read(cx);
 3228
 3229        for (selection, autoclose_region) in
 3230            self.selections_with_autoclose_regions(selections, &snapshot)
 3231        {
 3232            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3233                // Determine if the inserted text matches the opening or closing
 3234                // bracket of any of this language's bracket pairs.
 3235                let mut bracket_pair = None;
 3236                let mut is_bracket_pair_start = false;
 3237                let mut is_bracket_pair_end = false;
 3238                if !text.is_empty() {
 3239                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3240                    //  and they are removing the character that triggered IME popup.
 3241                    for (pair, enabled) in scope.brackets() {
 3242                        if !pair.close && !pair.surround {
 3243                            continue;
 3244                        }
 3245
 3246                        if enabled && pair.start.ends_with(text.as_ref()) {
 3247                            bracket_pair = Some(pair.clone());
 3248                            is_bracket_pair_start = true;
 3249                            break;
 3250                        }
 3251                        if pair.end.as_str() == text.as_ref() {
 3252                            bracket_pair = Some(pair.clone());
 3253                            is_bracket_pair_end = true;
 3254                            break;
 3255                        }
 3256                    }
 3257                }
 3258
 3259                if let Some(bracket_pair) = bracket_pair {
 3260                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3261                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3262                    let auto_surround =
 3263                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3264                    if selection.is_empty() {
 3265                        if is_bracket_pair_start {
 3266                            let prefix_len = bracket_pair.start.len() - text.len();
 3267
 3268                            // If the inserted text is a suffix of an opening bracket and the
 3269                            // selection is preceded by the rest of the opening bracket, then
 3270                            // insert the closing bracket.
 3271                            let following_text_allows_autoclose = snapshot
 3272                                .chars_at(selection.start)
 3273                                .next()
 3274                                .map_or(true, |c| scope.should_autoclose_before(c));
 3275                            let preceding_text_matches_prefix = prefix_len == 0
 3276                                || (selection.start.column >= (prefix_len as u32)
 3277                                    && snapshot.contains_str_at(
 3278                                        Point::new(
 3279                                            selection.start.row,
 3280                                            selection.start.column - (prefix_len as u32),
 3281                                        ),
 3282                                        &bracket_pair.start[..prefix_len],
 3283                                    ));
 3284
 3285                            if autoclose
 3286                                && bracket_pair.close
 3287                                && following_text_allows_autoclose
 3288                                && preceding_text_matches_prefix
 3289                            {
 3290                                let anchor = snapshot.anchor_before(selection.end);
 3291                                new_selections.push((selection.map(|_| anchor), text.len()));
 3292                                new_autoclose_regions.push((
 3293                                    anchor,
 3294                                    text.len(),
 3295                                    selection.id,
 3296                                    bracket_pair.clone(),
 3297                                ));
 3298                                edits.push((
 3299                                    selection.range(),
 3300                                    format!("{}{}", text, bracket_pair.end).into(),
 3301                                ));
 3302                                bracket_inserted = true;
 3303                                continue;
 3304                            }
 3305                        }
 3306
 3307                        if let Some(region) = autoclose_region {
 3308                            // If the selection is followed by an auto-inserted closing bracket,
 3309                            // then don't insert that closing bracket again; just move the selection
 3310                            // past the closing bracket.
 3311                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3312                                && text.as_ref() == region.pair.end.as_str();
 3313                            if should_skip {
 3314                                let anchor = snapshot.anchor_after(selection.end);
 3315                                new_selections
 3316                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3317                                continue;
 3318                            }
 3319                        }
 3320
 3321                        let always_treat_brackets_as_autoclosed = snapshot
 3322                            .settings_at(selection.start, cx)
 3323                            .always_treat_brackets_as_autoclosed;
 3324                        if always_treat_brackets_as_autoclosed
 3325                            && is_bracket_pair_end
 3326                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3327                        {
 3328                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3329                            // and the inserted text is a closing bracket and the selection is followed
 3330                            // by the closing bracket then move the selection past the closing bracket.
 3331                            let anchor = snapshot.anchor_after(selection.end);
 3332                            new_selections.push((selection.map(|_| anchor), text.len()));
 3333                            continue;
 3334                        }
 3335                    }
 3336                    // If an opening bracket is 1 character long and is typed while
 3337                    // text is selected, then surround that text with the bracket pair.
 3338                    else if auto_surround
 3339                        && bracket_pair.surround
 3340                        && is_bracket_pair_start
 3341                        && bracket_pair.start.chars().count() == 1
 3342                    {
 3343                        edits.push((selection.start..selection.start, text.clone()));
 3344                        edits.push((
 3345                            selection.end..selection.end,
 3346                            bracket_pair.end.as_str().into(),
 3347                        ));
 3348                        bracket_inserted = true;
 3349                        new_selections.push((
 3350                            Selection {
 3351                                id: selection.id,
 3352                                start: snapshot.anchor_after(selection.start),
 3353                                end: snapshot.anchor_before(selection.end),
 3354                                reversed: selection.reversed,
 3355                                goal: selection.goal,
 3356                            },
 3357                            0,
 3358                        ));
 3359                        continue;
 3360                    }
 3361                }
 3362            }
 3363
 3364            if self.auto_replace_emoji_shortcode
 3365                && selection.is_empty()
 3366                && text.as_ref().ends_with(':')
 3367            {
 3368                if let Some(possible_emoji_short_code) =
 3369                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3370                {
 3371                    if !possible_emoji_short_code.is_empty() {
 3372                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3373                            let emoji_shortcode_start = Point::new(
 3374                                selection.start.row,
 3375                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3376                            );
 3377
 3378                            // Remove shortcode from buffer
 3379                            edits.push((
 3380                                emoji_shortcode_start..selection.start,
 3381                                "".to_string().into(),
 3382                            ));
 3383                            new_selections.push((
 3384                                Selection {
 3385                                    id: selection.id,
 3386                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3387                                    end: snapshot.anchor_before(selection.start),
 3388                                    reversed: selection.reversed,
 3389                                    goal: selection.goal,
 3390                                },
 3391                                0,
 3392                            ));
 3393
 3394                            // Insert emoji
 3395                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3396                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3397                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3398
 3399                            continue;
 3400                        }
 3401                    }
 3402                }
 3403            }
 3404
 3405            // If not handling any auto-close operation, then just replace the selected
 3406            // text with the given input and move the selection to the end of the
 3407            // newly inserted text.
 3408            let anchor = snapshot.anchor_after(selection.end);
 3409            if !self.linked_edit_ranges.is_empty() {
 3410                let start_anchor = snapshot.anchor_before(selection.start);
 3411
 3412                let is_word_char = text.chars().next().map_or(true, |char| {
 3413                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3414                    classifier.is_word(char)
 3415                });
 3416
 3417                if is_word_char {
 3418                    if let Some(ranges) = self
 3419                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3420                    {
 3421                        for (buffer, edits) in ranges {
 3422                            linked_edits
 3423                                .entry(buffer.clone())
 3424                                .or_default()
 3425                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3426                        }
 3427                    }
 3428                }
 3429            }
 3430
 3431            new_selections.push((selection.map(|_| anchor), 0));
 3432            edits.push((selection.start..selection.end, text.clone()));
 3433        }
 3434
 3435        drop(snapshot);
 3436
 3437        self.transact(cx, |this, cx| {
 3438            this.buffer.update(cx, |buffer, cx| {
 3439                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3440            });
 3441            for (buffer, edits) in linked_edits {
 3442                buffer.update(cx, |buffer, cx| {
 3443                    let snapshot = buffer.snapshot();
 3444                    let edits = edits
 3445                        .into_iter()
 3446                        .map(|(range, text)| {
 3447                            use text::ToPoint as TP;
 3448                            let end_point = TP::to_point(&range.end, &snapshot);
 3449                            let start_point = TP::to_point(&range.start, &snapshot);
 3450                            (start_point..end_point, text)
 3451                        })
 3452                        .sorted_by_key(|(range, _)| range.start)
 3453                        .collect::<Vec<_>>();
 3454                    buffer.edit(edits, None, cx);
 3455                })
 3456            }
 3457            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3458            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3459            let snapshot = this.buffer.read(cx).read(cx);
 3460            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3461                .zip(new_selection_deltas)
 3462                .map(|(selection, delta)| Selection {
 3463                    id: selection.id,
 3464                    start: selection.start + delta,
 3465                    end: selection.end + delta,
 3466                    reversed: selection.reversed,
 3467                    goal: SelectionGoal::None,
 3468                })
 3469                .collect::<Vec<_>>();
 3470
 3471            let mut i = 0;
 3472            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3473                let position = position.to_offset(&snapshot) + delta;
 3474                let start = snapshot.anchor_before(position);
 3475                let end = snapshot.anchor_after(position);
 3476                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3477                    match existing_state.range.start.cmp(&start, &snapshot) {
 3478                        Ordering::Less => i += 1,
 3479                        Ordering::Greater => break,
 3480                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3481                            Ordering::Less => i += 1,
 3482                            Ordering::Equal => break,
 3483                            Ordering::Greater => break,
 3484                        },
 3485                    }
 3486                }
 3487                this.autoclose_regions.insert(
 3488                    i,
 3489                    AutocloseRegion {
 3490                        selection_id,
 3491                        range: start..end,
 3492                        pair,
 3493                    },
 3494                );
 3495            }
 3496
 3497            drop(snapshot);
 3498            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3499            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3500                s.select(new_selections)
 3501            });
 3502
 3503            if !bracket_inserted {
 3504                if let Some(on_type_format_task) =
 3505                    this.trigger_on_type_formatting(text.to_string(), cx)
 3506                {
 3507                    on_type_format_task.detach_and_log_err(cx);
 3508                }
 3509            }
 3510
 3511            let editor_settings = EditorSettings::get_global(cx);
 3512            if bracket_inserted
 3513                && (editor_settings.auto_signature_help
 3514                    || editor_settings.show_signature_help_after_edits)
 3515            {
 3516                this.show_signature_help(&ShowSignatureHelp, cx);
 3517            }
 3518
 3519            let trigger_in_words = !had_active_inline_completion;
 3520            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3521            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3522            this.refresh_inline_completion(true, false, cx);
 3523        });
 3524    }
 3525
 3526    fn find_possible_emoji_shortcode_at_position(
 3527        snapshot: &MultiBufferSnapshot,
 3528        position: Point,
 3529    ) -> Option<String> {
 3530        let mut chars = Vec::new();
 3531        let mut found_colon = false;
 3532        for char in snapshot.reversed_chars_at(position).take(100) {
 3533            // Found a possible emoji shortcode in the middle of the buffer
 3534            if found_colon {
 3535                if char.is_whitespace() {
 3536                    chars.reverse();
 3537                    return Some(chars.iter().collect());
 3538                }
 3539                // If the previous character is not a whitespace, we are in the middle of a word
 3540                // and we only want to complete the shortcode if the word is made up of other emojis
 3541                let mut containing_word = String::new();
 3542                for ch in snapshot
 3543                    .reversed_chars_at(position)
 3544                    .skip(chars.len() + 1)
 3545                    .take(100)
 3546                {
 3547                    if ch.is_whitespace() {
 3548                        break;
 3549                    }
 3550                    containing_word.push(ch);
 3551                }
 3552                let containing_word = containing_word.chars().rev().collect::<String>();
 3553                if util::word_consists_of_emojis(containing_word.as_str()) {
 3554                    chars.reverse();
 3555                    return Some(chars.iter().collect());
 3556                }
 3557            }
 3558
 3559            if char.is_whitespace() || !char.is_ascii() {
 3560                return None;
 3561            }
 3562            if char == ':' {
 3563                found_colon = true;
 3564            } else {
 3565                chars.push(char);
 3566            }
 3567        }
 3568        // Found a possible emoji shortcode at the beginning of the buffer
 3569        chars.reverse();
 3570        Some(chars.iter().collect())
 3571    }
 3572
 3573    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3574        self.transact(cx, |this, cx| {
 3575            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3576                let selections = this.selections.all::<usize>(cx);
 3577                let multi_buffer = this.buffer.read(cx);
 3578                let buffer = multi_buffer.snapshot(cx);
 3579                selections
 3580                    .iter()
 3581                    .map(|selection| {
 3582                        let start_point = selection.start.to_point(&buffer);
 3583                        let mut indent =
 3584                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3585                        indent.len = cmp::min(indent.len, start_point.column);
 3586                        let start = selection.start;
 3587                        let end = selection.end;
 3588                        let selection_is_empty = start == end;
 3589                        let language_scope = buffer.language_scope_at(start);
 3590                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3591                            &language_scope
 3592                        {
 3593                            let leading_whitespace_len = buffer
 3594                                .reversed_chars_at(start)
 3595                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3596                                .map(|c| c.len_utf8())
 3597                                .sum::<usize>();
 3598
 3599                            let trailing_whitespace_len = buffer
 3600                                .chars_at(end)
 3601                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3602                                .map(|c| c.len_utf8())
 3603                                .sum::<usize>();
 3604
 3605                            let insert_extra_newline =
 3606                                language.brackets().any(|(pair, enabled)| {
 3607                                    let pair_start = pair.start.trim_end();
 3608                                    let pair_end = pair.end.trim_start();
 3609
 3610                                    enabled
 3611                                        && pair.newline
 3612                                        && buffer.contains_str_at(
 3613                                            end + trailing_whitespace_len,
 3614                                            pair_end,
 3615                                        )
 3616                                        && buffer.contains_str_at(
 3617                                            (start - leading_whitespace_len)
 3618                                                .saturating_sub(pair_start.len()),
 3619                                            pair_start,
 3620                                        )
 3621                                });
 3622
 3623                            // Comment extension on newline is allowed only for cursor selections
 3624                            let comment_delimiter = maybe!({
 3625                                if !selection_is_empty {
 3626                                    return None;
 3627                                }
 3628
 3629                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3630                                    return None;
 3631                                }
 3632
 3633                                let delimiters = language.line_comment_prefixes();
 3634                                let max_len_of_delimiter =
 3635                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3636                                let (snapshot, range) =
 3637                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3638
 3639                                let mut index_of_first_non_whitespace = 0;
 3640                                let comment_candidate = snapshot
 3641                                    .chars_for_range(range)
 3642                                    .skip_while(|c| {
 3643                                        let should_skip = c.is_whitespace();
 3644                                        if should_skip {
 3645                                            index_of_first_non_whitespace += 1;
 3646                                        }
 3647                                        should_skip
 3648                                    })
 3649                                    .take(max_len_of_delimiter)
 3650                                    .collect::<String>();
 3651                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3652                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3653                                })?;
 3654                                let cursor_is_placed_after_comment_marker =
 3655                                    index_of_first_non_whitespace + comment_prefix.len()
 3656                                        <= start_point.column as usize;
 3657                                if cursor_is_placed_after_comment_marker {
 3658                                    Some(comment_prefix.clone())
 3659                                } else {
 3660                                    None
 3661                                }
 3662                            });
 3663                            (comment_delimiter, insert_extra_newline)
 3664                        } else {
 3665                            (None, false)
 3666                        };
 3667
 3668                        let capacity_for_delimiter = comment_delimiter
 3669                            .as_deref()
 3670                            .map(str::len)
 3671                            .unwrap_or_default();
 3672                        let mut new_text =
 3673                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3674                        new_text.push('\n');
 3675                        new_text.extend(indent.chars());
 3676                        if let Some(delimiter) = &comment_delimiter {
 3677                            new_text.push_str(delimiter);
 3678                        }
 3679                        if insert_extra_newline {
 3680                            new_text = new_text.repeat(2);
 3681                        }
 3682
 3683                        let anchor = buffer.anchor_after(end);
 3684                        let new_selection = selection.map(|_| anchor);
 3685                        (
 3686                            (start..end, new_text),
 3687                            (insert_extra_newline, new_selection),
 3688                        )
 3689                    })
 3690                    .unzip()
 3691            };
 3692
 3693            this.edit_with_autoindent(edits, cx);
 3694            let buffer = this.buffer.read(cx).snapshot(cx);
 3695            let new_selections = selection_fixup_info
 3696                .into_iter()
 3697                .map(|(extra_newline_inserted, new_selection)| {
 3698                    let mut cursor = new_selection.end.to_point(&buffer);
 3699                    if extra_newline_inserted {
 3700                        cursor.row -= 1;
 3701                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3702                    }
 3703                    new_selection.map(|_| cursor)
 3704                })
 3705                .collect();
 3706
 3707            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3708            this.refresh_inline_completion(true, false, cx);
 3709        });
 3710    }
 3711
 3712    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3713        let buffer = self.buffer.read(cx);
 3714        let snapshot = buffer.snapshot(cx);
 3715
 3716        let mut edits = Vec::new();
 3717        let mut rows = Vec::new();
 3718
 3719        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3720            let cursor = selection.head();
 3721            let row = cursor.row;
 3722
 3723            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3724
 3725            let newline = "\n".to_string();
 3726            edits.push((start_of_line..start_of_line, newline));
 3727
 3728            rows.push(row + rows_inserted as u32);
 3729        }
 3730
 3731        self.transact(cx, |editor, cx| {
 3732            editor.edit(edits, cx);
 3733
 3734            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3735                let mut index = 0;
 3736                s.move_cursors_with(|map, _, _| {
 3737                    let row = rows[index];
 3738                    index += 1;
 3739
 3740                    let point = Point::new(row, 0);
 3741                    let boundary = map.next_line_boundary(point).1;
 3742                    let clipped = map.clip_point(boundary, Bias::Left);
 3743
 3744                    (clipped, SelectionGoal::None)
 3745                });
 3746            });
 3747
 3748            let mut indent_edits = Vec::new();
 3749            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3750            for row in rows {
 3751                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3752                for (row, indent) in indents {
 3753                    if indent.len == 0 {
 3754                        continue;
 3755                    }
 3756
 3757                    let text = match indent.kind {
 3758                        IndentKind::Space => " ".repeat(indent.len as usize),
 3759                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3760                    };
 3761                    let point = Point::new(row.0, 0);
 3762                    indent_edits.push((point..point, text));
 3763                }
 3764            }
 3765            editor.edit(indent_edits, cx);
 3766        });
 3767    }
 3768
 3769    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3770        let buffer = self.buffer.read(cx);
 3771        let snapshot = buffer.snapshot(cx);
 3772
 3773        let mut edits = Vec::new();
 3774        let mut rows = Vec::new();
 3775        let mut rows_inserted = 0;
 3776
 3777        for selection in self.selections.all_adjusted(cx) {
 3778            let cursor = selection.head();
 3779            let row = cursor.row;
 3780
 3781            let point = Point::new(row + 1, 0);
 3782            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3783
 3784            let newline = "\n".to_string();
 3785            edits.push((start_of_line..start_of_line, newline));
 3786
 3787            rows_inserted += 1;
 3788            rows.push(row + rows_inserted);
 3789        }
 3790
 3791        self.transact(cx, |editor, cx| {
 3792            editor.edit(edits, cx);
 3793
 3794            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3795                let mut index = 0;
 3796                s.move_cursors_with(|map, _, _| {
 3797                    let row = rows[index];
 3798                    index += 1;
 3799
 3800                    let point = Point::new(row, 0);
 3801                    let boundary = map.next_line_boundary(point).1;
 3802                    let clipped = map.clip_point(boundary, Bias::Left);
 3803
 3804                    (clipped, SelectionGoal::None)
 3805                });
 3806            });
 3807
 3808            let mut indent_edits = Vec::new();
 3809            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3810            for row in rows {
 3811                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3812                for (row, indent) in indents {
 3813                    if indent.len == 0 {
 3814                        continue;
 3815                    }
 3816
 3817                    let text = match indent.kind {
 3818                        IndentKind::Space => " ".repeat(indent.len as usize),
 3819                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3820                    };
 3821                    let point = Point::new(row.0, 0);
 3822                    indent_edits.push((point..point, text));
 3823                }
 3824            }
 3825            editor.edit(indent_edits, cx);
 3826        });
 3827    }
 3828
 3829    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3830        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3831            original_indent_columns: Vec::new(),
 3832        });
 3833        self.insert_with_autoindent_mode(text, autoindent, cx);
 3834    }
 3835
 3836    fn insert_with_autoindent_mode(
 3837        &mut self,
 3838        text: &str,
 3839        autoindent_mode: Option<AutoindentMode>,
 3840        cx: &mut ViewContext<Self>,
 3841    ) {
 3842        if self.read_only(cx) {
 3843            return;
 3844        }
 3845
 3846        let text: Arc<str> = text.into();
 3847        self.transact(cx, |this, cx| {
 3848            let old_selections = this.selections.all_adjusted(cx);
 3849            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3850                let anchors = {
 3851                    let snapshot = buffer.read(cx);
 3852                    old_selections
 3853                        .iter()
 3854                        .map(|s| {
 3855                            let anchor = snapshot.anchor_after(s.head());
 3856                            s.map(|_| anchor)
 3857                        })
 3858                        .collect::<Vec<_>>()
 3859                };
 3860                buffer.edit(
 3861                    old_selections
 3862                        .iter()
 3863                        .map(|s| (s.start..s.end, text.clone())),
 3864                    autoindent_mode,
 3865                    cx,
 3866                );
 3867                anchors
 3868            });
 3869
 3870            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3871                s.select_anchors(selection_anchors);
 3872            })
 3873        });
 3874    }
 3875
 3876    fn trigger_completion_on_input(
 3877        &mut self,
 3878        text: &str,
 3879        trigger_in_words: bool,
 3880        cx: &mut ViewContext<Self>,
 3881    ) {
 3882        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3883            self.show_completions(
 3884                &ShowCompletions {
 3885                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3886                },
 3887                cx,
 3888            );
 3889        } else {
 3890            self.hide_context_menu(cx);
 3891        }
 3892    }
 3893
 3894    fn is_completion_trigger(
 3895        &self,
 3896        text: &str,
 3897        trigger_in_words: bool,
 3898        cx: &mut ViewContext<Self>,
 3899    ) -> bool {
 3900        let position = self.selections.newest_anchor().head();
 3901        let multibuffer = self.buffer.read(cx);
 3902        let Some(buffer) = position
 3903            .buffer_id
 3904            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3905        else {
 3906            return false;
 3907        };
 3908
 3909        if let Some(completion_provider) = &self.completion_provider {
 3910            completion_provider.is_completion_trigger(
 3911                &buffer,
 3912                position.text_anchor,
 3913                text,
 3914                trigger_in_words,
 3915                cx,
 3916            )
 3917        } else {
 3918            false
 3919        }
 3920    }
 3921
 3922    /// If any empty selections is touching the start of its innermost containing autoclose
 3923    /// region, expand it to select the brackets.
 3924    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3925        let selections = self.selections.all::<usize>(cx);
 3926        let buffer = self.buffer.read(cx).read(cx);
 3927        let new_selections = self
 3928            .selections_with_autoclose_regions(selections, &buffer)
 3929            .map(|(mut selection, region)| {
 3930                if !selection.is_empty() {
 3931                    return selection;
 3932                }
 3933
 3934                if let Some(region) = region {
 3935                    let mut range = region.range.to_offset(&buffer);
 3936                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3937                        range.start -= region.pair.start.len();
 3938                        if buffer.contains_str_at(range.start, &region.pair.start)
 3939                            && buffer.contains_str_at(range.end, &region.pair.end)
 3940                        {
 3941                            range.end += region.pair.end.len();
 3942                            selection.start = range.start;
 3943                            selection.end = range.end;
 3944
 3945                            return selection;
 3946                        }
 3947                    }
 3948                }
 3949
 3950                let always_treat_brackets_as_autoclosed = buffer
 3951                    .settings_at(selection.start, cx)
 3952                    .always_treat_brackets_as_autoclosed;
 3953
 3954                if !always_treat_brackets_as_autoclosed {
 3955                    return selection;
 3956                }
 3957
 3958                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3959                    for (pair, enabled) in scope.brackets() {
 3960                        if !enabled || !pair.close {
 3961                            continue;
 3962                        }
 3963
 3964                        if buffer.contains_str_at(selection.start, &pair.end) {
 3965                            let pair_start_len = pair.start.len();
 3966                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3967                            {
 3968                                selection.start -= pair_start_len;
 3969                                selection.end += pair.end.len();
 3970
 3971                                return selection;
 3972                            }
 3973                        }
 3974                    }
 3975                }
 3976
 3977                selection
 3978            })
 3979            .collect();
 3980
 3981        drop(buffer);
 3982        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3983    }
 3984
 3985    /// Iterate the given selections, and for each one, find the smallest surrounding
 3986    /// autoclose region. This uses the ordering of the selections and the autoclose
 3987    /// regions to avoid repeated comparisons.
 3988    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3989        &'a self,
 3990        selections: impl IntoIterator<Item = Selection<D>>,
 3991        buffer: &'a MultiBufferSnapshot,
 3992    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3993        let mut i = 0;
 3994        let mut regions = self.autoclose_regions.as_slice();
 3995        selections.into_iter().map(move |selection| {
 3996            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3997
 3998            let mut enclosing = None;
 3999            while let Some(pair_state) = regions.get(i) {
 4000                if pair_state.range.end.to_offset(buffer) < range.start {
 4001                    regions = &regions[i + 1..];
 4002                    i = 0;
 4003                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4004                    break;
 4005                } else {
 4006                    if pair_state.selection_id == selection.id {
 4007                        enclosing = Some(pair_state);
 4008                    }
 4009                    i += 1;
 4010                }
 4011            }
 4012
 4013            (selection.clone(), enclosing)
 4014        })
 4015    }
 4016
 4017    /// Remove any autoclose regions that no longer contain their selection.
 4018    fn invalidate_autoclose_regions(
 4019        &mut self,
 4020        mut selections: &[Selection<Anchor>],
 4021        buffer: &MultiBufferSnapshot,
 4022    ) {
 4023        self.autoclose_regions.retain(|state| {
 4024            let mut i = 0;
 4025            while let Some(selection) = selections.get(i) {
 4026                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4027                    selections = &selections[1..];
 4028                    continue;
 4029                }
 4030                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4031                    break;
 4032                }
 4033                if selection.id == state.selection_id {
 4034                    return true;
 4035                } else {
 4036                    i += 1;
 4037                }
 4038            }
 4039            false
 4040        });
 4041    }
 4042
 4043    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4044        let offset = position.to_offset(buffer);
 4045        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4046        if offset > word_range.start && kind == Some(CharKind::Word) {
 4047            Some(
 4048                buffer
 4049                    .text_for_range(word_range.start..offset)
 4050                    .collect::<String>(),
 4051            )
 4052        } else {
 4053            None
 4054        }
 4055    }
 4056
 4057    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4058        self.refresh_inlay_hints(
 4059            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4060            cx,
 4061        );
 4062    }
 4063
 4064    pub fn inlay_hints_enabled(&self) -> bool {
 4065        self.inlay_hint_cache.enabled
 4066    }
 4067
 4068    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4069        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4070            return;
 4071        }
 4072
 4073        let reason_description = reason.description();
 4074        let ignore_debounce = matches!(
 4075            reason,
 4076            InlayHintRefreshReason::SettingsChange(_)
 4077                | InlayHintRefreshReason::Toggle(_)
 4078                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4079        );
 4080        let (invalidate_cache, required_languages) = match reason {
 4081            InlayHintRefreshReason::Toggle(enabled) => {
 4082                self.inlay_hint_cache.enabled = enabled;
 4083                if enabled {
 4084                    (InvalidationStrategy::RefreshRequested, None)
 4085                } else {
 4086                    self.inlay_hint_cache.clear();
 4087                    self.splice_inlays(
 4088                        self.visible_inlay_hints(cx)
 4089                            .iter()
 4090                            .map(|inlay| inlay.id)
 4091                            .collect(),
 4092                        Vec::new(),
 4093                        cx,
 4094                    );
 4095                    return;
 4096                }
 4097            }
 4098            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4099                match self.inlay_hint_cache.update_settings(
 4100                    &self.buffer,
 4101                    new_settings,
 4102                    self.visible_inlay_hints(cx),
 4103                    cx,
 4104                ) {
 4105                    ControlFlow::Break(Some(InlaySplice {
 4106                        to_remove,
 4107                        to_insert,
 4108                    })) => {
 4109                        self.splice_inlays(to_remove, to_insert, cx);
 4110                        return;
 4111                    }
 4112                    ControlFlow::Break(None) => return,
 4113                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4114                }
 4115            }
 4116            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4117                if let Some(InlaySplice {
 4118                    to_remove,
 4119                    to_insert,
 4120                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4121                {
 4122                    self.splice_inlays(to_remove, to_insert, cx);
 4123                }
 4124                return;
 4125            }
 4126            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4127            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4128                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4129            }
 4130            InlayHintRefreshReason::RefreshRequested => {
 4131                (InvalidationStrategy::RefreshRequested, None)
 4132            }
 4133        };
 4134
 4135        if let Some(InlaySplice {
 4136            to_remove,
 4137            to_insert,
 4138        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4139            reason_description,
 4140            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4141            invalidate_cache,
 4142            ignore_debounce,
 4143            cx,
 4144        ) {
 4145            self.splice_inlays(to_remove, to_insert, cx);
 4146        }
 4147    }
 4148
 4149    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4150        self.display_map
 4151            .read(cx)
 4152            .current_inlays()
 4153            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4154            .cloned()
 4155            .collect()
 4156    }
 4157
 4158    pub fn excerpts_for_inlay_hints_query(
 4159        &self,
 4160        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4161        cx: &mut ViewContext<Editor>,
 4162    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4163        let Some(project) = self.project.as_ref() else {
 4164            return HashMap::default();
 4165        };
 4166        let project = project.read(cx);
 4167        let multi_buffer = self.buffer().read(cx);
 4168        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4169        let multi_buffer_visible_start = self
 4170            .scroll_manager
 4171            .anchor()
 4172            .anchor
 4173            .to_point(&multi_buffer_snapshot);
 4174        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4175            multi_buffer_visible_start
 4176                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4177            Bias::Left,
 4178        );
 4179        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4180        multi_buffer
 4181            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4182            .into_iter()
 4183            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4184            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4185                let buffer = buffer_handle.read(cx);
 4186                let buffer_file = project::File::from_dyn(buffer.file())?;
 4187                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4188                let worktree_entry = buffer_worktree
 4189                    .read(cx)
 4190                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4191                if worktree_entry.is_ignored {
 4192                    return None;
 4193                }
 4194
 4195                let language = buffer.language()?;
 4196                if let Some(restrict_to_languages) = restrict_to_languages {
 4197                    if !restrict_to_languages.contains(language) {
 4198                        return None;
 4199                    }
 4200                }
 4201                Some((
 4202                    excerpt_id,
 4203                    (
 4204                        buffer_handle,
 4205                        buffer.version().clone(),
 4206                        excerpt_visible_range,
 4207                    ),
 4208                ))
 4209            })
 4210            .collect()
 4211    }
 4212
 4213    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4214        TextLayoutDetails {
 4215            text_system: cx.text_system().clone(),
 4216            editor_style: self.style.clone().unwrap(),
 4217            rem_size: cx.rem_size(),
 4218            scroll_anchor: self.scroll_manager.anchor(),
 4219            visible_rows: self.visible_line_count(),
 4220            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4221        }
 4222    }
 4223
 4224    fn splice_inlays(
 4225        &self,
 4226        to_remove: Vec<InlayId>,
 4227        to_insert: Vec<Inlay>,
 4228        cx: &mut ViewContext<Self>,
 4229    ) {
 4230        self.display_map.update(cx, |display_map, cx| {
 4231            display_map.splice_inlays(to_remove, to_insert, cx);
 4232        });
 4233        cx.notify();
 4234    }
 4235
 4236    fn trigger_on_type_formatting(
 4237        &self,
 4238        input: String,
 4239        cx: &mut ViewContext<Self>,
 4240    ) -> Option<Task<Result<()>>> {
 4241        if input.len() != 1 {
 4242            return None;
 4243        }
 4244
 4245        let project = self.project.as_ref()?;
 4246        let position = self.selections.newest_anchor().head();
 4247        let (buffer, buffer_position) = self
 4248            .buffer
 4249            .read(cx)
 4250            .text_anchor_for_position(position, cx)?;
 4251
 4252        let settings = language_settings::language_settings(
 4253            buffer.read(cx).language_at(buffer_position).as_ref(),
 4254            buffer.read(cx).file(),
 4255            cx,
 4256        );
 4257        if !settings.use_on_type_format {
 4258            return None;
 4259        }
 4260
 4261        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4262        // hence we do LSP request & edit on host side only — add formats to host's history.
 4263        let push_to_lsp_host_history = true;
 4264        // If this is not the host, append its history with new edits.
 4265        let push_to_client_history = project.read(cx).is_via_collab();
 4266
 4267        let on_type_formatting = project.update(cx, |project, cx| {
 4268            project.on_type_format(
 4269                buffer.clone(),
 4270                buffer_position,
 4271                input,
 4272                push_to_lsp_host_history,
 4273                cx,
 4274            )
 4275        });
 4276        Some(cx.spawn(|editor, mut cx| async move {
 4277            if let Some(transaction) = on_type_formatting.await? {
 4278                if push_to_client_history {
 4279                    buffer
 4280                        .update(&mut cx, |buffer, _| {
 4281                            buffer.push_transaction(transaction, Instant::now());
 4282                        })
 4283                        .ok();
 4284                }
 4285                editor.update(&mut cx, |editor, cx| {
 4286                    editor.refresh_document_highlights(cx);
 4287                })?;
 4288            }
 4289            Ok(())
 4290        }))
 4291    }
 4292
 4293    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4294        if self.pending_rename.is_some() {
 4295            return;
 4296        }
 4297
 4298        let Some(provider) = self.completion_provider.as_ref() else {
 4299            return;
 4300        };
 4301
 4302        let position = self.selections.newest_anchor().head();
 4303        let (buffer, buffer_position) =
 4304            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4305                output
 4306            } else {
 4307                return;
 4308            };
 4309
 4310        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4311        let is_followup_invoke = {
 4312            let context_menu_state = self.context_menu.read();
 4313            matches!(
 4314                context_menu_state.deref(),
 4315                Some(ContextMenu::Completions(_))
 4316            )
 4317        };
 4318        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4319            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4320            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4321                CompletionTriggerKind::TRIGGER_CHARACTER
 4322            }
 4323
 4324            _ => CompletionTriggerKind::INVOKED,
 4325        };
 4326        let completion_context = CompletionContext {
 4327            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4328                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4329                    Some(String::from(trigger))
 4330                } else {
 4331                    None
 4332                }
 4333            }),
 4334            trigger_kind,
 4335        };
 4336        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4337        let sort_completions = provider.sort_completions();
 4338
 4339        let id = post_inc(&mut self.next_completion_id);
 4340        let task = cx.spawn(|this, mut cx| {
 4341            async move {
 4342                this.update(&mut cx, |this, _| {
 4343                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4344                })?;
 4345                let completions = completions.await.log_err();
 4346                let menu = if let Some(completions) = completions {
 4347                    let mut menu = CompletionsMenu {
 4348                        id,
 4349                        sort_completions,
 4350                        initial_position: position,
 4351                        match_candidates: completions
 4352                            .iter()
 4353                            .enumerate()
 4354                            .map(|(id, completion)| {
 4355                                StringMatchCandidate::new(
 4356                                    id,
 4357                                    completion.label.text[completion.label.filter_range.clone()]
 4358                                        .into(),
 4359                                )
 4360                            })
 4361                            .collect(),
 4362                        buffer: buffer.clone(),
 4363                        completions: Arc::new(RwLock::new(completions.into())),
 4364                        matches: Vec::new().into(),
 4365                        selected_item: 0,
 4366                        scroll_handle: UniformListScrollHandle::new(),
 4367                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4368                            DebouncedDelay::new(),
 4369                        )),
 4370                    };
 4371                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4372                        .await;
 4373
 4374                    if menu.matches.is_empty() {
 4375                        None
 4376                    } else {
 4377                        this.update(&mut cx, |editor, cx| {
 4378                            let completions = menu.completions.clone();
 4379                            let matches = menu.matches.clone();
 4380
 4381                            let delay_ms = EditorSettings::get_global(cx)
 4382                                .completion_documentation_secondary_query_debounce;
 4383                            let delay = Duration::from_millis(delay_ms);
 4384                            editor
 4385                                .completion_documentation_pre_resolve_debounce
 4386                                .fire_new(delay, cx, |editor, cx| {
 4387                                    CompletionsMenu::pre_resolve_completion_documentation(
 4388                                        buffer,
 4389                                        completions,
 4390                                        matches,
 4391                                        editor,
 4392                                        cx,
 4393                                    )
 4394                                });
 4395                        })
 4396                        .ok();
 4397                        Some(menu)
 4398                    }
 4399                } else {
 4400                    None
 4401                };
 4402
 4403                this.update(&mut cx, |this, cx| {
 4404                    let mut context_menu = this.context_menu.write();
 4405                    match context_menu.as_ref() {
 4406                        None => {}
 4407
 4408                        Some(ContextMenu::Completions(prev_menu)) => {
 4409                            if prev_menu.id > id {
 4410                                return;
 4411                            }
 4412                        }
 4413
 4414                        _ => return,
 4415                    }
 4416
 4417                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4418                        let menu = menu.unwrap();
 4419                        *context_menu = Some(ContextMenu::Completions(menu));
 4420                        drop(context_menu);
 4421                        this.discard_inline_completion(false, cx);
 4422                        cx.notify();
 4423                    } else if this.completion_tasks.len() <= 1 {
 4424                        // If there are no more completion tasks and the last menu was
 4425                        // empty, we should hide it. If it was already hidden, we should
 4426                        // also show the copilot completion when available.
 4427                        drop(context_menu);
 4428                        if this.hide_context_menu(cx).is_none() {
 4429                            this.update_visible_inline_completion(cx);
 4430                        }
 4431                    }
 4432                })?;
 4433
 4434                Ok::<_, anyhow::Error>(())
 4435            }
 4436            .log_err()
 4437        });
 4438
 4439        self.completion_tasks.push((id, task));
 4440    }
 4441
 4442    pub fn confirm_completion(
 4443        &mut self,
 4444        action: &ConfirmCompletion,
 4445        cx: &mut ViewContext<Self>,
 4446    ) -> Option<Task<Result<()>>> {
 4447        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4448    }
 4449
 4450    pub fn compose_completion(
 4451        &mut self,
 4452        action: &ComposeCompletion,
 4453        cx: &mut ViewContext<Self>,
 4454    ) -> Option<Task<Result<()>>> {
 4455        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4456    }
 4457
 4458    fn do_completion(
 4459        &mut self,
 4460        item_ix: Option<usize>,
 4461        intent: CompletionIntent,
 4462        cx: &mut ViewContext<Self>,
 4463    ) -> Option<Task<anyhow::Result<()>>> {
 4464        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4465            menu
 4466        } else {
 4467            return None;
 4468        };
 4469
 4470        let mut resolve_task_store = completions_menu
 4471            .selected_completion_documentation_resolve_debounce
 4472            .lock();
 4473        let selected_completion_resolve = resolve_task_store.start_now();
 4474        let menu_pre_resolve = self
 4475            .completion_documentation_pre_resolve_debounce
 4476            .start_now();
 4477        drop(resolve_task_store);
 4478
 4479        Some(cx.spawn(|editor, mut cx| async move {
 4480            match (selected_completion_resolve, menu_pre_resolve) {
 4481                (None, None) => {}
 4482                (Some(resolve), None) | (None, Some(resolve)) => resolve.await,
 4483                (Some(resolve_1), Some(resolve_2)) => {
 4484                    futures::join!(resolve_1, resolve_2);
 4485                }
 4486            }
 4487            if let Some(apply_edits_task) = editor.update(&mut cx, |editor, cx| {
 4488                editor.apply_resolved_completion(completions_menu, item_ix, intent, cx)
 4489            })? {
 4490                apply_edits_task.await?;
 4491            }
 4492            Ok(())
 4493        }))
 4494    }
 4495
 4496    fn apply_resolved_completion(
 4497        &mut self,
 4498        completions_menu: CompletionsMenu,
 4499        item_ix: Option<usize>,
 4500        intent: CompletionIntent,
 4501        cx: &mut ViewContext<'_, Editor>,
 4502    ) -> Option<Task<anyhow::Result<Option<language::Transaction>>>> {
 4503        use language::ToOffset as _;
 4504
 4505        let mat = completions_menu
 4506            .matches
 4507            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4508        let buffer_handle = completions_menu.buffer;
 4509        let completions = completions_menu.completions.read();
 4510        let completion = completions.get(mat.candidate_id)?;
 4511        cx.stop_propagation();
 4512
 4513        let snippet;
 4514        let text;
 4515
 4516        if completion.is_snippet() {
 4517            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4518            text = snippet.as_ref().unwrap().text.clone();
 4519        } else {
 4520            snippet = None;
 4521            text = completion.new_text.clone();
 4522        };
 4523        let selections = self.selections.all::<usize>(cx);
 4524        let buffer = buffer_handle.read(cx);
 4525        let old_range = completion.old_range.to_offset(buffer);
 4526        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4527
 4528        let newest_selection = self.selections.newest_anchor();
 4529        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4530            return None;
 4531        }
 4532
 4533        let lookbehind = newest_selection
 4534            .start
 4535            .text_anchor
 4536            .to_offset(buffer)
 4537            .saturating_sub(old_range.start);
 4538        let lookahead = old_range
 4539            .end
 4540            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4541        let mut common_prefix_len = old_text
 4542            .bytes()
 4543            .zip(text.bytes())
 4544            .take_while(|(a, b)| a == b)
 4545            .count();
 4546
 4547        let snapshot = self.buffer.read(cx).snapshot(cx);
 4548        let mut range_to_replace: Option<Range<isize>> = None;
 4549        let mut ranges = Vec::new();
 4550        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4551        for selection in &selections {
 4552            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4553                let start = selection.start.saturating_sub(lookbehind);
 4554                let end = selection.end + lookahead;
 4555                if selection.id == newest_selection.id {
 4556                    range_to_replace = Some(
 4557                        ((start + common_prefix_len) as isize - selection.start as isize)
 4558                            ..(end as isize - selection.start as isize),
 4559                    );
 4560                }
 4561                ranges.push(start + common_prefix_len..end);
 4562            } else {
 4563                common_prefix_len = 0;
 4564                ranges.clear();
 4565                ranges.extend(selections.iter().map(|s| {
 4566                    if s.id == newest_selection.id {
 4567                        range_to_replace = Some(
 4568                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4569                                - selection.start as isize
 4570                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4571                                    - selection.start as isize,
 4572                        );
 4573                        old_range.clone()
 4574                    } else {
 4575                        s.start..s.end
 4576                    }
 4577                }));
 4578                break;
 4579            }
 4580            if !self.linked_edit_ranges.is_empty() {
 4581                let start_anchor = snapshot.anchor_before(selection.head());
 4582                let end_anchor = snapshot.anchor_after(selection.tail());
 4583                if let Some(ranges) = self
 4584                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4585                {
 4586                    for (buffer, edits) in ranges {
 4587                        linked_edits.entry(buffer.clone()).or_default().extend(
 4588                            edits
 4589                                .into_iter()
 4590                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4591                        );
 4592                    }
 4593                }
 4594            }
 4595        }
 4596        let text = &text[common_prefix_len..];
 4597
 4598        cx.emit(EditorEvent::InputHandled {
 4599            utf16_range_to_replace: range_to_replace,
 4600            text: text.into(),
 4601        });
 4602
 4603        self.transact(cx, |this, cx| {
 4604            if let Some(mut snippet) = snippet {
 4605                snippet.text = text.to_string();
 4606                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4607                    tabstop.start -= common_prefix_len as isize;
 4608                    tabstop.end -= common_prefix_len as isize;
 4609                }
 4610
 4611                this.insert_snippet(&ranges, snippet, cx).log_err();
 4612            } else {
 4613                this.buffer.update(cx, |buffer, cx| {
 4614                    buffer.edit(
 4615                        ranges.iter().map(|range| (range.clone(), text)),
 4616                        this.autoindent_mode.clone(),
 4617                        cx,
 4618                    );
 4619                });
 4620            }
 4621            for (buffer, edits) in linked_edits {
 4622                buffer.update(cx, |buffer, cx| {
 4623                    let snapshot = buffer.snapshot();
 4624                    let edits = edits
 4625                        .into_iter()
 4626                        .map(|(range, text)| {
 4627                            use text::ToPoint as TP;
 4628                            let end_point = TP::to_point(&range.end, &snapshot);
 4629                            let start_point = TP::to_point(&range.start, &snapshot);
 4630                            (start_point..end_point, text)
 4631                        })
 4632                        .sorted_by_key(|(range, _)| range.start)
 4633                        .collect::<Vec<_>>();
 4634                    buffer.edit(edits, None, cx);
 4635                })
 4636            }
 4637
 4638            this.refresh_inline_completion(true, false, cx);
 4639        });
 4640
 4641        let show_new_completions_on_confirm = completion
 4642            .confirm
 4643            .as_ref()
 4644            .map_or(false, |confirm| confirm(intent, cx));
 4645        if show_new_completions_on_confirm {
 4646            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4647        }
 4648
 4649        let provider = self.completion_provider.as_ref()?;
 4650        let apply_edits = provider.apply_additional_edits_for_completion(
 4651            buffer_handle,
 4652            completion.clone(),
 4653            true,
 4654            cx,
 4655        );
 4656
 4657        let editor_settings = EditorSettings::get_global(cx);
 4658        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4659            // After the code completion is finished, users often want to know what signatures are needed.
 4660            // so we should automatically call signature_help
 4661            self.show_signature_help(&ShowSignatureHelp, cx);
 4662        }
 4663        Some(apply_edits)
 4664    }
 4665
 4666    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4667        let mut context_menu = self.context_menu.write();
 4668        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4669            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4670                // Toggle if we're selecting the same one
 4671                *context_menu = None;
 4672                cx.notify();
 4673                return;
 4674            } else {
 4675                // Otherwise, clear it and start a new one
 4676                *context_menu = None;
 4677                cx.notify();
 4678            }
 4679        }
 4680        drop(context_menu);
 4681        let snapshot = self.snapshot(cx);
 4682        let deployed_from_indicator = action.deployed_from_indicator;
 4683        let mut task = self.code_actions_task.take();
 4684        let action = action.clone();
 4685        cx.spawn(|editor, mut cx| async move {
 4686            while let Some(prev_task) = task {
 4687                prev_task.await.log_err();
 4688                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4689            }
 4690
 4691            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4692                if editor.focus_handle.is_focused(cx) {
 4693                    let multibuffer_point = action
 4694                        .deployed_from_indicator
 4695                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4696                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4697                    let (buffer, buffer_row) = snapshot
 4698                        .buffer_snapshot
 4699                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4700                        .and_then(|(buffer_snapshot, range)| {
 4701                            editor
 4702                                .buffer
 4703                                .read(cx)
 4704                                .buffer(buffer_snapshot.remote_id())
 4705                                .map(|buffer| (buffer, range.start.row))
 4706                        })?;
 4707                    let (_, code_actions) = editor
 4708                        .available_code_actions
 4709                        .clone()
 4710                        .and_then(|(location, code_actions)| {
 4711                            let snapshot = location.buffer.read(cx).snapshot();
 4712                            let point_range = location.range.to_point(&snapshot);
 4713                            let point_range = point_range.start.row..=point_range.end.row;
 4714                            if point_range.contains(&buffer_row) {
 4715                                Some((location, code_actions))
 4716                            } else {
 4717                                None
 4718                            }
 4719                        })
 4720                        .unzip();
 4721                    let buffer_id = buffer.read(cx).remote_id();
 4722                    let tasks = editor
 4723                        .tasks
 4724                        .get(&(buffer_id, buffer_row))
 4725                        .map(|t| Arc::new(t.to_owned()));
 4726                    if tasks.is_none() && code_actions.is_none() {
 4727                        return None;
 4728                    }
 4729
 4730                    editor.completion_tasks.clear();
 4731                    editor.discard_inline_completion(false, cx);
 4732                    let task_context =
 4733                        tasks
 4734                            .as_ref()
 4735                            .zip(editor.project.clone())
 4736                            .map(|(tasks, project)| {
 4737                                let position = Point::new(buffer_row, tasks.column);
 4738                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4739                                let location = Location {
 4740                                    buffer: buffer.clone(),
 4741                                    range: range_start..range_start,
 4742                                };
 4743                                // Fill in the environmental variables from the tree-sitter captures
 4744                                let mut captured_task_variables = TaskVariables::default();
 4745                                for (capture_name, value) in tasks.extra_variables.clone() {
 4746                                    captured_task_variables.insert(
 4747                                        task::VariableName::Custom(capture_name.into()),
 4748                                        value.clone(),
 4749                                    );
 4750                                }
 4751                                project.update(cx, |project, cx| {
 4752                                    project.task_store().update(cx, |task_store, cx| {
 4753                                        task_store.task_context_for_location(
 4754                                            captured_task_variables,
 4755                                            location,
 4756                                            cx,
 4757                                        )
 4758                                    })
 4759                                })
 4760                            });
 4761
 4762                    Some(cx.spawn(|editor, mut cx| async move {
 4763                        let task_context = match task_context {
 4764                            Some(task_context) => task_context.await,
 4765                            None => None,
 4766                        };
 4767                        let resolved_tasks =
 4768                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4769                                Arc::new(ResolvedTasks {
 4770                                    templates: tasks
 4771                                        .templates
 4772                                        .iter()
 4773                                        .filter_map(|(kind, template)| {
 4774                                            template
 4775                                                .resolve_task(&kind.to_id_base(), &task_context)
 4776                                                .map(|task| (kind.clone(), task))
 4777                                        })
 4778                                        .collect(),
 4779                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4780                                        multibuffer_point.row,
 4781                                        tasks.column,
 4782                                    )),
 4783                                })
 4784                            });
 4785                        let spawn_straight_away = resolved_tasks
 4786                            .as_ref()
 4787                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4788                            && code_actions
 4789                                .as_ref()
 4790                                .map_or(true, |actions| actions.is_empty());
 4791                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4792                            *editor.context_menu.write() =
 4793                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4794                                    buffer,
 4795                                    actions: CodeActionContents {
 4796                                        tasks: resolved_tasks,
 4797                                        actions: code_actions,
 4798                                    },
 4799                                    selected_item: Default::default(),
 4800                                    scroll_handle: UniformListScrollHandle::default(),
 4801                                    deployed_from_indicator,
 4802                                }));
 4803                            if spawn_straight_away {
 4804                                if let Some(task) = editor.confirm_code_action(
 4805                                    &ConfirmCodeAction { item_ix: Some(0) },
 4806                                    cx,
 4807                                ) {
 4808                                    cx.notify();
 4809                                    return task;
 4810                                }
 4811                            }
 4812                            cx.notify();
 4813                            Task::ready(Ok(()))
 4814                        }) {
 4815                            task.await
 4816                        } else {
 4817                            Ok(())
 4818                        }
 4819                    }))
 4820                } else {
 4821                    Some(Task::ready(Ok(())))
 4822                }
 4823            })?;
 4824            if let Some(task) = spawned_test_task {
 4825                task.await?;
 4826            }
 4827
 4828            Ok::<_, anyhow::Error>(())
 4829        })
 4830        .detach_and_log_err(cx);
 4831    }
 4832
 4833    pub fn confirm_code_action(
 4834        &mut self,
 4835        action: &ConfirmCodeAction,
 4836        cx: &mut ViewContext<Self>,
 4837    ) -> Option<Task<Result<()>>> {
 4838        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4839            menu
 4840        } else {
 4841            return None;
 4842        };
 4843        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4844        let action = actions_menu.actions.get(action_ix)?;
 4845        let title = action.label();
 4846        let buffer = actions_menu.buffer;
 4847        let workspace = self.workspace()?;
 4848
 4849        match action {
 4850            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4851                workspace.update(cx, |workspace, cx| {
 4852                    workspace::tasks::schedule_resolved_task(
 4853                        workspace,
 4854                        task_source_kind,
 4855                        resolved_task,
 4856                        false,
 4857                        cx,
 4858                    );
 4859
 4860                    Some(Task::ready(Ok(())))
 4861                })
 4862            }
 4863            CodeActionsItem::CodeAction {
 4864                excerpt_id,
 4865                action,
 4866                provider,
 4867            } => {
 4868                let apply_code_action =
 4869                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4870                let workspace = workspace.downgrade();
 4871                Some(cx.spawn(|editor, cx| async move {
 4872                    let project_transaction = apply_code_action.await?;
 4873                    Self::open_project_transaction(
 4874                        &editor,
 4875                        workspace,
 4876                        project_transaction,
 4877                        title,
 4878                        cx,
 4879                    )
 4880                    .await
 4881                }))
 4882            }
 4883        }
 4884    }
 4885
 4886    pub async fn open_project_transaction(
 4887        this: &WeakView<Editor>,
 4888        workspace: WeakView<Workspace>,
 4889        transaction: ProjectTransaction,
 4890        title: String,
 4891        mut cx: AsyncWindowContext,
 4892    ) -> Result<()> {
 4893        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4894        cx.update(|cx| {
 4895            entries.sort_unstable_by_key(|(buffer, _)| {
 4896                buffer.read(cx).file().map(|f| f.path().clone())
 4897            });
 4898        })?;
 4899
 4900        // If the project transaction's edits are all contained within this editor, then
 4901        // avoid opening a new editor to display them.
 4902
 4903        if let Some((buffer, transaction)) = entries.first() {
 4904            if entries.len() == 1 {
 4905                let excerpt = this.update(&mut cx, |editor, cx| {
 4906                    editor
 4907                        .buffer()
 4908                        .read(cx)
 4909                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4910                })?;
 4911                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4912                    if excerpted_buffer == *buffer {
 4913                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4914                            let excerpt_range = excerpt_range.to_offset(buffer);
 4915                            buffer
 4916                                .edited_ranges_for_transaction::<usize>(transaction)
 4917                                .all(|range| {
 4918                                    excerpt_range.start <= range.start
 4919                                        && excerpt_range.end >= range.end
 4920                                })
 4921                        })?;
 4922
 4923                        if all_edits_within_excerpt {
 4924                            return Ok(());
 4925                        }
 4926                    }
 4927                }
 4928            }
 4929        } else {
 4930            return Ok(());
 4931        }
 4932
 4933        let mut ranges_to_highlight = Vec::new();
 4934        let excerpt_buffer = cx.new_model(|cx| {
 4935            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4936            for (buffer_handle, transaction) in &entries {
 4937                let buffer = buffer_handle.read(cx);
 4938                ranges_to_highlight.extend(
 4939                    multibuffer.push_excerpts_with_context_lines(
 4940                        buffer_handle.clone(),
 4941                        buffer
 4942                            .edited_ranges_for_transaction::<usize>(transaction)
 4943                            .collect(),
 4944                        DEFAULT_MULTIBUFFER_CONTEXT,
 4945                        cx,
 4946                    ),
 4947                );
 4948            }
 4949            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4950            multibuffer
 4951        })?;
 4952
 4953        workspace.update(&mut cx, |workspace, cx| {
 4954            let project = workspace.project().clone();
 4955            let editor =
 4956                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4957            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4958            editor.update(cx, |editor, cx| {
 4959                editor.highlight_background::<Self>(
 4960                    &ranges_to_highlight,
 4961                    |theme| theme.editor_highlighted_line_background,
 4962                    cx,
 4963                );
 4964            });
 4965        })?;
 4966
 4967        Ok(())
 4968    }
 4969
 4970    pub fn clear_code_action_providers(&mut self) {
 4971        self.code_action_providers.clear();
 4972        self.available_code_actions.take();
 4973    }
 4974
 4975    pub fn push_code_action_provider(
 4976        &mut self,
 4977        provider: Arc<dyn CodeActionProvider>,
 4978        cx: &mut ViewContext<Self>,
 4979    ) {
 4980        self.code_action_providers.push(provider);
 4981        self.refresh_code_actions(cx);
 4982    }
 4983
 4984    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4985        let buffer = self.buffer.read(cx);
 4986        let newest_selection = self.selections.newest_anchor().clone();
 4987        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4988        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4989        if start_buffer != end_buffer {
 4990            return None;
 4991        }
 4992
 4993        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4994            cx.background_executor()
 4995                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4996                .await;
 4997
 4998            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4999                let providers = this.code_action_providers.clone();
 5000                let tasks = this
 5001                    .code_action_providers
 5002                    .iter()
 5003                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5004                    .collect::<Vec<_>>();
 5005                (providers, tasks)
 5006            })?;
 5007
 5008            let mut actions = Vec::new();
 5009            for (provider, provider_actions) in
 5010                providers.into_iter().zip(future::join_all(tasks).await)
 5011            {
 5012                if let Some(provider_actions) = provider_actions.log_err() {
 5013                    actions.extend(provider_actions.into_iter().map(|action| {
 5014                        AvailableCodeAction {
 5015                            excerpt_id: newest_selection.start.excerpt_id,
 5016                            action,
 5017                            provider: provider.clone(),
 5018                        }
 5019                    }));
 5020                }
 5021            }
 5022
 5023            this.update(&mut cx, |this, cx| {
 5024                this.available_code_actions = if actions.is_empty() {
 5025                    None
 5026                } else {
 5027                    Some((
 5028                        Location {
 5029                            buffer: start_buffer,
 5030                            range: start..end,
 5031                        },
 5032                        actions.into(),
 5033                    ))
 5034                };
 5035                cx.notify();
 5036            })
 5037        }));
 5038        None
 5039    }
 5040
 5041    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5042        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5043            self.show_git_blame_inline = false;
 5044
 5045            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5046                cx.background_executor().timer(delay).await;
 5047
 5048                this.update(&mut cx, |this, cx| {
 5049                    this.show_git_blame_inline = true;
 5050                    cx.notify();
 5051                })
 5052                .log_err();
 5053            }));
 5054        }
 5055    }
 5056
 5057    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5058        if self.pending_rename.is_some() {
 5059            return None;
 5060        }
 5061
 5062        let provider = self.semantics_provider.clone()?;
 5063        let buffer = self.buffer.read(cx);
 5064        let newest_selection = self.selections.newest_anchor().clone();
 5065        let cursor_position = newest_selection.head();
 5066        let (cursor_buffer, cursor_buffer_position) =
 5067            buffer.text_anchor_for_position(cursor_position, cx)?;
 5068        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5069        if cursor_buffer != tail_buffer {
 5070            return None;
 5071        }
 5072
 5073        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5074            cx.background_executor()
 5075                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5076                .await;
 5077
 5078            let highlights = if let Some(highlights) = cx
 5079                .update(|cx| {
 5080                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5081                })
 5082                .ok()
 5083                .flatten()
 5084            {
 5085                highlights.await.log_err()
 5086            } else {
 5087                None
 5088            };
 5089
 5090            if let Some(highlights) = highlights {
 5091                this.update(&mut cx, |this, cx| {
 5092                    if this.pending_rename.is_some() {
 5093                        return;
 5094                    }
 5095
 5096                    let buffer_id = cursor_position.buffer_id;
 5097                    let buffer = this.buffer.read(cx);
 5098                    if !buffer
 5099                        .text_anchor_for_position(cursor_position, cx)
 5100                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5101                    {
 5102                        return;
 5103                    }
 5104
 5105                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5106                    let mut write_ranges = Vec::new();
 5107                    let mut read_ranges = Vec::new();
 5108                    for highlight in highlights {
 5109                        for (excerpt_id, excerpt_range) in
 5110                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5111                        {
 5112                            let start = highlight
 5113                                .range
 5114                                .start
 5115                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5116                            let end = highlight
 5117                                .range
 5118                                .end
 5119                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5120                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5121                                continue;
 5122                            }
 5123
 5124                            let range = Anchor {
 5125                                buffer_id,
 5126                                excerpt_id,
 5127                                text_anchor: start,
 5128                            }..Anchor {
 5129                                buffer_id,
 5130                                excerpt_id,
 5131                                text_anchor: end,
 5132                            };
 5133                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5134                                write_ranges.push(range);
 5135                            } else {
 5136                                read_ranges.push(range);
 5137                            }
 5138                        }
 5139                    }
 5140
 5141                    this.highlight_background::<DocumentHighlightRead>(
 5142                        &read_ranges,
 5143                        |theme| theme.editor_document_highlight_read_background,
 5144                        cx,
 5145                    );
 5146                    this.highlight_background::<DocumentHighlightWrite>(
 5147                        &write_ranges,
 5148                        |theme| theme.editor_document_highlight_write_background,
 5149                        cx,
 5150                    );
 5151                    cx.notify();
 5152                })
 5153                .log_err();
 5154            }
 5155        }));
 5156        None
 5157    }
 5158
 5159    pub fn refresh_inline_completion(
 5160        &mut self,
 5161        debounce: bool,
 5162        user_requested: bool,
 5163        cx: &mut ViewContext<Self>,
 5164    ) -> Option<()> {
 5165        let provider = self.inline_completion_provider()?;
 5166        let cursor = self.selections.newest_anchor().head();
 5167        let (buffer, cursor_buffer_position) =
 5168            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5169
 5170        if !user_requested
 5171            && (!self.enable_inline_completions
 5172                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5173        {
 5174            self.discard_inline_completion(false, cx);
 5175            return None;
 5176        }
 5177
 5178        self.update_visible_inline_completion(cx);
 5179        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5180        Some(())
 5181    }
 5182
 5183    fn cycle_inline_completion(
 5184        &mut self,
 5185        direction: Direction,
 5186        cx: &mut ViewContext<Self>,
 5187    ) -> Option<()> {
 5188        let provider = self.inline_completion_provider()?;
 5189        let cursor = self.selections.newest_anchor().head();
 5190        let (buffer, cursor_buffer_position) =
 5191            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5192        if !self.enable_inline_completions
 5193            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5194        {
 5195            return None;
 5196        }
 5197
 5198        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5199        self.update_visible_inline_completion(cx);
 5200
 5201        Some(())
 5202    }
 5203
 5204    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5205        if !self.has_active_inline_completion(cx) {
 5206            self.refresh_inline_completion(false, true, cx);
 5207            return;
 5208        }
 5209
 5210        self.update_visible_inline_completion(cx);
 5211    }
 5212
 5213    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5214        self.show_cursor_names(cx);
 5215    }
 5216
 5217    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5218        self.show_cursor_names = true;
 5219        cx.notify();
 5220        cx.spawn(|this, mut cx| async move {
 5221            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5222            this.update(&mut cx, |this, cx| {
 5223                this.show_cursor_names = false;
 5224                cx.notify()
 5225            })
 5226            .ok()
 5227        })
 5228        .detach();
 5229    }
 5230
 5231    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5232        if self.has_active_inline_completion(cx) {
 5233            self.cycle_inline_completion(Direction::Next, cx);
 5234        } else {
 5235            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5236            if is_copilot_disabled {
 5237                cx.propagate();
 5238            }
 5239        }
 5240    }
 5241
 5242    pub fn previous_inline_completion(
 5243        &mut self,
 5244        _: &PreviousInlineCompletion,
 5245        cx: &mut ViewContext<Self>,
 5246    ) {
 5247        if self.has_active_inline_completion(cx) {
 5248            self.cycle_inline_completion(Direction::Prev, cx);
 5249        } else {
 5250            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5251            if is_copilot_disabled {
 5252                cx.propagate();
 5253            }
 5254        }
 5255    }
 5256
 5257    pub fn accept_inline_completion(
 5258        &mut self,
 5259        _: &AcceptInlineCompletion,
 5260        cx: &mut ViewContext<Self>,
 5261    ) {
 5262        let Some(completion) = self.take_active_inline_completion(cx) else {
 5263            return;
 5264        };
 5265        if let Some(provider) = self.inline_completion_provider() {
 5266            provider.accept(cx);
 5267        }
 5268
 5269        cx.emit(EditorEvent::InputHandled {
 5270            utf16_range_to_replace: None,
 5271            text: completion.text.to_string().into(),
 5272        });
 5273
 5274        if let Some(range) = completion.delete_range {
 5275            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5276        }
 5277        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5278        self.refresh_inline_completion(true, true, cx);
 5279        cx.notify();
 5280    }
 5281
 5282    pub fn accept_partial_inline_completion(
 5283        &mut self,
 5284        _: &AcceptPartialInlineCompletion,
 5285        cx: &mut ViewContext<Self>,
 5286    ) {
 5287        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5288            if let Some(completion) = self.take_active_inline_completion(cx) {
 5289                let mut partial_completion = completion
 5290                    .text
 5291                    .chars()
 5292                    .by_ref()
 5293                    .take_while(|c| c.is_alphabetic())
 5294                    .collect::<String>();
 5295                if partial_completion.is_empty() {
 5296                    partial_completion = completion
 5297                        .text
 5298                        .chars()
 5299                        .by_ref()
 5300                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5301                        .collect::<String>();
 5302                }
 5303
 5304                cx.emit(EditorEvent::InputHandled {
 5305                    utf16_range_to_replace: None,
 5306                    text: partial_completion.clone().into(),
 5307                });
 5308
 5309                if let Some(range) = completion.delete_range {
 5310                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5311                }
 5312                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5313
 5314                self.refresh_inline_completion(true, true, cx);
 5315                cx.notify();
 5316            }
 5317        }
 5318    }
 5319
 5320    fn discard_inline_completion(
 5321        &mut self,
 5322        should_report_inline_completion_event: bool,
 5323        cx: &mut ViewContext<Self>,
 5324    ) -> bool {
 5325        if let Some(provider) = self.inline_completion_provider() {
 5326            provider.discard(should_report_inline_completion_event, cx);
 5327        }
 5328
 5329        self.take_active_inline_completion(cx).is_some()
 5330    }
 5331
 5332    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5333        if let Some(completion) = self.active_inline_completion.as_ref() {
 5334            let buffer = self.buffer.read(cx).read(cx);
 5335            completion.position.is_valid(&buffer)
 5336        } else {
 5337            false
 5338        }
 5339    }
 5340
 5341    fn take_active_inline_completion(
 5342        &mut self,
 5343        cx: &mut ViewContext<Self>,
 5344    ) -> Option<CompletionState> {
 5345        let completion = self.active_inline_completion.take()?;
 5346        let render_inlay_ids = completion.render_inlay_ids.clone();
 5347        self.display_map.update(cx, |map, cx| {
 5348            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5349        });
 5350        let buffer = self.buffer.read(cx).read(cx);
 5351
 5352        if completion.position.is_valid(&buffer) {
 5353            Some(completion)
 5354        } else {
 5355            None
 5356        }
 5357    }
 5358
 5359    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5360        let selection = self.selections.newest_anchor();
 5361        let cursor = selection.head();
 5362
 5363        let excerpt_id = cursor.excerpt_id;
 5364
 5365        if self.context_menu.read().is_none()
 5366            && self.completion_tasks.is_empty()
 5367            && selection.start == selection.end
 5368        {
 5369            if let Some(provider) = self.inline_completion_provider() {
 5370                if let Some((buffer, cursor_buffer_position)) =
 5371                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5372                {
 5373                    if let Some(proposal) =
 5374                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5375                    {
 5376                        let mut to_remove = Vec::new();
 5377                        if let Some(completion) = self.active_inline_completion.take() {
 5378                            to_remove.extend(completion.render_inlay_ids.iter());
 5379                        }
 5380
 5381                        let to_add = proposal
 5382                            .inlays
 5383                            .iter()
 5384                            .filter_map(|inlay| {
 5385                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5386                                let id = post_inc(&mut self.next_inlay_id);
 5387                                match inlay {
 5388                                    InlayProposal::Hint(position, hint) => {
 5389                                        let position =
 5390                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5391                                        Some(Inlay::hint(id, position, hint))
 5392                                    }
 5393                                    InlayProposal::Suggestion(position, text) => {
 5394                                        let position =
 5395                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5396                                        Some(Inlay::suggestion(id, position, text.clone()))
 5397                                    }
 5398                                }
 5399                            })
 5400                            .collect_vec();
 5401
 5402                        self.active_inline_completion = Some(CompletionState {
 5403                            position: cursor,
 5404                            text: proposal.text,
 5405                            delete_range: proposal.delete_range.and_then(|range| {
 5406                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5407                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5408                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5409                                Some(start?..end?)
 5410                            }),
 5411                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5412                        });
 5413
 5414                        self.display_map
 5415                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5416
 5417                        cx.notify();
 5418                        return;
 5419                    }
 5420                }
 5421            }
 5422        }
 5423
 5424        self.discard_inline_completion(false, cx);
 5425    }
 5426
 5427    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5428        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5429    }
 5430
 5431    fn render_code_actions_indicator(
 5432        &self,
 5433        _style: &EditorStyle,
 5434        row: DisplayRow,
 5435        is_active: bool,
 5436        cx: &mut ViewContext<Self>,
 5437    ) -> Option<IconButton> {
 5438        if self.available_code_actions.is_some() {
 5439            Some(
 5440                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5441                    .shape(ui::IconButtonShape::Square)
 5442                    .icon_size(IconSize::XSmall)
 5443                    .icon_color(Color::Muted)
 5444                    .selected(is_active)
 5445                    .tooltip({
 5446                        let focus_handle = self.focus_handle.clone();
 5447                        move |cx| {
 5448                            Tooltip::for_action_in(
 5449                                "Toggle Code Actions",
 5450                                &ToggleCodeActions {
 5451                                    deployed_from_indicator: None,
 5452                                },
 5453                                &focus_handle,
 5454                                cx,
 5455                            )
 5456                        }
 5457                    })
 5458                    .on_click(cx.listener(move |editor, _e, cx| {
 5459                        editor.focus(cx);
 5460                        editor.toggle_code_actions(
 5461                            &ToggleCodeActions {
 5462                                deployed_from_indicator: Some(row),
 5463                            },
 5464                            cx,
 5465                        );
 5466                    })),
 5467            )
 5468        } else {
 5469            None
 5470        }
 5471    }
 5472
 5473    fn clear_tasks(&mut self) {
 5474        self.tasks.clear()
 5475    }
 5476
 5477    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5478        if self.tasks.insert(key, value).is_some() {
 5479            // This case should hopefully be rare, but just in case...
 5480            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5481        }
 5482    }
 5483
 5484    fn render_run_indicator(
 5485        &self,
 5486        _style: &EditorStyle,
 5487        is_active: bool,
 5488        row: DisplayRow,
 5489        cx: &mut ViewContext<Self>,
 5490    ) -> IconButton {
 5491        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5492            .shape(ui::IconButtonShape::Square)
 5493            .icon_size(IconSize::XSmall)
 5494            .icon_color(Color::Muted)
 5495            .selected(is_active)
 5496            .on_click(cx.listener(move |editor, _e, cx| {
 5497                editor.focus(cx);
 5498                editor.toggle_code_actions(
 5499                    &ToggleCodeActions {
 5500                        deployed_from_indicator: Some(row),
 5501                    },
 5502                    cx,
 5503                );
 5504            }))
 5505    }
 5506
 5507    pub fn context_menu_visible(&self) -> bool {
 5508        self.context_menu
 5509            .read()
 5510            .as_ref()
 5511            .map_or(false, |menu| menu.visible())
 5512    }
 5513
 5514    fn render_context_menu(
 5515        &self,
 5516        cursor_position: DisplayPoint,
 5517        style: &EditorStyle,
 5518        max_height: Pixels,
 5519        cx: &mut ViewContext<Editor>,
 5520    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5521        self.context_menu.read().as_ref().map(|menu| {
 5522            menu.render(
 5523                cursor_position,
 5524                style,
 5525                max_height,
 5526                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5527                cx,
 5528            )
 5529        })
 5530    }
 5531
 5532    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5533        cx.notify();
 5534        self.completion_tasks.clear();
 5535        let context_menu = self.context_menu.write().take();
 5536        if context_menu.is_some() {
 5537            self.update_visible_inline_completion(cx);
 5538        }
 5539        context_menu
 5540    }
 5541
 5542    pub fn insert_snippet(
 5543        &mut self,
 5544        insertion_ranges: &[Range<usize>],
 5545        snippet: Snippet,
 5546        cx: &mut ViewContext<Self>,
 5547    ) -> Result<()> {
 5548        struct Tabstop<T> {
 5549            is_end_tabstop: bool,
 5550            ranges: Vec<Range<T>>,
 5551        }
 5552
 5553        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5554            let snippet_text: Arc<str> = snippet.text.clone().into();
 5555            buffer.edit(
 5556                insertion_ranges
 5557                    .iter()
 5558                    .cloned()
 5559                    .map(|range| (range, snippet_text.clone())),
 5560                Some(AutoindentMode::EachLine),
 5561                cx,
 5562            );
 5563
 5564            let snapshot = &*buffer.read(cx);
 5565            let snippet = &snippet;
 5566            snippet
 5567                .tabstops
 5568                .iter()
 5569                .map(|tabstop| {
 5570                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5571                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5572                    });
 5573                    let mut tabstop_ranges = tabstop
 5574                        .iter()
 5575                        .flat_map(|tabstop_range| {
 5576                            let mut delta = 0_isize;
 5577                            insertion_ranges.iter().map(move |insertion_range| {
 5578                                let insertion_start = insertion_range.start as isize + delta;
 5579                                delta +=
 5580                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5581
 5582                                let start = ((insertion_start + tabstop_range.start) as usize)
 5583                                    .min(snapshot.len());
 5584                                let end = ((insertion_start + tabstop_range.end) as usize)
 5585                                    .min(snapshot.len());
 5586                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5587                            })
 5588                        })
 5589                        .collect::<Vec<_>>();
 5590                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5591
 5592                    Tabstop {
 5593                        is_end_tabstop,
 5594                        ranges: tabstop_ranges,
 5595                    }
 5596                })
 5597                .collect::<Vec<_>>()
 5598        });
 5599        if let Some(tabstop) = tabstops.first() {
 5600            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5601                s.select_ranges(tabstop.ranges.iter().cloned());
 5602            });
 5603
 5604            // If we're already at the last tabstop and it's at the end of the snippet,
 5605            // we're done, we don't need to keep the state around.
 5606            if !tabstop.is_end_tabstop {
 5607                let ranges = tabstops
 5608                    .into_iter()
 5609                    .map(|tabstop| tabstop.ranges)
 5610                    .collect::<Vec<_>>();
 5611                self.snippet_stack.push(SnippetState {
 5612                    active_index: 0,
 5613                    ranges,
 5614                });
 5615            }
 5616
 5617            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5618            if self.autoclose_regions.is_empty() {
 5619                let snapshot = self.buffer.read(cx).snapshot(cx);
 5620                for selection in &mut self.selections.all::<Point>(cx) {
 5621                    let selection_head = selection.head();
 5622                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5623                        continue;
 5624                    };
 5625
 5626                    let mut bracket_pair = None;
 5627                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5628                    let prev_chars = snapshot
 5629                        .reversed_chars_at(selection_head)
 5630                        .collect::<String>();
 5631                    for (pair, enabled) in scope.brackets() {
 5632                        if enabled
 5633                            && pair.close
 5634                            && prev_chars.starts_with(pair.start.as_str())
 5635                            && next_chars.starts_with(pair.end.as_str())
 5636                        {
 5637                            bracket_pair = Some(pair.clone());
 5638                            break;
 5639                        }
 5640                    }
 5641                    if let Some(pair) = bracket_pair {
 5642                        let start = snapshot.anchor_after(selection_head);
 5643                        let end = snapshot.anchor_after(selection_head);
 5644                        self.autoclose_regions.push(AutocloseRegion {
 5645                            selection_id: selection.id,
 5646                            range: start..end,
 5647                            pair,
 5648                        });
 5649                    }
 5650                }
 5651            }
 5652        }
 5653        Ok(())
 5654    }
 5655
 5656    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5657        self.move_to_snippet_tabstop(Bias::Right, cx)
 5658    }
 5659
 5660    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5661        self.move_to_snippet_tabstop(Bias::Left, cx)
 5662    }
 5663
 5664    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5665        if let Some(mut snippet) = self.snippet_stack.pop() {
 5666            match bias {
 5667                Bias::Left => {
 5668                    if snippet.active_index > 0 {
 5669                        snippet.active_index -= 1;
 5670                    } else {
 5671                        self.snippet_stack.push(snippet);
 5672                        return false;
 5673                    }
 5674                }
 5675                Bias::Right => {
 5676                    if snippet.active_index + 1 < snippet.ranges.len() {
 5677                        snippet.active_index += 1;
 5678                    } else {
 5679                        self.snippet_stack.push(snippet);
 5680                        return false;
 5681                    }
 5682                }
 5683            }
 5684            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5685                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5686                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5687                });
 5688                // If snippet state is not at the last tabstop, push it back on the stack
 5689                if snippet.active_index + 1 < snippet.ranges.len() {
 5690                    self.snippet_stack.push(snippet);
 5691                }
 5692                return true;
 5693            }
 5694        }
 5695
 5696        false
 5697    }
 5698
 5699    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5700        self.transact(cx, |this, cx| {
 5701            this.select_all(&SelectAll, cx);
 5702            this.insert("", cx);
 5703        });
 5704    }
 5705
 5706    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5707        self.transact(cx, |this, cx| {
 5708            this.select_autoclose_pair(cx);
 5709            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5710            if !this.linked_edit_ranges.is_empty() {
 5711                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5712                let snapshot = this.buffer.read(cx).snapshot(cx);
 5713
 5714                for selection in selections.iter() {
 5715                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5716                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5717                    if selection_start.buffer_id != selection_end.buffer_id {
 5718                        continue;
 5719                    }
 5720                    if let Some(ranges) =
 5721                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5722                    {
 5723                        for (buffer, entries) in ranges {
 5724                            linked_ranges.entry(buffer).or_default().extend(entries);
 5725                        }
 5726                    }
 5727                }
 5728            }
 5729
 5730            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5731            if !this.selections.line_mode {
 5732                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5733                for selection in &mut selections {
 5734                    if selection.is_empty() {
 5735                        let old_head = selection.head();
 5736                        let mut new_head =
 5737                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5738                                .to_point(&display_map);
 5739                        if let Some((buffer, line_buffer_range)) = display_map
 5740                            .buffer_snapshot
 5741                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5742                        {
 5743                            let indent_size =
 5744                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5745                            let indent_len = match indent_size.kind {
 5746                                IndentKind::Space => {
 5747                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5748                                }
 5749                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5750                            };
 5751                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5752                                let indent_len = indent_len.get();
 5753                                new_head = cmp::min(
 5754                                    new_head,
 5755                                    MultiBufferPoint::new(
 5756                                        old_head.row,
 5757                                        ((old_head.column - 1) / indent_len) * indent_len,
 5758                                    ),
 5759                                );
 5760                            }
 5761                        }
 5762
 5763                        selection.set_head(new_head, SelectionGoal::None);
 5764                    }
 5765                }
 5766            }
 5767
 5768            this.signature_help_state.set_backspace_pressed(true);
 5769            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5770            this.insert("", cx);
 5771            let empty_str: Arc<str> = Arc::from("");
 5772            for (buffer, edits) in linked_ranges {
 5773                let snapshot = buffer.read(cx).snapshot();
 5774                use text::ToPoint as TP;
 5775
 5776                let edits = edits
 5777                    .into_iter()
 5778                    .map(|range| {
 5779                        let end_point = TP::to_point(&range.end, &snapshot);
 5780                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5781
 5782                        if end_point == start_point {
 5783                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5784                                .saturating_sub(1);
 5785                            start_point = TP::to_point(&offset, &snapshot);
 5786                        };
 5787
 5788                        (start_point..end_point, empty_str.clone())
 5789                    })
 5790                    .sorted_by_key(|(range, _)| range.start)
 5791                    .collect::<Vec<_>>();
 5792                buffer.update(cx, |this, cx| {
 5793                    this.edit(edits, None, cx);
 5794                })
 5795            }
 5796            this.refresh_inline_completion(true, false, cx);
 5797            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5798        });
 5799    }
 5800
 5801    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5802        self.transact(cx, |this, cx| {
 5803            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5804                let line_mode = s.line_mode;
 5805                s.move_with(|map, selection| {
 5806                    if selection.is_empty() && !line_mode {
 5807                        let cursor = movement::right(map, selection.head());
 5808                        selection.end = cursor;
 5809                        selection.reversed = true;
 5810                        selection.goal = SelectionGoal::None;
 5811                    }
 5812                })
 5813            });
 5814            this.insert("", cx);
 5815            this.refresh_inline_completion(true, false, cx);
 5816        });
 5817    }
 5818
 5819    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5820        if self.move_to_prev_snippet_tabstop(cx) {
 5821            return;
 5822        }
 5823
 5824        self.outdent(&Outdent, cx);
 5825    }
 5826
 5827    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5828        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5829            return;
 5830        }
 5831
 5832        let mut selections = self.selections.all_adjusted(cx);
 5833        let buffer = self.buffer.read(cx);
 5834        let snapshot = buffer.snapshot(cx);
 5835        let rows_iter = selections.iter().map(|s| s.head().row);
 5836        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5837
 5838        let mut edits = Vec::new();
 5839        let mut prev_edited_row = 0;
 5840        let mut row_delta = 0;
 5841        for selection in &mut selections {
 5842            if selection.start.row != prev_edited_row {
 5843                row_delta = 0;
 5844            }
 5845            prev_edited_row = selection.end.row;
 5846
 5847            // If the selection is non-empty, then increase the indentation of the selected lines.
 5848            if !selection.is_empty() {
 5849                row_delta =
 5850                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5851                continue;
 5852            }
 5853
 5854            // If the selection is empty and the cursor is in the leading whitespace before the
 5855            // suggested indentation, then auto-indent the line.
 5856            let cursor = selection.head();
 5857            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5858            if let Some(suggested_indent) =
 5859                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5860            {
 5861                if cursor.column < suggested_indent.len
 5862                    && cursor.column <= current_indent.len
 5863                    && current_indent.len <= suggested_indent.len
 5864                {
 5865                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5866                    selection.end = selection.start;
 5867                    if row_delta == 0 {
 5868                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5869                            cursor.row,
 5870                            current_indent,
 5871                            suggested_indent,
 5872                        ));
 5873                        row_delta = suggested_indent.len - current_indent.len;
 5874                    }
 5875                    continue;
 5876                }
 5877            }
 5878
 5879            // Otherwise, insert a hard or soft tab.
 5880            let settings = buffer.settings_at(cursor, cx);
 5881            let tab_size = if settings.hard_tabs {
 5882                IndentSize::tab()
 5883            } else {
 5884                let tab_size = settings.tab_size.get();
 5885                let char_column = snapshot
 5886                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5887                    .flat_map(str::chars)
 5888                    .count()
 5889                    + row_delta as usize;
 5890                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5891                IndentSize::spaces(chars_to_next_tab_stop)
 5892            };
 5893            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5894            selection.end = selection.start;
 5895            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5896            row_delta += tab_size.len;
 5897        }
 5898
 5899        self.transact(cx, |this, cx| {
 5900            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5901            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5902            this.refresh_inline_completion(true, false, cx);
 5903        });
 5904    }
 5905
 5906    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5907        if self.read_only(cx) {
 5908            return;
 5909        }
 5910        let mut selections = self.selections.all::<Point>(cx);
 5911        let mut prev_edited_row = 0;
 5912        let mut row_delta = 0;
 5913        let mut edits = Vec::new();
 5914        let buffer = self.buffer.read(cx);
 5915        let snapshot = buffer.snapshot(cx);
 5916        for selection in &mut selections {
 5917            if selection.start.row != prev_edited_row {
 5918                row_delta = 0;
 5919            }
 5920            prev_edited_row = selection.end.row;
 5921
 5922            row_delta =
 5923                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5924        }
 5925
 5926        self.transact(cx, |this, cx| {
 5927            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5928            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5929        });
 5930    }
 5931
 5932    fn indent_selection(
 5933        buffer: &MultiBuffer,
 5934        snapshot: &MultiBufferSnapshot,
 5935        selection: &mut Selection<Point>,
 5936        edits: &mut Vec<(Range<Point>, String)>,
 5937        delta_for_start_row: u32,
 5938        cx: &AppContext,
 5939    ) -> u32 {
 5940        let settings = buffer.settings_at(selection.start, cx);
 5941        let tab_size = settings.tab_size.get();
 5942        let indent_kind = if settings.hard_tabs {
 5943            IndentKind::Tab
 5944        } else {
 5945            IndentKind::Space
 5946        };
 5947        let mut start_row = selection.start.row;
 5948        let mut end_row = selection.end.row + 1;
 5949
 5950        // If a selection ends at the beginning of a line, don't indent
 5951        // that last line.
 5952        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5953            end_row -= 1;
 5954        }
 5955
 5956        // Avoid re-indenting a row that has already been indented by a
 5957        // previous selection, but still update this selection's column
 5958        // to reflect that indentation.
 5959        if delta_for_start_row > 0 {
 5960            start_row += 1;
 5961            selection.start.column += delta_for_start_row;
 5962            if selection.end.row == selection.start.row {
 5963                selection.end.column += delta_for_start_row;
 5964            }
 5965        }
 5966
 5967        let mut delta_for_end_row = 0;
 5968        let has_multiple_rows = start_row + 1 != end_row;
 5969        for row in start_row..end_row {
 5970            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5971            let indent_delta = match (current_indent.kind, indent_kind) {
 5972                (IndentKind::Space, IndentKind::Space) => {
 5973                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5974                    IndentSize::spaces(columns_to_next_tab_stop)
 5975                }
 5976                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5977                (_, IndentKind::Tab) => IndentSize::tab(),
 5978            };
 5979
 5980            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5981                0
 5982            } else {
 5983                selection.start.column
 5984            };
 5985            let row_start = Point::new(row, start);
 5986            edits.push((
 5987                row_start..row_start,
 5988                indent_delta.chars().collect::<String>(),
 5989            ));
 5990
 5991            // Update this selection's endpoints to reflect the indentation.
 5992            if row == selection.start.row {
 5993                selection.start.column += indent_delta.len;
 5994            }
 5995            if row == selection.end.row {
 5996                selection.end.column += indent_delta.len;
 5997                delta_for_end_row = indent_delta.len;
 5998            }
 5999        }
 6000
 6001        if selection.start.row == selection.end.row {
 6002            delta_for_start_row + delta_for_end_row
 6003        } else {
 6004            delta_for_end_row
 6005        }
 6006    }
 6007
 6008    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6009        if self.read_only(cx) {
 6010            return;
 6011        }
 6012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6013        let selections = self.selections.all::<Point>(cx);
 6014        let mut deletion_ranges = Vec::new();
 6015        let mut last_outdent = None;
 6016        {
 6017            let buffer = self.buffer.read(cx);
 6018            let snapshot = buffer.snapshot(cx);
 6019            for selection in &selections {
 6020                let settings = buffer.settings_at(selection.start, cx);
 6021                let tab_size = settings.tab_size.get();
 6022                let mut rows = selection.spanned_rows(false, &display_map);
 6023
 6024                // Avoid re-outdenting a row that has already been outdented by a
 6025                // previous selection.
 6026                if let Some(last_row) = last_outdent {
 6027                    if last_row == rows.start {
 6028                        rows.start = rows.start.next_row();
 6029                    }
 6030                }
 6031                let has_multiple_rows = rows.len() > 1;
 6032                for row in rows.iter_rows() {
 6033                    let indent_size = snapshot.indent_size_for_line(row);
 6034                    if indent_size.len > 0 {
 6035                        let deletion_len = match indent_size.kind {
 6036                            IndentKind::Space => {
 6037                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6038                                if columns_to_prev_tab_stop == 0 {
 6039                                    tab_size
 6040                                } else {
 6041                                    columns_to_prev_tab_stop
 6042                                }
 6043                            }
 6044                            IndentKind::Tab => 1,
 6045                        };
 6046                        let start = if has_multiple_rows
 6047                            || deletion_len > selection.start.column
 6048                            || indent_size.len < selection.start.column
 6049                        {
 6050                            0
 6051                        } else {
 6052                            selection.start.column - deletion_len
 6053                        };
 6054                        deletion_ranges.push(
 6055                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6056                        );
 6057                        last_outdent = Some(row);
 6058                    }
 6059                }
 6060            }
 6061        }
 6062
 6063        self.transact(cx, |this, cx| {
 6064            this.buffer.update(cx, |buffer, cx| {
 6065                let empty_str: Arc<str> = Arc::default();
 6066                buffer.edit(
 6067                    deletion_ranges
 6068                        .into_iter()
 6069                        .map(|range| (range, empty_str.clone())),
 6070                    None,
 6071                    cx,
 6072                );
 6073            });
 6074            let selections = this.selections.all::<usize>(cx);
 6075            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6076        });
 6077    }
 6078
 6079    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6080        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6081        let selections = self.selections.all::<Point>(cx);
 6082
 6083        let mut new_cursors = Vec::new();
 6084        let mut edit_ranges = Vec::new();
 6085        let mut selections = selections.iter().peekable();
 6086        while let Some(selection) = selections.next() {
 6087            let mut rows = selection.spanned_rows(false, &display_map);
 6088            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6089
 6090            // Accumulate contiguous regions of rows that we want to delete.
 6091            while let Some(next_selection) = selections.peek() {
 6092                let next_rows = next_selection.spanned_rows(false, &display_map);
 6093                if next_rows.start <= rows.end {
 6094                    rows.end = next_rows.end;
 6095                    selections.next().unwrap();
 6096                } else {
 6097                    break;
 6098                }
 6099            }
 6100
 6101            let buffer = &display_map.buffer_snapshot;
 6102            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6103            let edit_end;
 6104            let cursor_buffer_row;
 6105            if buffer.max_point().row >= rows.end.0 {
 6106                // If there's a line after the range, delete the \n from the end of the row range
 6107                // and position the cursor on the next line.
 6108                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6109                cursor_buffer_row = rows.end;
 6110            } else {
 6111                // If there isn't a line after the range, delete the \n from the line before the
 6112                // start of the row range and position the cursor there.
 6113                edit_start = edit_start.saturating_sub(1);
 6114                edit_end = buffer.len();
 6115                cursor_buffer_row = rows.start.previous_row();
 6116            }
 6117
 6118            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6119            *cursor.column_mut() =
 6120                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6121
 6122            new_cursors.push((
 6123                selection.id,
 6124                buffer.anchor_after(cursor.to_point(&display_map)),
 6125            ));
 6126            edit_ranges.push(edit_start..edit_end);
 6127        }
 6128
 6129        self.transact(cx, |this, cx| {
 6130            let buffer = this.buffer.update(cx, |buffer, cx| {
 6131                let empty_str: Arc<str> = Arc::default();
 6132                buffer.edit(
 6133                    edit_ranges
 6134                        .into_iter()
 6135                        .map(|range| (range, empty_str.clone())),
 6136                    None,
 6137                    cx,
 6138                );
 6139                buffer.snapshot(cx)
 6140            });
 6141            let new_selections = new_cursors
 6142                .into_iter()
 6143                .map(|(id, cursor)| {
 6144                    let cursor = cursor.to_point(&buffer);
 6145                    Selection {
 6146                        id,
 6147                        start: cursor,
 6148                        end: cursor,
 6149                        reversed: false,
 6150                        goal: SelectionGoal::None,
 6151                    }
 6152                })
 6153                .collect();
 6154
 6155            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6156                s.select(new_selections);
 6157            });
 6158        });
 6159    }
 6160
 6161    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6162        if self.read_only(cx) {
 6163            return;
 6164        }
 6165        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6166        for selection in self.selections.all::<Point>(cx) {
 6167            let start = MultiBufferRow(selection.start.row);
 6168            let end = if selection.start.row == selection.end.row {
 6169                MultiBufferRow(selection.start.row + 1)
 6170            } else {
 6171                MultiBufferRow(selection.end.row)
 6172            };
 6173
 6174            if let Some(last_row_range) = row_ranges.last_mut() {
 6175                if start <= last_row_range.end {
 6176                    last_row_range.end = end;
 6177                    continue;
 6178                }
 6179            }
 6180            row_ranges.push(start..end);
 6181        }
 6182
 6183        let snapshot = self.buffer.read(cx).snapshot(cx);
 6184        let mut cursor_positions = Vec::new();
 6185        for row_range in &row_ranges {
 6186            let anchor = snapshot.anchor_before(Point::new(
 6187                row_range.end.previous_row().0,
 6188                snapshot.line_len(row_range.end.previous_row()),
 6189            ));
 6190            cursor_positions.push(anchor..anchor);
 6191        }
 6192
 6193        self.transact(cx, |this, cx| {
 6194            for row_range in row_ranges.into_iter().rev() {
 6195                for row in row_range.iter_rows().rev() {
 6196                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6197                    let next_line_row = row.next_row();
 6198                    let indent = snapshot.indent_size_for_line(next_line_row);
 6199                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6200
 6201                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6202                        " "
 6203                    } else {
 6204                        ""
 6205                    };
 6206
 6207                    this.buffer.update(cx, |buffer, cx| {
 6208                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6209                    });
 6210                }
 6211            }
 6212
 6213            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6214                s.select_anchor_ranges(cursor_positions)
 6215            });
 6216        });
 6217    }
 6218
 6219    pub fn sort_lines_case_sensitive(
 6220        &mut self,
 6221        _: &SortLinesCaseSensitive,
 6222        cx: &mut ViewContext<Self>,
 6223    ) {
 6224        self.manipulate_lines(cx, |lines| lines.sort())
 6225    }
 6226
 6227    pub fn sort_lines_case_insensitive(
 6228        &mut self,
 6229        _: &SortLinesCaseInsensitive,
 6230        cx: &mut ViewContext<Self>,
 6231    ) {
 6232        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6233    }
 6234
 6235    pub fn unique_lines_case_insensitive(
 6236        &mut self,
 6237        _: &UniqueLinesCaseInsensitive,
 6238        cx: &mut ViewContext<Self>,
 6239    ) {
 6240        self.manipulate_lines(cx, |lines| {
 6241            let mut seen = HashSet::default();
 6242            lines.retain(|line| seen.insert(line.to_lowercase()));
 6243        })
 6244    }
 6245
 6246    pub fn unique_lines_case_sensitive(
 6247        &mut self,
 6248        _: &UniqueLinesCaseSensitive,
 6249        cx: &mut ViewContext<Self>,
 6250    ) {
 6251        self.manipulate_lines(cx, |lines| {
 6252            let mut seen = HashSet::default();
 6253            lines.retain(|line| seen.insert(*line));
 6254        })
 6255    }
 6256
 6257    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6258        let mut revert_changes = HashMap::default();
 6259        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6260        for hunk in hunks_for_rows(
 6261            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6262            &multi_buffer_snapshot,
 6263        ) {
 6264            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6265        }
 6266        if !revert_changes.is_empty() {
 6267            self.transact(cx, |editor, cx| {
 6268                editor.revert(revert_changes, cx);
 6269            });
 6270        }
 6271    }
 6272
 6273    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6274        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6275        if !revert_changes.is_empty() {
 6276            self.transact(cx, |editor, cx| {
 6277                editor.revert(revert_changes, cx);
 6278            });
 6279        }
 6280    }
 6281
 6282    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6283        let snapshot = self.buffer.read(cx).snapshot(cx);
 6284        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6285        let mut ranges_by_buffer = HashMap::default();
 6286        self.transact(cx, |editor, cx| {
 6287            for hunk in hunks {
 6288                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6289                    ranges_by_buffer
 6290                        .entry(buffer.clone())
 6291                        .or_insert_with(Vec::new)
 6292                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 6293                }
 6294            }
 6295
 6296            for (buffer, ranges) in ranges_by_buffer {
 6297                buffer.update(cx, |buffer, cx| {
 6298                    buffer.merge_into_base(ranges, cx);
 6299                });
 6300            }
 6301        });
 6302    }
 6303
 6304    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6305        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6306            let project_path = buffer.read(cx).project_path(cx)?;
 6307            let project = self.project.as_ref()?.read(cx);
 6308            let entry = project.entry_for_path(&project_path, cx)?;
 6309            let abs_path = project.absolute_path(&project_path, cx)?;
 6310            let parent = if entry.is_symlink {
 6311                abs_path.canonicalize().ok()?
 6312            } else {
 6313                abs_path
 6314            }
 6315            .parent()?
 6316            .to_path_buf();
 6317            Some(parent)
 6318        }) {
 6319            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6320        }
 6321    }
 6322
 6323    fn gather_revert_changes(
 6324        &mut self,
 6325        selections: &[Selection<Anchor>],
 6326        cx: &mut ViewContext<'_, Editor>,
 6327    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6328        let mut revert_changes = HashMap::default();
 6329        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6330        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6331            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6332        }
 6333        revert_changes
 6334    }
 6335
 6336    pub fn prepare_revert_change(
 6337        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6338        multi_buffer: &Model<MultiBuffer>,
 6339        hunk: &MultiBufferDiffHunk,
 6340        cx: &AppContext,
 6341    ) -> Option<()> {
 6342        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6343        let buffer = buffer.read(cx);
 6344        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6345        let buffer_snapshot = buffer.snapshot();
 6346        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6347        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6348            probe
 6349                .0
 6350                .start
 6351                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6352                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6353        }) {
 6354            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6355            Some(())
 6356        } else {
 6357            None
 6358        }
 6359    }
 6360
 6361    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6362        self.manipulate_lines(cx, |lines| lines.reverse())
 6363    }
 6364
 6365    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6366        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6367    }
 6368
 6369    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6370    where
 6371        Fn: FnMut(&mut Vec<&str>),
 6372    {
 6373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6374        let buffer = self.buffer.read(cx).snapshot(cx);
 6375
 6376        let mut edits = Vec::new();
 6377
 6378        let selections = self.selections.all::<Point>(cx);
 6379        let mut selections = selections.iter().peekable();
 6380        let mut contiguous_row_selections = Vec::new();
 6381        let mut new_selections = Vec::new();
 6382        let mut added_lines = 0;
 6383        let mut removed_lines = 0;
 6384
 6385        while let Some(selection) = selections.next() {
 6386            let (start_row, end_row) = consume_contiguous_rows(
 6387                &mut contiguous_row_selections,
 6388                selection,
 6389                &display_map,
 6390                &mut selections,
 6391            );
 6392
 6393            let start_point = Point::new(start_row.0, 0);
 6394            let end_point = Point::new(
 6395                end_row.previous_row().0,
 6396                buffer.line_len(end_row.previous_row()),
 6397            );
 6398            let text = buffer
 6399                .text_for_range(start_point..end_point)
 6400                .collect::<String>();
 6401
 6402            let mut lines = text.split('\n').collect_vec();
 6403
 6404            let lines_before = lines.len();
 6405            callback(&mut lines);
 6406            let lines_after = lines.len();
 6407
 6408            edits.push((start_point..end_point, lines.join("\n")));
 6409
 6410            // Selections must change based on added and removed line count
 6411            let start_row =
 6412                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6413            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6414            new_selections.push(Selection {
 6415                id: selection.id,
 6416                start: start_row,
 6417                end: end_row,
 6418                goal: SelectionGoal::None,
 6419                reversed: selection.reversed,
 6420            });
 6421
 6422            if lines_after > lines_before {
 6423                added_lines += lines_after - lines_before;
 6424            } else if lines_before > lines_after {
 6425                removed_lines += lines_before - lines_after;
 6426            }
 6427        }
 6428
 6429        self.transact(cx, |this, cx| {
 6430            let buffer = this.buffer.update(cx, |buffer, cx| {
 6431                buffer.edit(edits, None, cx);
 6432                buffer.snapshot(cx)
 6433            });
 6434
 6435            // Recalculate offsets on newly edited buffer
 6436            let new_selections = new_selections
 6437                .iter()
 6438                .map(|s| {
 6439                    let start_point = Point::new(s.start.0, 0);
 6440                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6441                    Selection {
 6442                        id: s.id,
 6443                        start: buffer.point_to_offset(start_point),
 6444                        end: buffer.point_to_offset(end_point),
 6445                        goal: s.goal,
 6446                        reversed: s.reversed,
 6447                    }
 6448                })
 6449                .collect();
 6450
 6451            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6452                s.select(new_selections);
 6453            });
 6454
 6455            this.request_autoscroll(Autoscroll::fit(), cx);
 6456        });
 6457    }
 6458
 6459    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6460        self.manipulate_text(cx, |text| text.to_uppercase())
 6461    }
 6462
 6463    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6464        self.manipulate_text(cx, |text| text.to_lowercase())
 6465    }
 6466
 6467    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6468        self.manipulate_text(cx, |text| {
 6469            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6470            // https://github.com/rutrum/convert-case/issues/16
 6471            text.split('\n')
 6472                .map(|line| line.to_case(Case::Title))
 6473                .join("\n")
 6474        })
 6475    }
 6476
 6477    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6478        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6479    }
 6480
 6481    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6482        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6483    }
 6484
 6485    pub fn convert_to_upper_camel_case(
 6486        &mut self,
 6487        _: &ConvertToUpperCamelCase,
 6488        cx: &mut ViewContext<Self>,
 6489    ) {
 6490        self.manipulate_text(cx, |text| {
 6491            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6492            // https://github.com/rutrum/convert-case/issues/16
 6493            text.split('\n')
 6494                .map(|line| line.to_case(Case::UpperCamel))
 6495                .join("\n")
 6496        })
 6497    }
 6498
 6499    pub fn convert_to_lower_camel_case(
 6500        &mut self,
 6501        _: &ConvertToLowerCamelCase,
 6502        cx: &mut ViewContext<Self>,
 6503    ) {
 6504        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6505    }
 6506
 6507    pub fn convert_to_opposite_case(
 6508        &mut self,
 6509        _: &ConvertToOppositeCase,
 6510        cx: &mut ViewContext<Self>,
 6511    ) {
 6512        self.manipulate_text(cx, |text| {
 6513            text.chars()
 6514                .fold(String::with_capacity(text.len()), |mut t, c| {
 6515                    if c.is_uppercase() {
 6516                        t.extend(c.to_lowercase());
 6517                    } else {
 6518                        t.extend(c.to_uppercase());
 6519                    }
 6520                    t
 6521                })
 6522        })
 6523    }
 6524
 6525    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6526    where
 6527        Fn: FnMut(&str) -> String,
 6528    {
 6529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6530        let buffer = self.buffer.read(cx).snapshot(cx);
 6531
 6532        let mut new_selections = Vec::new();
 6533        let mut edits = Vec::new();
 6534        let mut selection_adjustment = 0i32;
 6535
 6536        for selection in self.selections.all::<usize>(cx) {
 6537            let selection_is_empty = selection.is_empty();
 6538
 6539            let (start, end) = if selection_is_empty {
 6540                let word_range = movement::surrounding_word(
 6541                    &display_map,
 6542                    selection.start.to_display_point(&display_map),
 6543                );
 6544                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6545                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6546                (start, end)
 6547            } else {
 6548                (selection.start, selection.end)
 6549            };
 6550
 6551            let text = buffer.text_for_range(start..end).collect::<String>();
 6552            let old_length = text.len() as i32;
 6553            let text = callback(&text);
 6554
 6555            new_selections.push(Selection {
 6556                start: (start as i32 - selection_adjustment) as usize,
 6557                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6558                goal: SelectionGoal::None,
 6559                ..selection
 6560            });
 6561
 6562            selection_adjustment += old_length - text.len() as i32;
 6563
 6564            edits.push((start..end, text));
 6565        }
 6566
 6567        self.transact(cx, |this, cx| {
 6568            this.buffer.update(cx, |buffer, cx| {
 6569                buffer.edit(edits, None, cx);
 6570            });
 6571
 6572            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6573                s.select(new_selections);
 6574            });
 6575
 6576            this.request_autoscroll(Autoscroll::fit(), cx);
 6577        });
 6578    }
 6579
 6580    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6582        let buffer = &display_map.buffer_snapshot;
 6583        let selections = self.selections.all::<Point>(cx);
 6584
 6585        let mut edits = Vec::new();
 6586        let mut selections_iter = selections.iter().peekable();
 6587        while let Some(selection) = selections_iter.next() {
 6588            // Avoid duplicating the same lines twice.
 6589            let mut rows = selection.spanned_rows(false, &display_map);
 6590
 6591            while let Some(next_selection) = selections_iter.peek() {
 6592                let next_rows = next_selection.spanned_rows(false, &display_map);
 6593                if next_rows.start < rows.end {
 6594                    rows.end = next_rows.end;
 6595                    selections_iter.next().unwrap();
 6596                } else {
 6597                    break;
 6598                }
 6599            }
 6600
 6601            // Copy the text from the selected row region and splice it either at the start
 6602            // or end of the region.
 6603            let start = Point::new(rows.start.0, 0);
 6604            let end = Point::new(
 6605                rows.end.previous_row().0,
 6606                buffer.line_len(rows.end.previous_row()),
 6607            );
 6608            let text = buffer
 6609                .text_for_range(start..end)
 6610                .chain(Some("\n"))
 6611                .collect::<String>();
 6612            let insert_location = if upwards {
 6613                Point::new(rows.end.0, 0)
 6614            } else {
 6615                start
 6616            };
 6617            edits.push((insert_location..insert_location, text));
 6618        }
 6619
 6620        self.transact(cx, |this, cx| {
 6621            this.buffer.update(cx, |buffer, cx| {
 6622                buffer.edit(edits, None, cx);
 6623            });
 6624
 6625            this.request_autoscroll(Autoscroll::fit(), cx);
 6626        });
 6627    }
 6628
 6629    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6630        self.duplicate_line(true, cx);
 6631    }
 6632
 6633    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6634        self.duplicate_line(false, cx);
 6635    }
 6636
 6637    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6638        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6639        let buffer = self.buffer.read(cx).snapshot(cx);
 6640
 6641        let mut edits = Vec::new();
 6642        let mut unfold_ranges = Vec::new();
 6643        let mut refold_ranges = Vec::new();
 6644
 6645        let selections = self.selections.all::<Point>(cx);
 6646        let mut selections = selections.iter().peekable();
 6647        let mut contiguous_row_selections = Vec::new();
 6648        let mut new_selections = Vec::new();
 6649
 6650        while let Some(selection) = selections.next() {
 6651            // Find all the selections that span a contiguous row range
 6652            let (start_row, end_row) = consume_contiguous_rows(
 6653                &mut contiguous_row_selections,
 6654                selection,
 6655                &display_map,
 6656                &mut selections,
 6657            );
 6658
 6659            // Move the text spanned by the row range to be before the line preceding the row range
 6660            if start_row.0 > 0 {
 6661                let range_to_move = Point::new(
 6662                    start_row.previous_row().0,
 6663                    buffer.line_len(start_row.previous_row()),
 6664                )
 6665                    ..Point::new(
 6666                        end_row.previous_row().0,
 6667                        buffer.line_len(end_row.previous_row()),
 6668                    );
 6669                let insertion_point = display_map
 6670                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6671                    .0;
 6672
 6673                // Don't move lines across excerpts
 6674                if buffer
 6675                    .excerpt_boundaries_in_range((
 6676                        Bound::Excluded(insertion_point),
 6677                        Bound::Included(range_to_move.end),
 6678                    ))
 6679                    .next()
 6680                    .is_none()
 6681                {
 6682                    let text = buffer
 6683                        .text_for_range(range_to_move.clone())
 6684                        .flat_map(|s| s.chars())
 6685                        .skip(1)
 6686                        .chain(['\n'])
 6687                        .collect::<String>();
 6688
 6689                    edits.push((
 6690                        buffer.anchor_after(range_to_move.start)
 6691                            ..buffer.anchor_before(range_to_move.end),
 6692                        String::new(),
 6693                    ));
 6694                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6695                    edits.push((insertion_anchor..insertion_anchor, text));
 6696
 6697                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6698
 6699                    // Move selections up
 6700                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6701                        |mut selection| {
 6702                            selection.start.row -= row_delta;
 6703                            selection.end.row -= row_delta;
 6704                            selection
 6705                        },
 6706                    ));
 6707
 6708                    // Move folds up
 6709                    unfold_ranges.push(range_to_move.clone());
 6710                    for fold in display_map.folds_in_range(
 6711                        buffer.anchor_before(range_to_move.start)
 6712                            ..buffer.anchor_after(range_to_move.end),
 6713                    ) {
 6714                        let mut start = fold.range.start.to_point(&buffer);
 6715                        let mut end = fold.range.end.to_point(&buffer);
 6716                        start.row -= row_delta;
 6717                        end.row -= row_delta;
 6718                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6719                    }
 6720                }
 6721            }
 6722
 6723            // If we didn't move line(s), preserve the existing selections
 6724            new_selections.append(&mut contiguous_row_selections);
 6725        }
 6726
 6727        self.transact(cx, |this, cx| {
 6728            this.unfold_ranges(unfold_ranges, true, true, cx);
 6729            this.buffer.update(cx, |buffer, cx| {
 6730                for (range, text) in edits {
 6731                    buffer.edit([(range, text)], None, cx);
 6732                }
 6733            });
 6734            this.fold_ranges(refold_ranges, true, cx);
 6735            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6736                s.select(new_selections);
 6737            })
 6738        });
 6739    }
 6740
 6741    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6742        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6743        let buffer = self.buffer.read(cx).snapshot(cx);
 6744
 6745        let mut edits = Vec::new();
 6746        let mut unfold_ranges = Vec::new();
 6747        let mut refold_ranges = Vec::new();
 6748
 6749        let selections = self.selections.all::<Point>(cx);
 6750        let mut selections = selections.iter().peekable();
 6751        let mut contiguous_row_selections = Vec::new();
 6752        let mut new_selections = Vec::new();
 6753
 6754        while let Some(selection) = selections.next() {
 6755            // Find all the selections that span a contiguous row range
 6756            let (start_row, end_row) = consume_contiguous_rows(
 6757                &mut contiguous_row_selections,
 6758                selection,
 6759                &display_map,
 6760                &mut selections,
 6761            );
 6762
 6763            // Move the text spanned by the row range to be after the last line of the row range
 6764            if end_row.0 <= buffer.max_point().row {
 6765                let range_to_move =
 6766                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6767                let insertion_point = display_map
 6768                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6769                    .0;
 6770
 6771                // Don't move lines across excerpt boundaries
 6772                if buffer
 6773                    .excerpt_boundaries_in_range((
 6774                        Bound::Excluded(range_to_move.start),
 6775                        Bound::Included(insertion_point),
 6776                    ))
 6777                    .next()
 6778                    .is_none()
 6779                {
 6780                    let mut text = String::from("\n");
 6781                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6782                    text.pop(); // Drop trailing newline
 6783                    edits.push((
 6784                        buffer.anchor_after(range_to_move.start)
 6785                            ..buffer.anchor_before(range_to_move.end),
 6786                        String::new(),
 6787                    ));
 6788                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6789                    edits.push((insertion_anchor..insertion_anchor, text));
 6790
 6791                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6792
 6793                    // Move selections down
 6794                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6795                        |mut selection| {
 6796                            selection.start.row += row_delta;
 6797                            selection.end.row += row_delta;
 6798                            selection
 6799                        },
 6800                    ));
 6801
 6802                    // Move folds down
 6803                    unfold_ranges.push(range_to_move.clone());
 6804                    for fold in display_map.folds_in_range(
 6805                        buffer.anchor_before(range_to_move.start)
 6806                            ..buffer.anchor_after(range_to_move.end),
 6807                    ) {
 6808                        let mut start = fold.range.start.to_point(&buffer);
 6809                        let mut end = fold.range.end.to_point(&buffer);
 6810                        start.row += row_delta;
 6811                        end.row += row_delta;
 6812                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6813                    }
 6814                }
 6815            }
 6816
 6817            // If we didn't move line(s), preserve the existing selections
 6818            new_selections.append(&mut contiguous_row_selections);
 6819        }
 6820
 6821        self.transact(cx, |this, cx| {
 6822            this.unfold_ranges(unfold_ranges, true, true, cx);
 6823            this.buffer.update(cx, |buffer, cx| {
 6824                for (range, text) in edits {
 6825                    buffer.edit([(range, text)], None, cx);
 6826                }
 6827            });
 6828            this.fold_ranges(refold_ranges, true, cx);
 6829            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6830        });
 6831    }
 6832
 6833    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6834        let text_layout_details = &self.text_layout_details(cx);
 6835        self.transact(cx, |this, cx| {
 6836            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6837                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6838                let line_mode = s.line_mode;
 6839                s.move_with(|display_map, selection| {
 6840                    if !selection.is_empty() || line_mode {
 6841                        return;
 6842                    }
 6843
 6844                    let mut head = selection.head();
 6845                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6846                    if head.column() == display_map.line_len(head.row()) {
 6847                        transpose_offset = display_map
 6848                            .buffer_snapshot
 6849                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6850                    }
 6851
 6852                    if transpose_offset == 0 {
 6853                        return;
 6854                    }
 6855
 6856                    *head.column_mut() += 1;
 6857                    head = display_map.clip_point(head, Bias::Right);
 6858                    let goal = SelectionGoal::HorizontalPosition(
 6859                        display_map
 6860                            .x_for_display_point(head, text_layout_details)
 6861                            .into(),
 6862                    );
 6863                    selection.collapse_to(head, goal);
 6864
 6865                    let transpose_start = display_map
 6866                        .buffer_snapshot
 6867                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6868                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6869                        let transpose_end = display_map
 6870                            .buffer_snapshot
 6871                            .clip_offset(transpose_offset + 1, Bias::Right);
 6872                        if let Some(ch) =
 6873                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6874                        {
 6875                            edits.push((transpose_start..transpose_offset, String::new()));
 6876                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6877                        }
 6878                    }
 6879                });
 6880                edits
 6881            });
 6882            this.buffer
 6883                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6884            let selections = this.selections.all::<usize>(cx);
 6885            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6886                s.select(selections);
 6887            });
 6888        });
 6889    }
 6890
 6891    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6892        self.rewrap_impl(true, cx)
 6893    }
 6894
 6895    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6896        let buffer = self.buffer.read(cx).snapshot(cx);
 6897        let selections = self.selections.all::<Point>(cx);
 6898        let mut selections = selections.iter().peekable();
 6899
 6900        let mut edits = Vec::new();
 6901        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6902
 6903        while let Some(selection) = selections.next() {
 6904            let mut start_row = selection.start.row;
 6905            let mut end_row = selection.end.row;
 6906
 6907            // Skip selections that overlap with a range that has already been rewrapped.
 6908            let selection_range = start_row..end_row;
 6909            if rewrapped_row_ranges
 6910                .iter()
 6911                .any(|range| range.overlaps(&selection_range))
 6912            {
 6913                continue;
 6914            }
 6915
 6916            let mut should_rewrap = !only_text;
 6917
 6918            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6919                match language_scope.language_name().0.as_ref() {
 6920                    "Markdown" | "Plain Text" => {
 6921                        should_rewrap = true;
 6922                    }
 6923                    _ => {}
 6924                }
 6925            }
 6926
 6927            // Since not all lines in the selection may be at the same indent
 6928            // level, choose the indent size that is the most common between all
 6929            // of the lines.
 6930            //
 6931            // If there is a tie, we use the deepest indent.
 6932            let (indent_size, indent_end) = {
 6933                let mut indent_size_occurrences = HashMap::default();
 6934                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6935
 6936                for row in start_row..=end_row {
 6937                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6938                    rows_by_indent_size.entry(indent).or_default().push(row);
 6939                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6940                }
 6941
 6942                let indent_size = indent_size_occurrences
 6943                    .into_iter()
 6944                    .max_by_key(|(indent, count)| (*count, indent.len))
 6945                    .map(|(indent, _)| indent)
 6946                    .unwrap_or_default();
 6947                let row = rows_by_indent_size[&indent_size][0];
 6948                let indent_end = Point::new(row, indent_size.len);
 6949
 6950                (indent_size, indent_end)
 6951            };
 6952
 6953            let mut line_prefix = indent_size.chars().collect::<String>();
 6954
 6955            if let Some(comment_prefix) =
 6956                buffer
 6957                    .language_scope_at(selection.head())
 6958                    .and_then(|language| {
 6959                        language
 6960                            .line_comment_prefixes()
 6961                            .iter()
 6962                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6963                            .cloned()
 6964                    })
 6965            {
 6966                line_prefix.push_str(&comment_prefix);
 6967                should_rewrap = true;
 6968            }
 6969
 6970            if selection.is_empty() {
 6971                'expand_upwards: while start_row > 0 {
 6972                    let prev_row = start_row - 1;
 6973                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6974                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6975                    {
 6976                        start_row = prev_row;
 6977                    } else {
 6978                        break 'expand_upwards;
 6979                    }
 6980                }
 6981
 6982                'expand_downwards: while end_row < buffer.max_point().row {
 6983                    let next_row = end_row + 1;
 6984                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6985                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6986                    {
 6987                        end_row = next_row;
 6988                    } else {
 6989                        break 'expand_downwards;
 6990                    }
 6991                }
 6992            }
 6993
 6994            if !should_rewrap {
 6995                continue;
 6996            }
 6997
 6998            let start = Point::new(start_row, 0);
 6999            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7000            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7001            let Some(lines_without_prefixes) = selection_text
 7002                .lines()
 7003                .map(|line| {
 7004                    line.strip_prefix(&line_prefix)
 7005                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7006                        .ok_or_else(|| {
 7007                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7008                        })
 7009                })
 7010                .collect::<Result<Vec<_>, _>>()
 7011                .log_err()
 7012            else {
 7013                continue;
 7014            };
 7015
 7016            let unwrapped_text = lines_without_prefixes.join(" ");
 7017            let wrap_column = buffer
 7018                .settings_at(Point::new(start_row, 0), cx)
 7019                .preferred_line_length as usize;
 7020            let mut wrapped_text = String::new();
 7021            let mut current_line = line_prefix.clone();
 7022            for word in unwrapped_text.split_whitespace() {
 7023                if current_line.len() + word.len() >= wrap_column {
 7024                    wrapped_text.push_str(&current_line);
 7025                    wrapped_text.push('\n');
 7026                    current_line.truncate(line_prefix.len());
 7027                }
 7028
 7029                if current_line.len() > line_prefix.len() {
 7030                    current_line.push(' ');
 7031                }
 7032
 7033                current_line.push_str(word);
 7034            }
 7035
 7036            if !current_line.is_empty() {
 7037                wrapped_text.push_str(&current_line);
 7038            }
 7039
 7040            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7041            let mut offset = start.to_offset(&buffer);
 7042            let mut moved_since_edit = true;
 7043
 7044            for change in diff.iter_all_changes() {
 7045                let value = change.value();
 7046                match change.tag() {
 7047                    ChangeTag::Equal => {
 7048                        offset += value.len();
 7049                        moved_since_edit = true;
 7050                    }
 7051                    ChangeTag::Delete => {
 7052                        let start = buffer.anchor_after(offset);
 7053                        let end = buffer.anchor_before(offset + value.len());
 7054
 7055                        if moved_since_edit {
 7056                            edits.push((start..end, String::new()));
 7057                        } else {
 7058                            edits.last_mut().unwrap().0.end = end;
 7059                        }
 7060
 7061                        offset += value.len();
 7062                        moved_since_edit = false;
 7063                    }
 7064                    ChangeTag::Insert => {
 7065                        if moved_since_edit {
 7066                            let anchor = buffer.anchor_after(offset);
 7067                            edits.push((anchor..anchor, value.to_string()));
 7068                        } else {
 7069                            edits.last_mut().unwrap().1.push_str(value);
 7070                        }
 7071
 7072                        moved_since_edit = false;
 7073                    }
 7074                }
 7075            }
 7076
 7077            rewrapped_row_ranges.push(start_row..=end_row);
 7078        }
 7079
 7080        self.buffer
 7081            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7082    }
 7083
 7084    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7085        let mut text = String::new();
 7086        let buffer = self.buffer.read(cx).snapshot(cx);
 7087        let mut selections = self.selections.all::<Point>(cx);
 7088        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7089        {
 7090            let max_point = buffer.max_point();
 7091            let mut is_first = true;
 7092            for selection in &mut selections {
 7093                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7094                if is_entire_line {
 7095                    selection.start = Point::new(selection.start.row, 0);
 7096                    if !selection.is_empty() && selection.end.column == 0 {
 7097                        selection.end = cmp::min(max_point, selection.end);
 7098                    } else {
 7099                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7100                    }
 7101                    selection.goal = SelectionGoal::None;
 7102                }
 7103                if is_first {
 7104                    is_first = false;
 7105                } else {
 7106                    text += "\n";
 7107                }
 7108                let mut len = 0;
 7109                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7110                    text.push_str(chunk);
 7111                    len += chunk.len();
 7112                }
 7113                clipboard_selections.push(ClipboardSelection {
 7114                    len,
 7115                    is_entire_line,
 7116                    first_line_indent: buffer
 7117                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7118                        .len,
 7119                });
 7120            }
 7121        }
 7122
 7123        self.transact(cx, |this, cx| {
 7124            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7125                s.select(selections);
 7126            });
 7127            this.insert("", cx);
 7128            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7129                text,
 7130                clipboard_selections,
 7131            ));
 7132        });
 7133    }
 7134
 7135    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7136        let selections = self.selections.all::<Point>(cx);
 7137        let buffer = self.buffer.read(cx).read(cx);
 7138        let mut text = String::new();
 7139
 7140        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7141        {
 7142            let max_point = buffer.max_point();
 7143            let mut is_first = true;
 7144            for selection in selections.iter() {
 7145                let mut start = selection.start;
 7146                let mut end = selection.end;
 7147                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7148                if is_entire_line {
 7149                    start = Point::new(start.row, 0);
 7150                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7151                }
 7152                if is_first {
 7153                    is_first = false;
 7154                } else {
 7155                    text += "\n";
 7156                }
 7157                let mut len = 0;
 7158                for chunk in buffer.text_for_range(start..end) {
 7159                    text.push_str(chunk);
 7160                    len += chunk.len();
 7161                }
 7162                clipboard_selections.push(ClipboardSelection {
 7163                    len,
 7164                    is_entire_line,
 7165                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7166                });
 7167            }
 7168        }
 7169
 7170        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7171            text,
 7172            clipboard_selections,
 7173        ));
 7174    }
 7175
 7176    pub fn do_paste(
 7177        &mut self,
 7178        text: &String,
 7179        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7180        handle_entire_lines: bool,
 7181        cx: &mut ViewContext<Self>,
 7182    ) {
 7183        if self.read_only(cx) {
 7184            return;
 7185        }
 7186
 7187        let clipboard_text = Cow::Borrowed(text);
 7188
 7189        self.transact(cx, |this, cx| {
 7190            if let Some(mut clipboard_selections) = clipboard_selections {
 7191                let old_selections = this.selections.all::<usize>(cx);
 7192                let all_selections_were_entire_line =
 7193                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7194                let first_selection_indent_column =
 7195                    clipboard_selections.first().map(|s| s.first_line_indent);
 7196                if clipboard_selections.len() != old_selections.len() {
 7197                    clipboard_selections.drain(..);
 7198                }
 7199
 7200                this.buffer.update(cx, |buffer, cx| {
 7201                    let snapshot = buffer.read(cx);
 7202                    let mut start_offset = 0;
 7203                    let mut edits = Vec::new();
 7204                    let mut original_indent_columns = Vec::new();
 7205                    for (ix, selection) in old_selections.iter().enumerate() {
 7206                        let to_insert;
 7207                        let entire_line;
 7208                        let original_indent_column;
 7209                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7210                            let end_offset = start_offset + clipboard_selection.len;
 7211                            to_insert = &clipboard_text[start_offset..end_offset];
 7212                            entire_line = clipboard_selection.is_entire_line;
 7213                            start_offset = end_offset + 1;
 7214                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7215                        } else {
 7216                            to_insert = clipboard_text.as_str();
 7217                            entire_line = all_selections_were_entire_line;
 7218                            original_indent_column = first_selection_indent_column
 7219                        }
 7220
 7221                        // If the corresponding selection was empty when this slice of the
 7222                        // clipboard text was written, then the entire line containing the
 7223                        // selection was copied. If this selection is also currently empty,
 7224                        // then paste the line before the current line of the buffer.
 7225                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7226                            let column = selection.start.to_point(&snapshot).column as usize;
 7227                            let line_start = selection.start - column;
 7228                            line_start..line_start
 7229                        } else {
 7230                            selection.range()
 7231                        };
 7232
 7233                        edits.push((range, to_insert));
 7234                        original_indent_columns.extend(original_indent_column);
 7235                    }
 7236                    drop(snapshot);
 7237
 7238                    buffer.edit(
 7239                        edits,
 7240                        Some(AutoindentMode::Block {
 7241                            original_indent_columns,
 7242                        }),
 7243                        cx,
 7244                    );
 7245                });
 7246
 7247                let selections = this.selections.all::<usize>(cx);
 7248                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7249            } else {
 7250                this.insert(&clipboard_text, cx);
 7251            }
 7252        });
 7253    }
 7254
 7255    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7256        if let Some(item) = cx.read_from_clipboard() {
 7257            let entries = item.entries();
 7258
 7259            match entries.first() {
 7260                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7261                // of all the pasted entries.
 7262                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7263                    .do_paste(
 7264                        clipboard_string.text(),
 7265                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7266                        true,
 7267                        cx,
 7268                    ),
 7269                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7270            }
 7271        }
 7272    }
 7273
 7274    pub fn undo(&mut self, _: &Undo, 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.undo(cx)) {
 7280            if let 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            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7292        }
 7293    }
 7294
 7295    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7296        if self.read_only(cx) {
 7297            return;
 7298        }
 7299
 7300        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7301            if let Some((_, Some(selections))) =
 7302                self.selection_history.transaction(transaction_id).cloned()
 7303            {
 7304                self.change_selections(None, cx, |s| {
 7305                    s.select_anchors(selections.to_vec());
 7306                });
 7307            }
 7308            self.request_autoscroll(Autoscroll::fit(), cx);
 7309            self.unmark_text(cx);
 7310            self.refresh_inline_completion(true, false, cx);
 7311            cx.emit(EditorEvent::Edited { transaction_id });
 7312        }
 7313    }
 7314
 7315    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7316        self.buffer
 7317            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7318    }
 7319
 7320    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7321        self.buffer
 7322            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7323    }
 7324
 7325    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7327            let line_mode = s.line_mode;
 7328            s.move_with(|map, selection| {
 7329                let cursor = if selection.is_empty() && !line_mode {
 7330                    movement::left(map, selection.start)
 7331                } else {
 7332                    selection.start
 7333                };
 7334                selection.collapse_to(cursor, SelectionGoal::None);
 7335            });
 7336        })
 7337    }
 7338
 7339    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7340        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7341            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7342        })
 7343    }
 7344
 7345    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7346        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7347            let line_mode = s.line_mode;
 7348            s.move_with(|map, selection| {
 7349                let cursor = if selection.is_empty() && !line_mode {
 7350                    movement::right(map, selection.end)
 7351                } else {
 7352                    selection.end
 7353                };
 7354                selection.collapse_to(cursor, SelectionGoal::None)
 7355            });
 7356        })
 7357    }
 7358
 7359    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7360        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7361            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7362        })
 7363    }
 7364
 7365    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7366        if self.take_rename(true, cx).is_some() {
 7367            return;
 7368        }
 7369
 7370        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7371            cx.propagate();
 7372            return;
 7373        }
 7374
 7375        let text_layout_details = &self.text_layout_details(cx);
 7376        let selection_count = self.selections.count();
 7377        let first_selection = self.selections.first_anchor();
 7378
 7379        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7380            let line_mode = s.line_mode;
 7381            s.move_with(|map, selection| {
 7382                if !selection.is_empty() && !line_mode {
 7383                    selection.goal = SelectionGoal::None;
 7384                }
 7385                let (cursor, goal) = movement::up(
 7386                    map,
 7387                    selection.start,
 7388                    selection.goal,
 7389                    false,
 7390                    text_layout_details,
 7391                );
 7392                selection.collapse_to(cursor, goal);
 7393            });
 7394        });
 7395
 7396        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7397        {
 7398            cx.propagate();
 7399        }
 7400    }
 7401
 7402    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7403        if self.take_rename(true, cx).is_some() {
 7404            return;
 7405        }
 7406
 7407        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7408            cx.propagate();
 7409            return;
 7410        }
 7411
 7412        let text_layout_details = &self.text_layout_details(cx);
 7413
 7414        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7415            let line_mode = s.line_mode;
 7416            s.move_with(|map, selection| {
 7417                if !selection.is_empty() && !line_mode {
 7418                    selection.goal = SelectionGoal::None;
 7419                }
 7420                let (cursor, goal) = movement::up_by_rows(
 7421                    map,
 7422                    selection.start,
 7423                    action.lines,
 7424                    selection.goal,
 7425                    false,
 7426                    text_layout_details,
 7427                );
 7428                selection.collapse_to(cursor, goal);
 7429            });
 7430        })
 7431    }
 7432
 7433    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7434        if self.take_rename(true, cx).is_some() {
 7435            return;
 7436        }
 7437
 7438        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7439            cx.propagate();
 7440            return;
 7441        }
 7442
 7443        let text_layout_details = &self.text_layout_details(cx);
 7444
 7445        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7446            let line_mode = s.line_mode;
 7447            s.move_with(|map, selection| {
 7448                if !selection.is_empty() && !line_mode {
 7449                    selection.goal = SelectionGoal::None;
 7450                }
 7451                let (cursor, goal) = movement::down_by_rows(
 7452                    map,
 7453                    selection.start,
 7454                    action.lines,
 7455                    selection.goal,
 7456                    false,
 7457                    text_layout_details,
 7458                );
 7459                selection.collapse_to(cursor, goal);
 7460            });
 7461        })
 7462    }
 7463
 7464    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7465        let text_layout_details = &self.text_layout_details(cx);
 7466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7467            s.move_heads_with(|map, head, goal| {
 7468                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7469            })
 7470        })
 7471    }
 7472
 7473    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7474        let text_layout_details = &self.text_layout_details(cx);
 7475        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7476            s.move_heads_with(|map, head, goal| {
 7477                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7478            })
 7479        })
 7480    }
 7481
 7482    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7483        let Some(row_count) = self.visible_row_count() else {
 7484            return;
 7485        };
 7486
 7487        let text_layout_details = &self.text_layout_details(cx);
 7488
 7489        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7490            s.move_heads_with(|map, head, goal| {
 7491                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7492            })
 7493        })
 7494    }
 7495
 7496    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7497        if self.take_rename(true, cx).is_some() {
 7498            return;
 7499        }
 7500
 7501        if self
 7502            .context_menu
 7503            .write()
 7504            .as_mut()
 7505            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7506            .unwrap_or(false)
 7507        {
 7508            return;
 7509        }
 7510
 7511        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7512            cx.propagate();
 7513            return;
 7514        }
 7515
 7516        let Some(row_count) = self.visible_row_count() else {
 7517            return;
 7518        };
 7519
 7520        let autoscroll = if action.center_cursor {
 7521            Autoscroll::center()
 7522        } else {
 7523            Autoscroll::fit()
 7524        };
 7525
 7526        let text_layout_details = &self.text_layout_details(cx);
 7527
 7528        self.change_selections(Some(autoscroll), cx, |s| {
 7529            let line_mode = s.line_mode;
 7530            s.move_with(|map, selection| {
 7531                if !selection.is_empty() && !line_mode {
 7532                    selection.goal = SelectionGoal::None;
 7533                }
 7534                let (cursor, goal) = movement::up_by_rows(
 7535                    map,
 7536                    selection.end,
 7537                    row_count,
 7538                    selection.goal,
 7539                    false,
 7540                    text_layout_details,
 7541                );
 7542                selection.collapse_to(cursor, goal);
 7543            });
 7544        });
 7545    }
 7546
 7547    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7548        let text_layout_details = &self.text_layout_details(cx);
 7549        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7550            s.move_heads_with(|map, head, goal| {
 7551                movement::up(map, head, goal, false, text_layout_details)
 7552            })
 7553        })
 7554    }
 7555
 7556    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7557        self.take_rename(true, cx);
 7558
 7559        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7560            cx.propagate();
 7561            return;
 7562        }
 7563
 7564        let text_layout_details = &self.text_layout_details(cx);
 7565        let selection_count = self.selections.count();
 7566        let first_selection = self.selections.first_anchor();
 7567
 7568        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7569            let line_mode = s.line_mode;
 7570            s.move_with(|map, selection| {
 7571                if !selection.is_empty() && !line_mode {
 7572                    selection.goal = SelectionGoal::None;
 7573                }
 7574                let (cursor, goal) = movement::down(
 7575                    map,
 7576                    selection.end,
 7577                    selection.goal,
 7578                    false,
 7579                    text_layout_details,
 7580                );
 7581                selection.collapse_to(cursor, goal);
 7582            });
 7583        });
 7584
 7585        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7586        {
 7587            cx.propagate();
 7588        }
 7589    }
 7590
 7591    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7592        let Some(row_count) = self.visible_row_count() else {
 7593            return;
 7594        };
 7595
 7596        let text_layout_details = &self.text_layout_details(cx);
 7597
 7598        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7599            s.move_heads_with(|map, head, goal| {
 7600                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7601            })
 7602        })
 7603    }
 7604
 7605    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7606        if self.take_rename(true, cx).is_some() {
 7607            return;
 7608        }
 7609
 7610        if self
 7611            .context_menu
 7612            .write()
 7613            .as_mut()
 7614            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7615            .unwrap_or(false)
 7616        {
 7617            return;
 7618        }
 7619
 7620        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7621            cx.propagate();
 7622            return;
 7623        }
 7624
 7625        let Some(row_count) = self.visible_row_count() else {
 7626            return;
 7627        };
 7628
 7629        let autoscroll = if action.center_cursor {
 7630            Autoscroll::center()
 7631        } else {
 7632            Autoscroll::fit()
 7633        };
 7634
 7635        let text_layout_details = &self.text_layout_details(cx);
 7636        self.change_selections(Some(autoscroll), cx, |s| {
 7637            let line_mode = s.line_mode;
 7638            s.move_with(|map, selection| {
 7639                if !selection.is_empty() && !line_mode {
 7640                    selection.goal = SelectionGoal::None;
 7641                }
 7642                let (cursor, goal) = movement::down_by_rows(
 7643                    map,
 7644                    selection.end,
 7645                    row_count,
 7646                    selection.goal,
 7647                    false,
 7648                    text_layout_details,
 7649                );
 7650                selection.collapse_to(cursor, goal);
 7651            });
 7652        });
 7653    }
 7654
 7655    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7656        let text_layout_details = &self.text_layout_details(cx);
 7657        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7658            s.move_heads_with(|map, head, goal| {
 7659                movement::down(map, head, goal, false, text_layout_details)
 7660            })
 7661        });
 7662    }
 7663
 7664    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7665        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7666            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7667        }
 7668    }
 7669
 7670    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7671        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7672            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7673        }
 7674    }
 7675
 7676    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7677        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7678            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7679        }
 7680    }
 7681
 7682    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7683        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7684            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7685        }
 7686    }
 7687
 7688    pub fn move_to_previous_word_start(
 7689        &mut self,
 7690        _: &MoveToPreviousWordStart,
 7691        cx: &mut ViewContext<Self>,
 7692    ) {
 7693        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7694            s.move_cursors_with(|map, head, _| {
 7695                (
 7696                    movement::previous_word_start(map, head),
 7697                    SelectionGoal::None,
 7698                )
 7699            });
 7700        })
 7701    }
 7702
 7703    pub fn move_to_previous_subword_start(
 7704        &mut self,
 7705        _: &MoveToPreviousSubwordStart,
 7706        cx: &mut ViewContext<Self>,
 7707    ) {
 7708        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7709            s.move_cursors_with(|map, head, _| {
 7710                (
 7711                    movement::previous_subword_start(map, head),
 7712                    SelectionGoal::None,
 7713                )
 7714            });
 7715        })
 7716    }
 7717
 7718    pub fn select_to_previous_word_start(
 7719        &mut self,
 7720        _: &SelectToPreviousWordStart,
 7721        cx: &mut ViewContext<Self>,
 7722    ) {
 7723        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7724            s.move_heads_with(|map, head, _| {
 7725                (
 7726                    movement::previous_word_start(map, head),
 7727                    SelectionGoal::None,
 7728                )
 7729            });
 7730        })
 7731    }
 7732
 7733    pub fn select_to_previous_subword_start(
 7734        &mut self,
 7735        _: &SelectToPreviousSubwordStart,
 7736        cx: &mut ViewContext<Self>,
 7737    ) {
 7738        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7739            s.move_heads_with(|map, head, _| {
 7740                (
 7741                    movement::previous_subword_start(map, head),
 7742                    SelectionGoal::None,
 7743                )
 7744            });
 7745        })
 7746    }
 7747
 7748    pub fn delete_to_previous_word_start(
 7749        &mut self,
 7750        action: &DeleteToPreviousWordStart,
 7751        cx: &mut ViewContext<Self>,
 7752    ) {
 7753        self.transact(cx, |this, cx| {
 7754            this.select_autoclose_pair(cx);
 7755            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7756                let line_mode = s.line_mode;
 7757                s.move_with(|map, selection| {
 7758                    if selection.is_empty() && !line_mode {
 7759                        let cursor = if action.ignore_newlines {
 7760                            movement::previous_word_start(map, selection.head())
 7761                        } else {
 7762                            movement::previous_word_start_or_newline(map, selection.head())
 7763                        };
 7764                        selection.set_head(cursor, SelectionGoal::None);
 7765                    }
 7766                });
 7767            });
 7768            this.insert("", cx);
 7769        });
 7770    }
 7771
 7772    pub fn delete_to_previous_subword_start(
 7773        &mut self,
 7774        _: &DeleteToPreviousSubwordStart,
 7775        cx: &mut ViewContext<Self>,
 7776    ) {
 7777        self.transact(cx, |this, cx| {
 7778            this.select_autoclose_pair(cx);
 7779            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7780                let line_mode = s.line_mode;
 7781                s.move_with(|map, selection| {
 7782                    if selection.is_empty() && !line_mode {
 7783                        let cursor = movement::previous_subword_start(map, selection.head());
 7784                        selection.set_head(cursor, SelectionGoal::None);
 7785                    }
 7786                });
 7787            });
 7788            this.insert("", cx);
 7789        });
 7790    }
 7791
 7792    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7794            s.move_cursors_with(|map, head, _| {
 7795                (movement::next_word_end(map, head), SelectionGoal::None)
 7796            });
 7797        })
 7798    }
 7799
 7800    pub fn move_to_next_subword_end(
 7801        &mut self,
 7802        _: &MoveToNextSubwordEnd,
 7803        cx: &mut ViewContext<Self>,
 7804    ) {
 7805        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7806            s.move_cursors_with(|map, head, _| {
 7807                (movement::next_subword_end(map, head), SelectionGoal::None)
 7808            });
 7809        })
 7810    }
 7811
 7812    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7813        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7814            s.move_heads_with(|map, head, _| {
 7815                (movement::next_word_end(map, head), SelectionGoal::None)
 7816            });
 7817        })
 7818    }
 7819
 7820    pub fn select_to_next_subword_end(
 7821        &mut self,
 7822        _: &SelectToNextSubwordEnd,
 7823        cx: &mut ViewContext<Self>,
 7824    ) {
 7825        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7826            s.move_heads_with(|map, head, _| {
 7827                (movement::next_subword_end(map, head), SelectionGoal::None)
 7828            });
 7829        })
 7830    }
 7831
 7832    pub fn delete_to_next_word_end(
 7833        &mut self,
 7834        action: &DeleteToNextWordEnd,
 7835        cx: &mut ViewContext<Self>,
 7836    ) {
 7837        self.transact(cx, |this, cx| {
 7838            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7839                let line_mode = s.line_mode;
 7840                s.move_with(|map, selection| {
 7841                    if selection.is_empty() && !line_mode {
 7842                        let cursor = if action.ignore_newlines {
 7843                            movement::next_word_end(map, selection.head())
 7844                        } else {
 7845                            movement::next_word_end_or_newline(map, selection.head())
 7846                        };
 7847                        selection.set_head(cursor, SelectionGoal::None);
 7848                    }
 7849                });
 7850            });
 7851            this.insert("", cx);
 7852        });
 7853    }
 7854
 7855    pub fn delete_to_next_subword_end(
 7856        &mut self,
 7857        _: &DeleteToNextSubwordEnd,
 7858        cx: &mut ViewContext<Self>,
 7859    ) {
 7860        self.transact(cx, |this, cx| {
 7861            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7862                s.move_with(|map, selection| {
 7863                    if selection.is_empty() {
 7864                        let cursor = movement::next_subword_end(map, selection.head());
 7865                        selection.set_head(cursor, SelectionGoal::None);
 7866                    }
 7867                });
 7868            });
 7869            this.insert("", cx);
 7870        });
 7871    }
 7872
 7873    pub fn move_to_beginning_of_line(
 7874        &mut self,
 7875        action: &MoveToBeginningOfLine,
 7876        cx: &mut ViewContext<Self>,
 7877    ) {
 7878        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7879            s.move_cursors_with(|map, head, _| {
 7880                (
 7881                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7882                    SelectionGoal::None,
 7883                )
 7884            });
 7885        })
 7886    }
 7887
 7888    pub fn select_to_beginning_of_line(
 7889        &mut self,
 7890        action: &SelectToBeginningOfLine,
 7891        cx: &mut ViewContext<Self>,
 7892    ) {
 7893        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7894            s.move_heads_with(|map, head, _| {
 7895                (
 7896                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7897                    SelectionGoal::None,
 7898                )
 7899            });
 7900        });
 7901    }
 7902
 7903    pub fn delete_to_beginning_of_line(
 7904        &mut self,
 7905        _: &DeleteToBeginningOfLine,
 7906        cx: &mut ViewContext<Self>,
 7907    ) {
 7908        self.transact(cx, |this, cx| {
 7909            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7910                s.move_with(|_, selection| {
 7911                    selection.reversed = true;
 7912                });
 7913            });
 7914
 7915            this.select_to_beginning_of_line(
 7916                &SelectToBeginningOfLine {
 7917                    stop_at_soft_wraps: false,
 7918                },
 7919                cx,
 7920            );
 7921            this.backspace(&Backspace, cx);
 7922        });
 7923    }
 7924
 7925    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7926        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7927            s.move_cursors_with(|map, head, _| {
 7928                (
 7929                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7930                    SelectionGoal::None,
 7931                )
 7932            });
 7933        })
 7934    }
 7935
 7936    pub fn select_to_end_of_line(
 7937        &mut self,
 7938        action: &SelectToEndOfLine,
 7939        cx: &mut ViewContext<Self>,
 7940    ) {
 7941        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7942            s.move_heads_with(|map, head, _| {
 7943                (
 7944                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7945                    SelectionGoal::None,
 7946                )
 7947            });
 7948        })
 7949    }
 7950
 7951    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7952        self.transact(cx, |this, cx| {
 7953            this.select_to_end_of_line(
 7954                &SelectToEndOfLine {
 7955                    stop_at_soft_wraps: false,
 7956                },
 7957                cx,
 7958            );
 7959            this.delete(&Delete, cx);
 7960        });
 7961    }
 7962
 7963    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7964        self.transact(cx, |this, cx| {
 7965            this.select_to_end_of_line(
 7966                &SelectToEndOfLine {
 7967                    stop_at_soft_wraps: false,
 7968                },
 7969                cx,
 7970            );
 7971            this.cut(&Cut, cx);
 7972        });
 7973    }
 7974
 7975    pub fn move_to_start_of_paragraph(
 7976        &mut self,
 7977        _: &MoveToStartOfParagraph,
 7978        cx: &mut ViewContext<Self>,
 7979    ) {
 7980        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7981            cx.propagate();
 7982            return;
 7983        }
 7984
 7985        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7986            s.move_with(|map, selection| {
 7987                selection.collapse_to(
 7988                    movement::start_of_paragraph(map, selection.head(), 1),
 7989                    SelectionGoal::None,
 7990                )
 7991            });
 7992        })
 7993    }
 7994
 7995    pub fn move_to_end_of_paragraph(
 7996        &mut self,
 7997        _: &MoveToEndOfParagraph,
 7998        cx: &mut ViewContext<Self>,
 7999    ) {
 8000        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8001            cx.propagate();
 8002            return;
 8003        }
 8004
 8005        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8006            s.move_with(|map, selection| {
 8007                selection.collapse_to(
 8008                    movement::end_of_paragraph(map, selection.head(), 1),
 8009                    SelectionGoal::None,
 8010                )
 8011            });
 8012        })
 8013    }
 8014
 8015    pub fn select_to_start_of_paragraph(
 8016        &mut self,
 8017        _: &SelectToStartOfParagraph,
 8018        cx: &mut ViewContext<Self>,
 8019    ) {
 8020        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8021            cx.propagate();
 8022            return;
 8023        }
 8024
 8025        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8026            s.move_heads_with(|map, head, _| {
 8027                (
 8028                    movement::start_of_paragraph(map, head, 1),
 8029                    SelectionGoal::None,
 8030                )
 8031            });
 8032        })
 8033    }
 8034
 8035    pub fn select_to_end_of_paragraph(
 8036        &mut self,
 8037        _: &SelectToEndOfParagraph,
 8038        cx: &mut ViewContext<Self>,
 8039    ) {
 8040        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8041            cx.propagate();
 8042            return;
 8043        }
 8044
 8045        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8046            s.move_heads_with(|map, head, _| {
 8047                (
 8048                    movement::end_of_paragraph(map, head, 1),
 8049                    SelectionGoal::None,
 8050                )
 8051            });
 8052        })
 8053    }
 8054
 8055    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8056        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8057            cx.propagate();
 8058            return;
 8059        }
 8060
 8061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8062            s.select_ranges(vec![0..0]);
 8063        });
 8064    }
 8065
 8066    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8067        let mut selection = self.selections.last::<Point>(cx);
 8068        selection.set_head(Point::zero(), SelectionGoal::None);
 8069
 8070        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8071            s.select(vec![selection]);
 8072        });
 8073    }
 8074
 8075    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8076        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8077            cx.propagate();
 8078            return;
 8079        }
 8080
 8081        let cursor = self.buffer.read(cx).read(cx).len();
 8082        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8083            s.select_ranges(vec![cursor..cursor])
 8084        });
 8085    }
 8086
 8087    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8088        self.nav_history = nav_history;
 8089    }
 8090
 8091    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8092        self.nav_history.as_ref()
 8093    }
 8094
 8095    fn push_to_nav_history(
 8096        &mut self,
 8097        cursor_anchor: Anchor,
 8098        new_position: Option<Point>,
 8099        cx: &mut ViewContext<Self>,
 8100    ) {
 8101        if let Some(nav_history) = self.nav_history.as_mut() {
 8102            let buffer = self.buffer.read(cx).read(cx);
 8103            let cursor_position = cursor_anchor.to_point(&buffer);
 8104            let scroll_state = self.scroll_manager.anchor();
 8105            let scroll_top_row = scroll_state.top_row(&buffer);
 8106            drop(buffer);
 8107
 8108            if let Some(new_position) = new_position {
 8109                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8110                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8111                    return;
 8112                }
 8113            }
 8114
 8115            nav_history.push(
 8116                Some(NavigationData {
 8117                    cursor_anchor,
 8118                    cursor_position,
 8119                    scroll_anchor: scroll_state,
 8120                    scroll_top_row,
 8121                }),
 8122                cx,
 8123            );
 8124        }
 8125    }
 8126
 8127    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8128        let buffer = self.buffer.read(cx).snapshot(cx);
 8129        let mut selection = self.selections.first::<usize>(cx);
 8130        selection.set_head(buffer.len(), SelectionGoal::None);
 8131        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8132            s.select(vec![selection]);
 8133        });
 8134    }
 8135
 8136    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8137        let end = self.buffer.read(cx).read(cx).len();
 8138        self.change_selections(None, cx, |s| {
 8139            s.select_ranges(vec![0..end]);
 8140        });
 8141    }
 8142
 8143    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8145        let mut selections = self.selections.all::<Point>(cx);
 8146        let max_point = display_map.buffer_snapshot.max_point();
 8147        for selection in &mut selections {
 8148            let rows = selection.spanned_rows(true, &display_map);
 8149            selection.start = Point::new(rows.start.0, 0);
 8150            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8151            selection.reversed = false;
 8152        }
 8153        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8154            s.select(selections);
 8155        });
 8156    }
 8157
 8158    pub fn split_selection_into_lines(
 8159        &mut self,
 8160        _: &SplitSelectionIntoLines,
 8161        cx: &mut ViewContext<Self>,
 8162    ) {
 8163        let mut to_unfold = Vec::new();
 8164        let mut new_selection_ranges = Vec::new();
 8165        {
 8166            let selections = self.selections.all::<Point>(cx);
 8167            let buffer = self.buffer.read(cx).read(cx);
 8168            for selection in selections {
 8169                for row in selection.start.row..selection.end.row {
 8170                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8171                    new_selection_ranges.push(cursor..cursor);
 8172                }
 8173                new_selection_ranges.push(selection.end..selection.end);
 8174                to_unfold.push(selection.start..selection.end);
 8175            }
 8176        }
 8177        self.unfold_ranges(to_unfold, true, true, cx);
 8178        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8179            s.select_ranges(new_selection_ranges);
 8180        });
 8181    }
 8182
 8183    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8184        self.add_selection(true, cx);
 8185    }
 8186
 8187    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8188        self.add_selection(false, cx);
 8189    }
 8190
 8191    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8192        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8193        let mut selections = self.selections.all::<Point>(cx);
 8194        let text_layout_details = self.text_layout_details(cx);
 8195        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8196            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8197            let range = oldest_selection.display_range(&display_map).sorted();
 8198
 8199            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8200            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8201            let positions = start_x.min(end_x)..start_x.max(end_x);
 8202
 8203            selections.clear();
 8204            let mut stack = Vec::new();
 8205            for row in range.start.row().0..=range.end.row().0 {
 8206                if let Some(selection) = self.selections.build_columnar_selection(
 8207                    &display_map,
 8208                    DisplayRow(row),
 8209                    &positions,
 8210                    oldest_selection.reversed,
 8211                    &text_layout_details,
 8212                ) {
 8213                    stack.push(selection.id);
 8214                    selections.push(selection);
 8215                }
 8216            }
 8217
 8218            if above {
 8219                stack.reverse();
 8220            }
 8221
 8222            AddSelectionsState { above, stack }
 8223        });
 8224
 8225        let last_added_selection = *state.stack.last().unwrap();
 8226        let mut new_selections = Vec::new();
 8227        if above == state.above {
 8228            let end_row = if above {
 8229                DisplayRow(0)
 8230            } else {
 8231                display_map.max_point().row()
 8232            };
 8233
 8234            'outer: for selection in selections {
 8235                if selection.id == last_added_selection {
 8236                    let range = selection.display_range(&display_map).sorted();
 8237                    debug_assert_eq!(range.start.row(), range.end.row());
 8238                    let mut row = range.start.row();
 8239                    let positions =
 8240                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8241                            px(start)..px(end)
 8242                        } else {
 8243                            let start_x =
 8244                                display_map.x_for_display_point(range.start, &text_layout_details);
 8245                            let end_x =
 8246                                display_map.x_for_display_point(range.end, &text_layout_details);
 8247                            start_x.min(end_x)..start_x.max(end_x)
 8248                        };
 8249
 8250                    while row != end_row {
 8251                        if above {
 8252                            row.0 -= 1;
 8253                        } else {
 8254                            row.0 += 1;
 8255                        }
 8256
 8257                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8258                            &display_map,
 8259                            row,
 8260                            &positions,
 8261                            selection.reversed,
 8262                            &text_layout_details,
 8263                        ) {
 8264                            state.stack.push(new_selection.id);
 8265                            if above {
 8266                                new_selections.push(new_selection);
 8267                                new_selections.push(selection);
 8268                            } else {
 8269                                new_selections.push(selection);
 8270                                new_selections.push(new_selection);
 8271                            }
 8272
 8273                            continue 'outer;
 8274                        }
 8275                    }
 8276                }
 8277
 8278                new_selections.push(selection);
 8279            }
 8280        } else {
 8281            new_selections = selections;
 8282            new_selections.retain(|s| s.id != last_added_selection);
 8283            state.stack.pop();
 8284        }
 8285
 8286        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8287            s.select(new_selections);
 8288        });
 8289        if state.stack.len() > 1 {
 8290            self.add_selections_state = Some(state);
 8291        }
 8292    }
 8293
 8294    pub fn select_next_match_internal(
 8295        &mut self,
 8296        display_map: &DisplaySnapshot,
 8297        replace_newest: bool,
 8298        autoscroll: Option<Autoscroll>,
 8299        cx: &mut ViewContext<Self>,
 8300    ) -> Result<()> {
 8301        fn select_next_match_ranges(
 8302            this: &mut Editor,
 8303            range: Range<usize>,
 8304            replace_newest: bool,
 8305            auto_scroll: Option<Autoscroll>,
 8306            cx: &mut ViewContext<Editor>,
 8307        ) {
 8308            this.unfold_ranges([range.clone()], false, true, cx);
 8309            this.change_selections(auto_scroll, cx, |s| {
 8310                if replace_newest {
 8311                    s.delete(s.newest_anchor().id);
 8312                }
 8313                s.insert_range(range.clone());
 8314            });
 8315        }
 8316
 8317        let buffer = &display_map.buffer_snapshot;
 8318        let mut selections = self.selections.all::<usize>(cx);
 8319        if let Some(mut select_next_state) = self.select_next_state.take() {
 8320            let query = &select_next_state.query;
 8321            if !select_next_state.done {
 8322                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8323                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8324                let mut next_selected_range = None;
 8325
 8326                let bytes_after_last_selection =
 8327                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8328                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8329                let query_matches = query
 8330                    .stream_find_iter(bytes_after_last_selection)
 8331                    .map(|result| (last_selection.end, result))
 8332                    .chain(
 8333                        query
 8334                            .stream_find_iter(bytes_before_first_selection)
 8335                            .map(|result| (0, result)),
 8336                    );
 8337
 8338                for (start_offset, query_match) in query_matches {
 8339                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8340                    let offset_range =
 8341                        start_offset + query_match.start()..start_offset + query_match.end();
 8342                    let display_range = offset_range.start.to_display_point(display_map)
 8343                        ..offset_range.end.to_display_point(display_map);
 8344
 8345                    if !select_next_state.wordwise
 8346                        || (!movement::is_inside_word(display_map, display_range.start)
 8347                            && !movement::is_inside_word(display_map, display_range.end))
 8348                    {
 8349                        // TODO: This is n^2, because we might check all the selections
 8350                        if !selections
 8351                            .iter()
 8352                            .any(|selection| selection.range().overlaps(&offset_range))
 8353                        {
 8354                            next_selected_range = Some(offset_range);
 8355                            break;
 8356                        }
 8357                    }
 8358                }
 8359
 8360                if let Some(next_selected_range) = next_selected_range {
 8361                    select_next_match_ranges(
 8362                        self,
 8363                        next_selected_range,
 8364                        replace_newest,
 8365                        autoscroll,
 8366                        cx,
 8367                    );
 8368                } else {
 8369                    select_next_state.done = true;
 8370                }
 8371            }
 8372
 8373            self.select_next_state = Some(select_next_state);
 8374        } else {
 8375            let mut only_carets = true;
 8376            let mut same_text_selected = true;
 8377            let mut selected_text = None;
 8378
 8379            let mut selections_iter = selections.iter().peekable();
 8380            while let Some(selection) = selections_iter.next() {
 8381                if selection.start != selection.end {
 8382                    only_carets = false;
 8383                }
 8384
 8385                if same_text_selected {
 8386                    if selected_text.is_none() {
 8387                        selected_text =
 8388                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8389                    }
 8390
 8391                    if let Some(next_selection) = selections_iter.peek() {
 8392                        if next_selection.range().len() == selection.range().len() {
 8393                            let next_selected_text = buffer
 8394                                .text_for_range(next_selection.range())
 8395                                .collect::<String>();
 8396                            if Some(next_selected_text) != selected_text {
 8397                                same_text_selected = false;
 8398                                selected_text = None;
 8399                            }
 8400                        } else {
 8401                            same_text_selected = false;
 8402                            selected_text = None;
 8403                        }
 8404                    }
 8405                }
 8406            }
 8407
 8408            if only_carets {
 8409                for selection in &mut selections {
 8410                    let word_range = movement::surrounding_word(
 8411                        display_map,
 8412                        selection.start.to_display_point(display_map),
 8413                    );
 8414                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8415                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8416                    selection.goal = SelectionGoal::None;
 8417                    selection.reversed = false;
 8418                    select_next_match_ranges(
 8419                        self,
 8420                        selection.start..selection.end,
 8421                        replace_newest,
 8422                        autoscroll,
 8423                        cx,
 8424                    );
 8425                }
 8426
 8427                if selections.len() == 1 {
 8428                    let selection = selections
 8429                        .last()
 8430                        .expect("ensured that there's only one selection");
 8431                    let query = buffer
 8432                        .text_for_range(selection.start..selection.end)
 8433                        .collect::<String>();
 8434                    let is_empty = query.is_empty();
 8435                    let select_state = SelectNextState {
 8436                        query: AhoCorasick::new(&[query])?,
 8437                        wordwise: true,
 8438                        done: is_empty,
 8439                    };
 8440                    self.select_next_state = Some(select_state);
 8441                } else {
 8442                    self.select_next_state = None;
 8443                }
 8444            } else if let Some(selected_text) = selected_text {
 8445                self.select_next_state = Some(SelectNextState {
 8446                    query: AhoCorasick::new(&[selected_text])?,
 8447                    wordwise: false,
 8448                    done: false,
 8449                });
 8450                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8451            }
 8452        }
 8453        Ok(())
 8454    }
 8455
 8456    pub fn select_all_matches(
 8457        &mut self,
 8458        _action: &SelectAllMatches,
 8459        cx: &mut ViewContext<Self>,
 8460    ) -> Result<()> {
 8461        self.push_to_selection_history();
 8462        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8463
 8464        self.select_next_match_internal(&display_map, false, None, cx)?;
 8465        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8466            return Ok(());
 8467        };
 8468        if select_next_state.done {
 8469            return Ok(());
 8470        }
 8471
 8472        let mut new_selections = self.selections.all::<usize>(cx);
 8473
 8474        let buffer = &display_map.buffer_snapshot;
 8475        let query_matches = select_next_state
 8476            .query
 8477            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8478
 8479        for query_match in query_matches {
 8480            let query_match = query_match.unwrap(); // can only fail due to I/O
 8481            let offset_range = query_match.start()..query_match.end();
 8482            let display_range = offset_range.start.to_display_point(&display_map)
 8483                ..offset_range.end.to_display_point(&display_map);
 8484
 8485            if !select_next_state.wordwise
 8486                || (!movement::is_inside_word(&display_map, display_range.start)
 8487                    && !movement::is_inside_word(&display_map, display_range.end))
 8488            {
 8489                self.selections.change_with(cx, |selections| {
 8490                    new_selections.push(Selection {
 8491                        id: selections.new_selection_id(),
 8492                        start: offset_range.start,
 8493                        end: offset_range.end,
 8494                        reversed: false,
 8495                        goal: SelectionGoal::None,
 8496                    });
 8497                });
 8498            }
 8499        }
 8500
 8501        new_selections.sort_by_key(|selection| selection.start);
 8502        let mut ix = 0;
 8503        while ix + 1 < new_selections.len() {
 8504            let current_selection = &new_selections[ix];
 8505            let next_selection = &new_selections[ix + 1];
 8506            if current_selection.range().overlaps(&next_selection.range()) {
 8507                if current_selection.id < next_selection.id {
 8508                    new_selections.remove(ix + 1);
 8509                } else {
 8510                    new_selections.remove(ix);
 8511                }
 8512            } else {
 8513                ix += 1;
 8514            }
 8515        }
 8516
 8517        select_next_state.done = true;
 8518        self.unfold_ranges(
 8519            new_selections.iter().map(|selection| selection.range()),
 8520            false,
 8521            false,
 8522            cx,
 8523        );
 8524        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8525            selections.select(new_selections)
 8526        });
 8527
 8528        Ok(())
 8529    }
 8530
 8531    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8532        self.push_to_selection_history();
 8533        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8534        self.select_next_match_internal(
 8535            &display_map,
 8536            action.replace_newest,
 8537            Some(Autoscroll::newest()),
 8538            cx,
 8539        )?;
 8540        Ok(())
 8541    }
 8542
 8543    pub fn select_previous(
 8544        &mut self,
 8545        action: &SelectPrevious,
 8546        cx: &mut ViewContext<Self>,
 8547    ) -> Result<()> {
 8548        self.push_to_selection_history();
 8549        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8550        let buffer = &display_map.buffer_snapshot;
 8551        let mut selections = self.selections.all::<usize>(cx);
 8552        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8553            let query = &select_prev_state.query;
 8554            if !select_prev_state.done {
 8555                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8556                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8557                let mut next_selected_range = None;
 8558                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8559                let bytes_before_last_selection =
 8560                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8561                let bytes_after_first_selection =
 8562                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8563                let query_matches = query
 8564                    .stream_find_iter(bytes_before_last_selection)
 8565                    .map(|result| (last_selection.start, result))
 8566                    .chain(
 8567                        query
 8568                            .stream_find_iter(bytes_after_first_selection)
 8569                            .map(|result| (buffer.len(), result)),
 8570                    );
 8571                for (end_offset, query_match) in query_matches {
 8572                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8573                    let offset_range =
 8574                        end_offset - query_match.end()..end_offset - query_match.start();
 8575                    let display_range = offset_range.start.to_display_point(&display_map)
 8576                        ..offset_range.end.to_display_point(&display_map);
 8577
 8578                    if !select_prev_state.wordwise
 8579                        || (!movement::is_inside_word(&display_map, display_range.start)
 8580                            && !movement::is_inside_word(&display_map, display_range.end))
 8581                    {
 8582                        next_selected_range = Some(offset_range);
 8583                        break;
 8584                    }
 8585                }
 8586
 8587                if let Some(next_selected_range) = next_selected_range {
 8588                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8589                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8590                        if action.replace_newest {
 8591                            s.delete(s.newest_anchor().id);
 8592                        }
 8593                        s.insert_range(next_selected_range);
 8594                    });
 8595                } else {
 8596                    select_prev_state.done = true;
 8597                }
 8598            }
 8599
 8600            self.select_prev_state = Some(select_prev_state);
 8601        } else {
 8602            let mut only_carets = true;
 8603            let mut same_text_selected = true;
 8604            let mut selected_text = None;
 8605
 8606            let mut selections_iter = selections.iter().peekable();
 8607            while let Some(selection) = selections_iter.next() {
 8608                if selection.start != selection.end {
 8609                    only_carets = false;
 8610                }
 8611
 8612                if same_text_selected {
 8613                    if selected_text.is_none() {
 8614                        selected_text =
 8615                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8616                    }
 8617
 8618                    if let Some(next_selection) = selections_iter.peek() {
 8619                        if next_selection.range().len() == selection.range().len() {
 8620                            let next_selected_text = buffer
 8621                                .text_for_range(next_selection.range())
 8622                                .collect::<String>();
 8623                            if Some(next_selected_text) != selected_text {
 8624                                same_text_selected = false;
 8625                                selected_text = None;
 8626                            }
 8627                        } else {
 8628                            same_text_selected = false;
 8629                            selected_text = None;
 8630                        }
 8631                    }
 8632                }
 8633            }
 8634
 8635            if only_carets {
 8636                for selection in &mut selections {
 8637                    let word_range = movement::surrounding_word(
 8638                        &display_map,
 8639                        selection.start.to_display_point(&display_map),
 8640                    );
 8641                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8642                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8643                    selection.goal = SelectionGoal::None;
 8644                    selection.reversed = false;
 8645                }
 8646                if selections.len() == 1 {
 8647                    let selection = selections
 8648                        .last()
 8649                        .expect("ensured that there's only one selection");
 8650                    let query = buffer
 8651                        .text_for_range(selection.start..selection.end)
 8652                        .collect::<String>();
 8653                    let is_empty = query.is_empty();
 8654                    let select_state = SelectNextState {
 8655                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8656                        wordwise: true,
 8657                        done: is_empty,
 8658                    };
 8659                    self.select_prev_state = Some(select_state);
 8660                } else {
 8661                    self.select_prev_state = None;
 8662                }
 8663
 8664                self.unfold_ranges(
 8665                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8666                    false,
 8667                    true,
 8668                    cx,
 8669                );
 8670                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8671                    s.select(selections);
 8672                });
 8673            } else if let Some(selected_text) = selected_text {
 8674                self.select_prev_state = Some(SelectNextState {
 8675                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8676                    wordwise: false,
 8677                    done: false,
 8678                });
 8679                self.select_previous(action, cx)?;
 8680            }
 8681        }
 8682        Ok(())
 8683    }
 8684
 8685    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8686        let text_layout_details = &self.text_layout_details(cx);
 8687        self.transact(cx, |this, cx| {
 8688            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8689            let mut edits = Vec::new();
 8690            let mut selection_edit_ranges = Vec::new();
 8691            let mut last_toggled_row = None;
 8692            let snapshot = this.buffer.read(cx).read(cx);
 8693            let empty_str: Arc<str> = Arc::default();
 8694            let mut suffixes_inserted = Vec::new();
 8695
 8696            fn comment_prefix_range(
 8697                snapshot: &MultiBufferSnapshot,
 8698                row: MultiBufferRow,
 8699                comment_prefix: &str,
 8700                comment_prefix_whitespace: &str,
 8701            ) -> Range<Point> {
 8702                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8703
 8704                let mut line_bytes = snapshot
 8705                    .bytes_in_range(start..snapshot.max_point())
 8706                    .flatten()
 8707                    .copied();
 8708
 8709                // If this line currently begins with the line comment prefix, then record
 8710                // the range containing the prefix.
 8711                if line_bytes
 8712                    .by_ref()
 8713                    .take(comment_prefix.len())
 8714                    .eq(comment_prefix.bytes())
 8715                {
 8716                    // Include any whitespace that matches the comment prefix.
 8717                    let matching_whitespace_len = line_bytes
 8718                        .zip(comment_prefix_whitespace.bytes())
 8719                        .take_while(|(a, b)| a == b)
 8720                        .count() as u32;
 8721                    let end = Point::new(
 8722                        start.row,
 8723                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8724                    );
 8725                    start..end
 8726                } else {
 8727                    start..start
 8728                }
 8729            }
 8730
 8731            fn comment_suffix_range(
 8732                snapshot: &MultiBufferSnapshot,
 8733                row: MultiBufferRow,
 8734                comment_suffix: &str,
 8735                comment_suffix_has_leading_space: bool,
 8736            ) -> Range<Point> {
 8737                let end = Point::new(row.0, snapshot.line_len(row));
 8738                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8739
 8740                let mut line_end_bytes = snapshot
 8741                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8742                    .flatten()
 8743                    .copied();
 8744
 8745                let leading_space_len = if suffix_start_column > 0
 8746                    && line_end_bytes.next() == Some(b' ')
 8747                    && comment_suffix_has_leading_space
 8748                {
 8749                    1
 8750                } else {
 8751                    0
 8752                };
 8753
 8754                // If this line currently begins with the line comment prefix, then record
 8755                // the range containing the prefix.
 8756                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8757                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8758                    start..end
 8759                } else {
 8760                    end..end
 8761                }
 8762            }
 8763
 8764            // TODO: Handle selections that cross excerpts
 8765            for selection in &mut selections {
 8766                let start_column = snapshot
 8767                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8768                    .len;
 8769                let language = if let Some(language) =
 8770                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8771                {
 8772                    language
 8773                } else {
 8774                    continue;
 8775                };
 8776
 8777                selection_edit_ranges.clear();
 8778
 8779                // If multiple selections contain a given row, avoid processing that
 8780                // row more than once.
 8781                let mut start_row = MultiBufferRow(selection.start.row);
 8782                if last_toggled_row == Some(start_row) {
 8783                    start_row = start_row.next_row();
 8784                }
 8785                let end_row =
 8786                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8787                        MultiBufferRow(selection.end.row - 1)
 8788                    } else {
 8789                        MultiBufferRow(selection.end.row)
 8790                    };
 8791                last_toggled_row = Some(end_row);
 8792
 8793                if start_row > end_row {
 8794                    continue;
 8795                }
 8796
 8797                // If the language has line comments, toggle those.
 8798                let full_comment_prefixes = language.line_comment_prefixes();
 8799                if !full_comment_prefixes.is_empty() {
 8800                    let first_prefix = full_comment_prefixes
 8801                        .first()
 8802                        .expect("prefixes is non-empty");
 8803                    let prefix_trimmed_lengths = full_comment_prefixes
 8804                        .iter()
 8805                        .map(|p| p.trim_end_matches(' ').len())
 8806                        .collect::<SmallVec<[usize; 4]>>();
 8807
 8808                    let mut all_selection_lines_are_comments = true;
 8809
 8810                    for row in start_row.0..=end_row.0 {
 8811                        let row = MultiBufferRow(row);
 8812                        if start_row < end_row && snapshot.is_line_blank(row) {
 8813                            continue;
 8814                        }
 8815
 8816                        let prefix_range = full_comment_prefixes
 8817                            .iter()
 8818                            .zip(prefix_trimmed_lengths.iter().copied())
 8819                            .map(|(prefix, trimmed_prefix_len)| {
 8820                                comment_prefix_range(
 8821                                    snapshot.deref(),
 8822                                    row,
 8823                                    &prefix[..trimmed_prefix_len],
 8824                                    &prefix[trimmed_prefix_len..],
 8825                                )
 8826                            })
 8827                            .max_by_key(|range| range.end.column - range.start.column)
 8828                            .expect("prefixes is non-empty");
 8829
 8830                        if prefix_range.is_empty() {
 8831                            all_selection_lines_are_comments = false;
 8832                        }
 8833
 8834                        selection_edit_ranges.push(prefix_range);
 8835                    }
 8836
 8837                    if all_selection_lines_are_comments {
 8838                        edits.extend(
 8839                            selection_edit_ranges
 8840                                .iter()
 8841                                .cloned()
 8842                                .map(|range| (range, empty_str.clone())),
 8843                        );
 8844                    } else {
 8845                        let min_column = selection_edit_ranges
 8846                            .iter()
 8847                            .map(|range| range.start.column)
 8848                            .min()
 8849                            .unwrap_or(0);
 8850                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8851                            let position = Point::new(range.start.row, min_column);
 8852                            (position..position, first_prefix.clone())
 8853                        }));
 8854                    }
 8855                } else if let Some((full_comment_prefix, comment_suffix)) =
 8856                    language.block_comment_delimiters()
 8857                {
 8858                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8859                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8860                    let prefix_range = comment_prefix_range(
 8861                        snapshot.deref(),
 8862                        start_row,
 8863                        comment_prefix,
 8864                        comment_prefix_whitespace,
 8865                    );
 8866                    let suffix_range = comment_suffix_range(
 8867                        snapshot.deref(),
 8868                        end_row,
 8869                        comment_suffix.trim_start_matches(' '),
 8870                        comment_suffix.starts_with(' '),
 8871                    );
 8872
 8873                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8874                        edits.push((
 8875                            prefix_range.start..prefix_range.start,
 8876                            full_comment_prefix.clone(),
 8877                        ));
 8878                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8879                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8880                    } else {
 8881                        edits.push((prefix_range, empty_str.clone()));
 8882                        edits.push((suffix_range, empty_str.clone()));
 8883                    }
 8884                } else {
 8885                    continue;
 8886                }
 8887            }
 8888
 8889            drop(snapshot);
 8890            this.buffer.update(cx, |buffer, cx| {
 8891                buffer.edit(edits, None, cx);
 8892            });
 8893
 8894            // Adjust selections so that they end before any comment suffixes that
 8895            // were inserted.
 8896            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8897            let mut selections = this.selections.all::<Point>(cx);
 8898            let snapshot = this.buffer.read(cx).read(cx);
 8899            for selection in &mut selections {
 8900                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8901                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8902                        Ordering::Less => {
 8903                            suffixes_inserted.next();
 8904                            continue;
 8905                        }
 8906                        Ordering::Greater => break,
 8907                        Ordering::Equal => {
 8908                            if selection.end.column == snapshot.line_len(row) {
 8909                                if selection.is_empty() {
 8910                                    selection.start.column -= suffix_len as u32;
 8911                                }
 8912                                selection.end.column -= suffix_len as u32;
 8913                            }
 8914                            break;
 8915                        }
 8916                    }
 8917                }
 8918            }
 8919
 8920            drop(snapshot);
 8921            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8922
 8923            let selections = this.selections.all::<Point>(cx);
 8924            let selections_on_single_row = selections.windows(2).all(|selections| {
 8925                selections[0].start.row == selections[1].start.row
 8926                    && selections[0].end.row == selections[1].end.row
 8927                    && selections[0].start.row == selections[0].end.row
 8928            });
 8929            let selections_selecting = selections
 8930                .iter()
 8931                .any(|selection| selection.start != selection.end);
 8932            let advance_downwards = action.advance_downwards
 8933                && selections_on_single_row
 8934                && !selections_selecting
 8935                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8936
 8937            if advance_downwards {
 8938                let snapshot = this.buffer.read(cx).snapshot(cx);
 8939
 8940                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8941                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8942                        let mut point = display_point.to_point(display_snapshot);
 8943                        point.row += 1;
 8944                        point = snapshot.clip_point(point, Bias::Left);
 8945                        let display_point = point.to_display_point(display_snapshot);
 8946                        let goal = SelectionGoal::HorizontalPosition(
 8947                            display_snapshot
 8948                                .x_for_display_point(display_point, text_layout_details)
 8949                                .into(),
 8950                        );
 8951                        (display_point, goal)
 8952                    })
 8953                });
 8954            }
 8955        });
 8956    }
 8957
 8958    pub fn select_enclosing_symbol(
 8959        &mut self,
 8960        _: &SelectEnclosingSymbol,
 8961        cx: &mut ViewContext<Self>,
 8962    ) {
 8963        let buffer = self.buffer.read(cx).snapshot(cx);
 8964        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8965
 8966        fn update_selection(
 8967            selection: &Selection<usize>,
 8968            buffer_snap: &MultiBufferSnapshot,
 8969        ) -> Option<Selection<usize>> {
 8970            let cursor = selection.head();
 8971            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8972            for symbol in symbols.iter().rev() {
 8973                let start = symbol.range.start.to_offset(buffer_snap);
 8974                let end = symbol.range.end.to_offset(buffer_snap);
 8975                let new_range = start..end;
 8976                if start < selection.start || end > selection.end {
 8977                    return Some(Selection {
 8978                        id: selection.id,
 8979                        start: new_range.start,
 8980                        end: new_range.end,
 8981                        goal: SelectionGoal::None,
 8982                        reversed: selection.reversed,
 8983                    });
 8984                }
 8985            }
 8986            None
 8987        }
 8988
 8989        let mut selected_larger_symbol = false;
 8990        let new_selections = old_selections
 8991            .iter()
 8992            .map(|selection| match update_selection(selection, &buffer) {
 8993                Some(new_selection) => {
 8994                    if new_selection.range() != selection.range() {
 8995                        selected_larger_symbol = true;
 8996                    }
 8997                    new_selection
 8998                }
 8999                None => selection.clone(),
 9000            })
 9001            .collect::<Vec<_>>();
 9002
 9003        if selected_larger_symbol {
 9004            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9005                s.select(new_selections);
 9006            });
 9007        }
 9008    }
 9009
 9010    pub fn select_larger_syntax_node(
 9011        &mut self,
 9012        _: &SelectLargerSyntaxNode,
 9013        cx: &mut ViewContext<Self>,
 9014    ) {
 9015        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9016        let buffer = self.buffer.read(cx).snapshot(cx);
 9017        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9018
 9019        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9020        let mut selected_larger_node = false;
 9021        let new_selections = old_selections
 9022            .iter()
 9023            .map(|selection| {
 9024                let old_range = selection.start..selection.end;
 9025                let mut new_range = old_range.clone();
 9026                while let Some(containing_range) =
 9027                    buffer.range_for_syntax_ancestor(new_range.clone())
 9028                {
 9029                    new_range = containing_range;
 9030                    if !display_map.intersects_fold(new_range.start)
 9031                        && !display_map.intersects_fold(new_range.end)
 9032                    {
 9033                        break;
 9034                    }
 9035                }
 9036
 9037                selected_larger_node |= new_range != old_range;
 9038                Selection {
 9039                    id: selection.id,
 9040                    start: new_range.start,
 9041                    end: new_range.end,
 9042                    goal: SelectionGoal::None,
 9043                    reversed: selection.reversed,
 9044                }
 9045            })
 9046            .collect::<Vec<_>>();
 9047
 9048        if selected_larger_node {
 9049            stack.push(old_selections);
 9050            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9051                s.select(new_selections);
 9052            });
 9053        }
 9054        self.select_larger_syntax_node_stack = stack;
 9055    }
 9056
 9057    pub fn select_smaller_syntax_node(
 9058        &mut self,
 9059        _: &SelectSmallerSyntaxNode,
 9060        cx: &mut ViewContext<Self>,
 9061    ) {
 9062        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9063        if let Some(selections) = stack.pop() {
 9064            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9065                s.select(selections.to_vec());
 9066            });
 9067        }
 9068        self.select_larger_syntax_node_stack = stack;
 9069    }
 9070
 9071    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9072        if !EditorSettings::get_global(cx).gutter.runnables {
 9073            self.clear_tasks();
 9074            return Task::ready(());
 9075        }
 9076        let project = self.project.clone();
 9077        cx.spawn(|this, mut cx| async move {
 9078            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9079                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9080            }) else {
 9081                return;
 9082            };
 9083
 9084            let Some(project) = project else {
 9085                return;
 9086            };
 9087
 9088            let hide_runnables = project
 9089                .update(&mut cx, |project, cx| {
 9090                    // Do not display any test indicators in non-dev server remote projects.
 9091                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9092                })
 9093                .unwrap_or(true);
 9094            if hide_runnables {
 9095                return;
 9096            }
 9097            let new_rows =
 9098                cx.background_executor()
 9099                    .spawn({
 9100                        let snapshot = display_snapshot.clone();
 9101                        async move {
 9102                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9103                        }
 9104                    })
 9105                    .await;
 9106            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9107
 9108            this.update(&mut cx, |this, _| {
 9109                this.clear_tasks();
 9110                for (key, value) in rows {
 9111                    this.insert_tasks(key, value);
 9112                }
 9113            })
 9114            .ok();
 9115        })
 9116    }
 9117    fn fetch_runnable_ranges(
 9118        snapshot: &DisplaySnapshot,
 9119        range: Range<Anchor>,
 9120    ) -> Vec<language::RunnableRange> {
 9121        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9122    }
 9123
 9124    fn runnable_rows(
 9125        project: Model<Project>,
 9126        snapshot: DisplaySnapshot,
 9127        runnable_ranges: Vec<RunnableRange>,
 9128        mut cx: AsyncWindowContext,
 9129    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9130        runnable_ranges
 9131            .into_iter()
 9132            .filter_map(|mut runnable| {
 9133                let tasks = cx
 9134                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9135                    .ok()?;
 9136                if tasks.is_empty() {
 9137                    return None;
 9138                }
 9139
 9140                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9141
 9142                let row = snapshot
 9143                    .buffer_snapshot
 9144                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9145                    .1
 9146                    .start
 9147                    .row;
 9148
 9149                let context_range =
 9150                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9151                Some((
 9152                    (runnable.buffer_id, row),
 9153                    RunnableTasks {
 9154                        templates: tasks,
 9155                        offset: MultiBufferOffset(runnable.run_range.start),
 9156                        context_range,
 9157                        column: point.column,
 9158                        extra_variables: runnable.extra_captures,
 9159                    },
 9160                ))
 9161            })
 9162            .collect()
 9163    }
 9164
 9165    fn templates_with_tags(
 9166        project: &Model<Project>,
 9167        runnable: &mut Runnable,
 9168        cx: &WindowContext<'_>,
 9169    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9170        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9171            let (worktree_id, file) = project
 9172                .buffer_for_id(runnable.buffer, cx)
 9173                .and_then(|buffer| buffer.read(cx).file())
 9174                .map(|file| (file.worktree_id(cx), file.clone()))
 9175                .unzip();
 9176
 9177            (
 9178                project.task_store().read(cx).task_inventory().cloned(),
 9179                worktree_id,
 9180                file,
 9181            )
 9182        });
 9183
 9184        let tags = mem::take(&mut runnable.tags);
 9185        let mut tags: Vec<_> = tags
 9186            .into_iter()
 9187            .flat_map(|tag| {
 9188                let tag = tag.0.clone();
 9189                inventory
 9190                    .as_ref()
 9191                    .into_iter()
 9192                    .flat_map(|inventory| {
 9193                        inventory.read(cx).list_tasks(
 9194                            file.clone(),
 9195                            Some(runnable.language.clone()),
 9196                            worktree_id,
 9197                            cx,
 9198                        )
 9199                    })
 9200                    .filter(move |(_, template)| {
 9201                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9202                    })
 9203            })
 9204            .sorted_by_key(|(kind, _)| kind.to_owned())
 9205            .collect();
 9206        if let Some((leading_tag_source, _)) = tags.first() {
 9207            // Strongest source wins; if we have worktree tag binding, prefer that to
 9208            // global and language bindings;
 9209            // if we have a global binding, prefer that to language binding.
 9210            let first_mismatch = tags
 9211                .iter()
 9212                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9213            if let Some(index) = first_mismatch {
 9214                tags.truncate(index);
 9215            }
 9216        }
 9217
 9218        tags
 9219    }
 9220
 9221    pub fn move_to_enclosing_bracket(
 9222        &mut self,
 9223        _: &MoveToEnclosingBracket,
 9224        cx: &mut ViewContext<Self>,
 9225    ) {
 9226        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9227            s.move_offsets_with(|snapshot, selection| {
 9228                let Some(enclosing_bracket_ranges) =
 9229                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9230                else {
 9231                    return;
 9232                };
 9233
 9234                let mut best_length = usize::MAX;
 9235                let mut best_inside = false;
 9236                let mut best_in_bracket_range = false;
 9237                let mut best_destination = None;
 9238                for (open, close) in enclosing_bracket_ranges {
 9239                    let close = close.to_inclusive();
 9240                    let length = close.end() - open.start;
 9241                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9242                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9243                        || close.contains(&selection.head());
 9244
 9245                    // If best is next to a bracket and current isn't, skip
 9246                    if !in_bracket_range && best_in_bracket_range {
 9247                        continue;
 9248                    }
 9249
 9250                    // Prefer smaller lengths unless best is inside and current isn't
 9251                    if length > best_length && (best_inside || !inside) {
 9252                        continue;
 9253                    }
 9254
 9255                    best_length = length;
 9256                    best_inside = inside;
 9257                    best_in_bracket_range = in_bracket_range;
 9258                    best_destination = Some(
 9259                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9260                            if inside {
 9261                                open.end
 9262                            } else {
 9263                                open.start
 9264                            }
 9265                        } else if inside {
 9266                            *close.start()
 9267                        } else {
 9268                            *close.end()
 9269                        },
 9270                    );
 9271                }
 9272
 9273                if let Some(destination) = best_destination {
 9274                    selection.collapse_to(destination, SelectionGoal::None);
 9275                }
 9276            })
 9277        });
 9278    }
 9279
 9280    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9281        self.end_selection(cx);
 9282        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9283        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9284            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9285            self.select_next_state = entry.select_next_state;
 9286            self.select_prev_state = entry.select_prev_state;
 9287            self.add_selections_state = entry.add_selections_state;
 9288            self.request_autoscroll(Autoscroll::newest(), cx);
 9289        }
 9290        self.selection_history.mode = SelectionHistoryMode::Normal;
 9291    }
 9292
 9293    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9294        self.end_selection(cx);
 9295        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9296        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9297            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9298            self.select_next_state = entry.select_next_state;
 9299            self.select_prev_state = entry.select_prev_state;
 9300            self.add_selections_state = entry.add_selections_state;
 9301            self.request_autoscroll(Autoscroll::newest(), cx);
 9302        }
 9303        self.selection_history.mode = SelectionHistoryMode::Normal;
 9304    }
 9305
 9306    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9307        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9308    }
 9309
 9310    pub fn expand_excerpts_down(
 9311        &mut self,
 9312        action: &ExpandExcerptsDown,
 9313        cx: &mut ViewContext<Self>,
 9314    ) {
 9315        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9316    }
 9317
 9318    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9319        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9320    }
 9321
 9322    pub fn expand_excerpts_for_direction(
 9323        &mut self,
 9324        lines: u32,
 9325        direction: ExpandExcerptDirection,
 9326        cx: &mut ViewContext<Self>,
 9327    ) {
 9328        let selections = self.selections.disjoint_anchors();
 9329
 9330        let lines = if lines == 0 {
 9331            EditorSettings::get_global(cx).expand_excerpt_lines
 9332        } else {
 9333            lines
 9334        };
 9335
 9336        self.buffer.update(cx, |buffer, cx| {
 9337            buffer.expand_excerpts(
 9338                selections
 9339                    .iter()
 9340                    .map(|selection| selection.head().excerpt_id)
 9341                    .dedup(),
 9342                lines,
 9343                direction,
 9344                cx,
 9345            )
 9346        })
 9347    }
 9348
 9349    pub fn expand_excerpt(
 9350        &mut self,
 9351        excerpt: ExcerptId,
 9352        direction: ExpandExcerptDirection,
 9353        cx: &mut ViewContext<Self>,
 9354    ) {
 9355        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9356        self.buffer.update(cx, |buffer, cx| {
 9357            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9358        })
 9359    }
 9360
 9361    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9362        self.go_to_diagnostic_impl(Direction::Next, cx)
 9363    }
 9364
 9365    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9366        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9367    }
 9368
 9369    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9370        let buffer = self.buffer.read(cx).snapshot(cx);
 9371        let selection = self.selections.newest::<usize>(cx);
 9372
 9373        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9374        if direction == Direction::Next {
 9375            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9376                let (group_id, jump_to) = popover.activation_info();
 9377                if self.activate_diagnostics(group_id, cx) {
 9378                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9379                        let mut new_selection = s.newest_anchor().clone();
 9380                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9381                        s.select_anchors(vec![new_selection.clone()]);
 9382                    });
 9383                }
 9384                return;
 9385            }
 9386        }
 9387
 9388        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9389            active_diagnostics
 9390                .primary_range
 9391                .to_offset(&buffer)
 9392                .to_inclusive()
 9393        });
 9394        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9395            if active_primary_range.contains(&selection.head()) {
 9396                *active_primary_range.start()
 9397            } else {
 9398                selection.head()
 9399            }
 9400        } else {
 9401            selection.head()
 9402        };
 9403        let snapshot = self.snapshot(cx);
 9404        loop {
 9405            let diagnostics = if direction == Direction::Prev {
 9406                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9407            } else {
 9408                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9409            }
 9410            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9411            let group = diagnostics
 9412                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9413                // be sorted in a stable way
 9414                // skip until we are at current active diagnostic, if it exists
 9415                .skip_while(|entry| {
 9416                    (match direction {
 9417                        Direction::Prev => entry.range.start >= search_start,
 9418                        Direction::Next => entry.range.start <= search_start,
 9419                    }) && self
 9420                        .active_diagnostics
 9421                        .as_ref()
 9422                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9423                })
 9424                .find_map(|entry| {
 9425                    if entry.diagnostic.is_primary
 9426                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9427                        && !entry.range.is_empty()
 9428                        // if we match with the active diagnostic, skip it
 9429                        && Some(entry.diagnostic.group_id)
 9430                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9431                    {
 9432                        Some((entry.range, entry.diagnostic.group_id))
 9433                    } else {
 9434                        None
 9435                    }
 9436                });
 9437
 9438            if let Some((primary_range, group_id)) = group {
 9439                if self.activate_diagnostics(group_id, cx) {
 9440                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9441                        s.select(vec![Selection {
 9442                            id: selection.id,
 9443                            start: primary_range.start,
 9444                            end: primary_range.start,
 9445                            reversed: false,
 9446                            goal: SelectionGoal::None,
 9447                        }]);
 9448                    });
 9449                }
 9450                break;
 9451            } else {
 9452                // Cycle around to the start of the buffer, potentially moving back to the start of
 9453                // the currently active diagnostic.
 9454                active_primary_range.take();
 9455                if direction == Direction::Prev {
 9456                    if search_start == buffer.len() {
 9457                        break;
 9458                    } else {
 9459                        search_start = buffer.len();
 9460                    }
 9461                } else if search_start == 0 {
 9462                    break;
 9463                } else {
 9464                    search_start = 0;
 9465                }
 9466            }
 9467        }
 9468    }
 9469
 9470    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9471        let snapshot = self
 9472            .display_map
 9473            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9474        let selection = self.selections.newest::<Point>(cx);
 9475        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9476    }
 9477
 9478    fn go_to_hunk_after_position(
 9479        &mut self,
 9480        snapshot: &DisplaySnapshot,
 9481        position: Point,
 9482        cx: &mut ViewContext<'_, Editor>,
 9483    ) -> Option<MultiBufferDiffHunk> {
 9484        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9485            snapshot,
 9486            position,
 9487            false,
 9488            snapshot
 9489                .buffer_snapshot
 9490                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9491            cx,
 9492        ) {
 9493            return Some(hunk);
 9494        }
 9495
 9496        let wrapped_point = Point::zero();
 9497        self.go_to_next_hunk_in_direction(
 9498            snapshot,
 9499            wrapped_point,
 9500            true,
 9501            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9502                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9503            ),
 9504            cx,
 9505        )
 9506    }
 9507
 9508    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9509        let snapshot = self
 9510            .display_map
 9511            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9512        let selection = self.selections.newest::<Point>(cx);
 9513
 9514        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9515    }
 9516
 9517    fn go_to_hunk_before_position(
 9518        &mut self,
 9519        snapshot: &DisplaySnapshot,
 9520        position: Point,
 9521        cx: &mut ViewContext<'_, Editor>,
 9522    ) -> Option<MultiBufferDiffHunk> {
 9523        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9524            snapshot,
 9525            position,
 9526            false,
 9527            snapshot
 9528                .buffer_snapshot
 9529                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9530            cx,
 9531        ) {
 9532            return Some(hunk);
 9533        }
 9534
 9535        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9536        self.go_to_next_hunk_in_direction(
 9537            snapshot,
 9538            wrapped_point,
 9539            true,
 9540            snapshot
 9541                .buffer_snapshot
 9542                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9543            cx,
 9544        )
 9545    }
 9546
 9547    fn go_to_next_hunk_in_direction(
 9548        &mut self,
 9549        snapshot: &DisplaySnapshot,
 9550        initial_point: Point,
 9551        is_wrapped: bool,
 9552        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9553        cx: &mut ViewContext<Editor>,
 9554    ) -> Option<MultiBufferDiffHunk> {
 9555        let display_point = initial_point.to_display_point(snapshot);
 9556        let mut hunks = hunks
 9557            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9558            .filter(|(display_hunk, _)| {
 9559                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9560            })
 9561            .dedup();
 9562
 9563        if let Some((display_hunk, hunk)) = hunks.next() {
 9564            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9565                let row = display_hunk.start_display_row();
 9566                let point = DisplayPoint::new(row, 0);
 9567                s.select_display_ranges([point..point]);
 9568            });
 9569
 9570            Some(hunk)
 9571        } else {
 9572            None
 9573        }
 9574    }
 9575
 9576    pub fn go_to_definition(
 9577        &mut self,
 9578        _: &GoToDefinition,
 9579        cx: &mut ViewContext<Self>,
 9580    ) -> Task<Result<Navigated>> {
 9581        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9582        cx.spawn(|editor, mut cx| async move {
 9583            if definition.await? == Navigated::Yes {
 9584                return Ok(Navigated::Yes);
 9585            }
 9586            match editor.update(&mut cx, |editor, cx| {
 9587                editor.find_all_references(&FindAllReferences, cx)
 9588            })? {
 9589                Some(references) => references.await,
 9590                None => Ok(Navigated::No),
 9591            }
 9592        })
 9593    }
 9594
 9595    pub fn go_to_declaration(
 9596        &mut self,
 9597        _: &GoToDeclaration,
 9598        cx: &mut ViewContext<Self>,
 9599    ) -> Task<Result<Navigated>> {
 9600        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9601    }
 9602
 9603    pub fn go_to_declaration_split(
 9604        &mut self,
 9605        _: &GoToDeclaration,
 9606        cx: &mut ViewContext<Self>,
 9607    ) -> Task<Result<Navigated>> {
 9608        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9609    }
 9610
 9611    pub fn go_to_implementation(
 9612        &mut self,
 9613        _: &GoToImplementation,
 9614        cx: &mut ViewContext<Self>,
 9615    ) -> Task<Result<Navigated>> {
 9616        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9617    }
 9618
 9619    pub fn go_to_implementation_split(
 9620        &mut self,
 9621        _: &GoToImplementationSplit,
 9622        cx: &mut ViewContext<Self>,
 9623    ) -> Task<Result<Navigated>> {
 9624        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9625    }
 9626
 9627    pub fn go_to_type_definition(
 9628        &mut self,
 9629        _: &GoToTypeDefinition,
 9630        cx: &mut ViewContext<Self>,
 9631    ) -> Task<Result<Navigated>> {
 9632        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9633    }
 9634
 9635    pub fn go_to_definition_split(
 9636        &mut self,
 9637        _: &GoToDefinitionSplit,
 9638        cx: &mut ViewContext<Self>,
 9639    ) -> Task<Result<Navigated>> {
 9640        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9641    }
 9642
 9643    pub fn go_to_type_definition_split(
 9644        &mut self,
 9645        _: &GoToTypeDefinitionSplit,
 9646        cx: &mut ViewContext<Self>,
 9647    ) -> Task<Result<Navigated>> {
 9648        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9649    }
 9650
 9651    fn go_to_definition_of_kind(
 9652        &mut self,
 9653        kind: GotoDefinitionKind,
 9654        split: bool,
 9655        cx: &mut ViewContext<Self>,
 9656    ) -> Task<Result<Navigated>> {
 9657        let Some(provider) = self.semantics_provider.clone() else {
 9658            return Task::ready(Ok(Navigated::No));
 9659        };
 9660        let buffer = self.buffer.read(cx);
 9661        let head = self.selections.newest::<usize>(cx).head();
 9662        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9663            text_anchor
 9664        } else {
 9665            return Task::ready(Ok(Navigated::No));
 9666        };
 9667
 9668        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9669            return Task::ready(Ok(Navigated::No));
 9670        };
 9671
 9672        cx.spawn(|editor, mut cx| async move {
 9673            let definitions = definitions.await?;
 9674            let navigated = editor
 9675                .update(&mut cx, |editor, cx| {
 9676                    editor.navigate_to_hover_links(
 9677                        Some(kind),
 9678                        definitions
 9679                            .into_iter()
 9680                            .filter(|location| {
 9681                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9682                            })
 9683                            .map(HoverLink::Text)
 9684                            .collect::<Vec<_>>(),
 9685                        split,
 9686                        cx,
 9687                    )
 9688                })?
 9689                .await?;
 9690            anyhow::Ok(navigated)
 9691        })
 9692    }
 9693
 9694    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9695        let position = self.selections.newest_anchor().head();
 9696        let Some((buffer, buffer_position)) =
 9697            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9698        else {
 9699            return;
 9700        };
 9701
 9702        cx.spawn(|editor, mut cx| async move {
 9703            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9704                editor.update(&mut cx, |_, cx| {
 9705                    cx.open_url(&url);
 9706                })
 9707            } else {
 9708                Ok(())
 9709            }
 9710        })
 9711        .detach();
 9712    }
 9713
 9714    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9715        let Some(workspace) = self.workspace() else {
 9716            return;
 9717        };
 9718
 9719        let position = self.selections.newest_anchor().head();
 9720
 9721        let Some((buffer, buffer_position)) =
 9722            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9723        else {
 9724            return;
 9725        };
 9726
 9727        let project = self.project.clone();
 9728
 9729        cx.spawn(|_, mut cx| async move {
 9730            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9731
 9732            if let Some((_, path)) = result {
 9733                workspace
 9734                    .update(&mut cx, |workspace, cx| {
 9735                        workspace.open_resolved_path(path, cx)
 9736                    })?
 9737                    .await?;
 9738            }
 9739            anyhow::Ok(())
 9740        })
 9741        .detach();
 9742    }
 9743
 9744    pub(crate) fn navigate_to_hover_links(
 9745        &mut self,
 9746        kind: Option<GotoDefinitionKind>,
 9747        mut definitions: Vec<HoverLink>,
 9748        split: bool,
 9749        cx: &mut ViewContext<Editor>,
 9750    ) -> Task<Result<Navigated>> {
 9751        // If there is one definition, just open it directly
 9752        if definitions.len() == 1 {
 9753            let definition = definitions.pop().unwrap();
 9754
 9755            enum TargetTaskResult {
 9756                Location(Option<Location>),
 9757                AlreadyNavigated,
 9758            }
 9759
 9760            let target_task = match definition {
 9761                HoverLink::Text(link) => {
 9762                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9763                }
 9764                HoverLink::InlayHint(lsp_location, server_id) => {
 9765                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9766                    cx.background_executor().spawn(async move {
 9767                        let location = computation.await?;
 9768                        Ok(TargetTaskResult::Location(location))
 9769                    })
 9770                }
 9771                HoverLink::Url(url) => {
 9772                    cx.open_url(&url);
 9773                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9774                }
 9775                HoverLink::File(path) => {
 9776                    if let Some(workspace) = self.workspace() {
 9777                        cx.spawn(|_, mut cx| async move {
 9778                            workspace
 9779                                .update(&mut cx, |workspace, cx| {
 9780                                    workspace.open_resolved_path(path, cx)
 9781                                })?
 9782                                .await
 9783                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9784                        })
 9785                    } else {
 9786                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9787                    }
 9788                }
 9789            };
 9790            cx.spawn(|editor, mut cx| async move {
 9791                let target = match target_task.await.context("target resolution task")? {
 9792                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9793                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9794                    TargetTaskResult::Location(Some(target)) => target,
 9795                };
 9796
 9797                editor.update(&mut cx, |editor, cx| {
 9798                    let Some(workspace) = editor.workspace() else {
 9799                        return Navigated::No;
 9800                    };
 9801                    let pane = workspace.read(cx).active_pane().clone();
 9802
 9803                    let range = target.range.to_offset(target.buffer.read(cx));
 9804                    let range = editor.range_for_match(&range);
 9805
 9806                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9807                        let buffer = target.buffer.read(cx);
 9808                        let range = check_multiline_range(buffer, range);
 9809                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9810                            s.select_ranges([range]);
 9811                        });
 9812                    } else {
 9813                        cx.window_context().defer(move |cx| {
 9814                            let target_editor: View<Self> =
 9815                                workspace.update(cx, |workspace, cx| {
 9816                                    let pane = if split {
 9817                                        workspace.adjacent_pane(cx)
 9818                                    } else {
 9819                                        workspace.active_pane().clone()
 9820                                    };
 9821
 9822                                    workspace.open_project_item(
 9823                                        pane,
 9824                                        target.buffer.clone(),
 9825                                        true,
 9826                                        true,
 9827                                        cx,
 9828                                    )
 9829                                });
 9830                            target_editor.update(cx, |target_editor, cx| {
 9831                                // When selecting a definition in a different buffer, disable the nav history
 9832                                // to avoid creating a history entry at the previous cursor location.
 9833                                pane.update(cx, |pane, _| pane.disable_history());
 9834                                let buffer = target.buffer.read(cx);
 9835                                let range = check_multiline_range(buffer, range);
 9836                                target_editor.change_selections(
 9837                                    Some(Autoscroll::focused()),
 9838                                    cx,
 9839                                    |s| {
 9840                                        s.select_ranges([range]);
 9841                                    },
 9842                                );
 9843                                pane.update(cx, |pane, _| pane.enable_history());
 9844                            });
 9845                        });
 9846                    }
 9847                    Navigated::Yes
 9848                })
 9849            })
 9850        } else if !definitions.is_empty() {
 9851            cx.spawn(|editor, mut cx| async move {
 9852                let (title, location_tasks, workspace) = editor
 9853                    .update(&mut cx, |editor, cx| {
 9854                        let tab_kind = match kind {
 9855                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9856                            _ => "Definitions",
 9857                        };
 9858                        let title = definitions
 9859                            .iter()
 9860                            .find_map(|definition| match definition {
 9861                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9862                                    let buffer = origin.buffer.read(cx);
 9863                                    format!(
 9864                                        "{} for {}",
 9865                                        tab_kind,
 9866                                        buffer
 9867                                            .text_for_range(origin.range.clone())
 9868                                            .collect::<String>()
 9869                                    )
 9870                                }),
 9871                                HoverLink::InlayHint(_, _) => None,
 9872                                HoverLink::Url(_) => None,
 9873                                HoverLink::File(_) => None,
 9874                            })
 9875                            .unwrap_or(tab_kind.to_string());
 9876                        let location_tasks = definitions
 9877                            .into_iter()
 9878                            .map(|definition| match definition {
 9879                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9880                                HoverLink::InlayHint(lsp_location, server_id) => {
 9881                                    editor.compute_target_location(lsp_location, server_id, cx)
 9882                                }
 9883                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9884                                HoverLink::File(_) => Task::ready(Ok(None)),
 9885                            })
 9886                            .collect::<Vec<_>>();
 9887                        (title, location_tasks, editor.workspace().clone())
 9888                    })
 9889                    .context("location tasks preparation")?;
 9890
 9891                let locations = future::join_all(location_tasks)
 9892                    .await
 9893                    .into_iter()
 9894                    .filter_map(|location| location.transpose())
 9895                    .collect::<Result<_>>()
 9896                    .context("location tasks")?;
 9897
 9898                let Some(workspace) = workspace else {
 9899                    return Ok(Navigated::No);
 9900                };
 9901                let opened = workspace
 9902                    .update(&mut cx, |workspace, cx| {
 9903                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9904                    })
 9905                    .ok();
 9906
 9907                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9908            })
 9909        } else {
 9910            Task::ready(Ok(Navigated::No))
 9911        }
 9912    }
 9913
 9914    fn compute_target_location(
 9915        &self,
 9916        lsp_location: lsp::Location,
 9917        server_id: LanguageServerId,
 9918        cx: &mut ViewContext<Editor>,
 9919    ) -> Task<anyhow::Result<Option<Location>>> {
 9920        let Some(project) = self.project.clone() else {
 9921            return Task::Ready(Some(Ok(None)));
 9922        };
 9923
 9924        cx.spawn(move |editor, mut cx| async move {
 9925            let location_task = editor.update(&mut cx, |editor, cx| {
 9926                project.update(cx, |project, cx| {
 9927                    let language_server_name =
 9928                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9929                            project
 9930                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9931                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9932                        });
 9933                    language_server_name.map(|language_server_name| {
 9934                        project.open_local_buffer_via_lsp(
 9935                            lsp_location.uri.clone(),
 9936                            server_id,
 9937                            language_server_name,
 9938                            cx,
 9939                        )
 9940                    })
 9941                })
 9942            })?;
 9943            let location = match location_task {
 9944                Some(task) => Some({
 9945                    let target_buffer_handle = task.await.context("open local buffer")?;
 9946                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9947                        let target_start = target_buffer
 9948                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9949                        let target_end = target_buffer
 9950                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9951                        target_buffer.anchor_after(target_start)
 9952                            ..target_buffer.anchor_before(target_end)
 9953                    })?;
 9954                    Location {
 9955                        buffer: target_buffer_handle,
 9956                        range,
 9957                    }
 9958                }),
 9959                None => None,
 9960            };
 9961            Ok(location)
 9962        })
 9963    }
 9964
 9965    pub fn find_all_references(
 9966        &mut self,
 9967        _: &FindAllReferences,
 9968        cx: &mut ViewContext<Self>,
 9969    ) -> Option<Task<Result<Navigated>>> {
 9970        let multi_buffer = self.buffer.read(cx);
 9971        let selection = self.selections.newest::<usize>(cx);
 9972        let head = selection.head();
 9973
 9974        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9975        let head_anchor = multi_buffer_snapshot.anchor_at(
 9976            head,
 9977            if head < selection.tail() {
 9978                Bias::Right
 9979            } else {
 9980                Bias::Left
 9981            },
 9982        );
 9983
 9984        match self
 9985            .find_all_references_task_sources
 9986            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9987        {
 9988            Ok(_) => {
 9989                log::info!(
 9990                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9991                );
 9992                return None;
 9993            }
 9994            Err(i) => {
 9995                self.find_all_references_task_sources.insert(i, head_anchor);
 9996            }
 9997        }
 9998
 9999        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10000        let workspace = self.workspace()?;
10001        let project = workspace.read(cx).project().clone();
10002        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10003        Some(cx.spawn(|editor, mut cx| async move {
10004            let _cleanup = defer({
10005                let mut cx = cx.clone();
10006                move || {
10007                    let _ = editor.update(&mut cx, |editor, _| {
10008                        if let Ok(i) =
10009                            editor
10010                                .find_all_references_task_sources
10011                                .binary_search_by(|anchor| {
10012                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10013                                })
10014                        {
10015                            editor.find_all_references_task_sources.remove(i);
10016                        }
10017                    });
10018                }
10019            });
10020
10021            let locations = references.await?;
10022            if locations.is_empty() {
10023                return anyhow::Ok(Navigated::No);
10024            }
10025
10026            workspace.update(&mut cx, |workspace, cx| {
10027                let title = locations
10028                    .first()
10029                    .as_ref()
10030                    .map(|location| {
10031                        let buffer = location.buffer.read(cx);
10032                        format!(
10033                            "References to `{}`",
10034                            buffer
10035                                .text_for_range(location.range.clone())
10036                                .collect::<String>()
10037                        )
10038                    })
10039                    .unwrap();
10040                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10041                Navigated::Yes
10042            })
10043        }))
10044    }
10045
10046    /// Opens a multibuffer with the given project locations in it
10047    pub fn open_locations_in_multibuffer(
10048        workspace: &mut Workspace,
10049        mut locations: Vec<Location>,
10050        title: String,
10051        split: bool,
10052        cx: &mut ViewContext<Workspace>,
10053    ) {
10054        // If there are multiple definitions, open them in a multibuffer
10055        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10056        let mut locations = locations.into_iter().peekable();
10057        let mut ranges_to_highlight = Vec::new();
10058        let capability = workspace.project().read(cx).capability();
10059
10060        let excerpt_buffer = cx.new_model(|cx| {
10061            let mut multibuffer = MultiBuffer::new(capability);
10062            while let Some(location) = locations.next() {
10063                let buffer = location.buffer.read(cx);
10064                let mut ranges_for_buffer = Vec::new();
10065                let range = location.range.to_offset(buffer);
10066                ranges_for_buffer.push(range.clone());
10067
10068                while let Some(next_location) = locations.peek() {
10069                    if next_location.buffer == location.buffer {
10070                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10071                        locations.next();
10072                    } else {
10073                        break;
10074                    }
10075                }
10076
10077                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10078                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10079                    location.buffer.clone(),
10080                    ranges_for_buffer,
10081                    DEFAULT_MULTIBUFFER_CONTEXT,
10082                    cx,
10083                ))
10084            }
10085
10086            multibuffer.with_title(title)
10087        });
10088
10089        let editor = cx.new_view(|cx| {
10090            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10091        });
10092        editor.update(cx, |editor, cx| {
10093            if let Some(first_range) = ranges_to_highlight.first() {
10094                editor.change_selections(None, cx, |selections| {
10095                    selections.clear_disjoint();
10096                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10097                });
10098            }
10099            editor.highlight_background::<Self>(
10100                &ranges_to_highlight,
10101                |theme| theme.editor_highlighted_line_background,
10102                cx,
10103            );
10104        });
10105
10106        let item = Box::new(editor);
10107        let item_id = item.item_id();
10108
10109        if split {
10110            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10111        } else {
10112            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10113                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10114                    pane.close_current_preview_item(cx)
10115                } else {
10116                    None
10117                }
10118            });
10119            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10120        }
10121        workspace.active_pane().update(cx, |pane, cx| {
10122            pane.set_preview_item_id(Some(item_id), cx);
10123        });
10124    }
10125
10126    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10127        use language::ToOffset as _;
10128
10129        let provider = self.semantics_provider.clone()?;
10130        let selection = self.selections.newest_anchor().clone();
10131        let (cursor_buffer, cursor_buffer_position) = self
10132            .buffer
10133            .read(cx)
10134            .text_anchor_for_position(selection.head(), cx)?;
10135        let (tail_buffer, cursor_buffer_position_end) = self
10136            .buffer
10137            .read(cx)
10138            .text_anchor_for_position(selection.tail(), cx)?;
10139        if tail_buffer != cursor_buffer {
10140            return None;
10141        }
10142
10143        let snapshot = cursor_buffer.read(cx).snapshot();
10144        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10145        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10146        let prepare_rename = provider
10147            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10148            .unwrap_or_else(|| Task::ready(Ok(None)));
10149        drop(snapshot);
10150
10151        Some(cx.spawn(|this, mut cx| async move {
10152            let rename_range = if let Some(range) = prepare_rename.await? {
10153                Some(range)
10154            } else {
10155                this.update(&mut cx, |this, cx| {
10156                    let buffer = this.buffer.read(cx).snapshot(cx);
10157                    let mut buffer_highlights = this
10158                        .document_highlights_for_position(selection.head(), &buffer)
10159                        .filter(|highlight| {
10160                            highlight.start.excerpt_id == selection.head().excerpt_id
10161                                && highlight.end.excerpt_id == selection.head().excerpt_id
10162                        });
10163                    buffer_highlights
10164                        .next()
10165                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10166                })?
10167            };
10168            if let Some(rename_range) = rename_range {
10169                this.update(&mut cx, |this, cx| {
10170                    let snapshot = cursor_buffer.read(cx).snapshot();
10171                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10172                    let cursor_offset_in_rename_range =
10173                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10174                    let cursor_offset_in_rename_range_end =
10175                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10176
10177                    this.take_rename(false, cx);
10178                    let buffer = this.buffer.read(cx).read(cx);
10179                    let cursor_offset = selection.head().to_offset(&buffer);
10180                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10181                    let rename_end = rename_start + rename_buffer_range.len();
10182                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10183                    let mut old_highlight_id = None;
10184                    let old_name: Arc<str> = buffer
10185                        .chunks(rename_start..rename_end, true)
10186                        .map(|chunk| {
10187                            if old_highlight_id.is_none() {
10188                                old_highlight_id = chunk.syntax_highlight_id;
10189                            }
10190                            chunk.text
10191                        })
10192                        .collect::<String>()
10193                        .into();
10194
10195                    drop(buffer);
10196
10197                    // Position the selection in the rename editor so that it matches the current selection.
10198                    this.show_local_selections = false;
10199                    let rename_editor = cx.new_view(|cx| {
10200                        let mut editor = Editor::single_line(cx);
10201                        editor.buffer.update(cx, |buffer, cx| {
10202                            buffer.edit([(0..0, old_name.clone())], None, cx)
10203                        });
10204                        let rename_selection_range = match cursor_offset_in_rename_range
10205                            .cmp(&cursor_offset_in_rename_range_end)
10206                        {
10207                            Ordering::Equal => {
10208                                editor.select_all(&SelectAll, cx);
10209                                return editor;
10210                            }
10211                            Ordering::Less => {
10212                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10213                            }
10214                            Ordering::Greater => {
10215                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10216                            }
10217                        };
10218                        if rename_selection_range.end > old_name.len() {
10219                            editor.select_all(&SelectAll, cx);
10220                        } else {
10221                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10222                                s.select_ranges([rename_selection_range]);
10223                            });
10224                        }
10225                        editor
10226                    });
10227                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10228                        if e == &EditorEvent::Focused {
10229                            cx.emit(EditorEvent::FocusedIn)
10230                        }
10231                    })
10232                    .detach();
10233
10234                    let write_highlights =
10235                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10236                    let read_highlights =
10237                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10238                    let ranges = write_highlights
10239                        .iter()
10240                        .flat_map(|(_, ranges)| ranges.iter())
10241                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10242                        .cloned()
10243                        .collect();
10244
10245                    this.highlight_text::<Rename>(
10246                        ranges,
10247                        HighlightStyle {
10248                            fade_out: Some(0.6),
10249                            ..Default::default()
10250                        },
10251                        cx,
10252                    );
10253                    let rename_focus_handle = rename_editor.focus_handle(cx);
10254                    cx.focus(&rename_focus_handle);
10255                    let block_id = this.insert_blocks(
10256                        [BlockProperties {
10257                            style: BlockStyle::Flex,
10258                            position: range.start,
10259                            height: 1,
10260                            render: Box::new({
10261                                let rename_editor = rename_editor.clone();
10262                                move |cx: &mut BlockContext| {
10263                                    let mut text_style = cx.editor_style.text.clone();
10264                                    if let Some(highlight_style) = old_highlight_id
10265                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10266                                    {
10267                                        text_style = text_style.highlight(highlight_style);
10268                                    }
10269                                    div()
10270                                        .pl(cx.anchor_x)
10271                                        .child(EditorElement::new(
10272                                            &rename_editor,
10273                                            EditorStyle {
10274                                                background: cx.theme().system().transparent,
10275                                                local_player: cx.editor_style.local_player,
10276                                                text: text_style,
10277                                                scrollbar_width: cx.editor_style.scrollbar_width,
10278                                                syntax: cx.editor_style.syntax.clone(),
10279                                                status: cx.editor_style.status.clone(),
10280                                                inlay_hints_style: HighlightStyle {
10281                                                    font_weight: Some(FontWeight::BOLD),
10282                                                    ..make_inlay_hints_style(cx)
10283                                                },
10284                                                suggestions_style: HighlightStyle {
10285                                                    color: Some(cx.theme().status().predictive),
10286                                                    ..HighlightStyle::default()
10287                                                },
10288                                                ..EditorStyle::default()
10289                                            },
10290                                        ))
10291                                        .into_any_element()
10292                                }
10293                            }),
10294                            disposition: BlockDisposition::Below,
10295                            priority: 0,
10296                        }],
10297                        Some(Autoscroll::fit()),
10298                        cx,
10299                    )[0];
10300                    this.pending_rename = Some(RenameState {
10301                        range,
10302                        old_name,
10303                        editor: rename_editor,
10304                        block_id,
10305                    });
10306                })?;
10307            }
10308
10309            Ok(())
10310        }))
10311    }
10312
10313    pub fn confirm_rename(
10314        &mut self,
10315        _: &ConfirmRename,
10316        cx: &mut ViewContext<Self>,
10317    ) -> Option<Task<Result<()>>> {
10318        let rename = self.take_rename(false, cx)?;
10319        let workspace = self.workspace()?.downgrade();
10320        let (buffer, start) = self
10321            .buffer
10322            .read(cx)
10323            .text_anchor_for_position(rename.range.start, cx)?;
10324        let (end_buffer, _) = self
10325            .buffer
10326            .read(cx)
10327            .text_anchor_for_position(rename.range.end, cx)?;
10328        if buffer != end_buffer {
10329            return None;
10330        }
10331
10332        let old_name = rename.old_name;
10333        let new_name = rename.editor.read(cx).text(cx);
10334
10335        let rename = self.semantics_provider.as_ref()?.perform_rename(
10336            &buffer,
10337            start,
10338            new_name.clone(),
10339            cx,
10340        )?;
10341
10342        Some(cx.spawn(|editor, mut cx| async move {
10343            let project_transaction = rename.await?;
10344            Self::open_project_transaction(
10345                &editor,
10346                workspace,
10347                project_transaction,
10348                format!("Rename: {}{}", old_name, new_name),
10349                cx.clone(),
10350            )
10351            .await?;
10352
10353            editor.update(&mut cx, |editor, cx| {
10354                editor.refresh_document_highlights(cx);
10355            })?;
10356            Ok(())
10357        }))
10358    }
10359
10360    fn take_rename(
10361        &mut self,
10362        moving_cursor: bool,
10363        cx: &mut ViewContext<Self>,
10364    ) -> Option<RenameState> {
10365        let rename = self.pending_rename.take()?;
10366        if rename.editor.focus_handle(cx).is_focused(cx) {
10367            cx.focus(&self.focus_handle);
10368        }
10369
10370        self.remove_blocks(
10371            [rename.block_id].into_iter().collect(),
10372            Some(Autoscroll::fit()),
10373            cx,
10374        );
10375        self.clear_highlights::<Rename>(cx);
10376        self.show_local_selections = true;
10377
10378        if moving_cursor {
10379            let rename_editor = rename.editor.read(cx);
10380            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10381
10382            // Update the selection to match the position of the selection inside
10383            // the rename editor.
10384            let snapshot = self.buffer.read(cx).read(cx);
10385            let rename_range = rename.range.to_offset(&snapshot);
10386            let cursor_in_editor = snapshot
10387                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10388                .min(rename_range.end);
10389            drop(snapshot);
10390
10391            self.change_selections(None, cx, |s| {
10392                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10393            });
10394        } else {
10395            self.refresh_document_highlights(cx);
10396        }
10397
10398        Some(rename)
10399    }
10400
10401    pub fn pending_rename(&self) -> Option<&RenameState> {
10402        self.pending_rename.as_ref()
10403    }
10404
10405    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10406        let project = match &self.project {
10407            Some(project) => project.clone(),
10408            None => return None,
10409        };
10410
10411        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10412    }
10413
10414    fn perform_format(
10415        &mut self,
10416        project: Model<Project>,
10417        trigger: FormatTrigger,
10418        cx: &mut ViewContext<Self>,
10419    ) -> Task<Result<()>> {
10420        let buffer = self.buffer().clone();
10421        let mut buffers = buffer.read(cx).all_buffers();
10422        if trigger == FormatTrigger::Save {
10423            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10424        }
10425
10426        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10427        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10428
10429        cx.spawn(|_, mut cx| async move {
10430            let transaction = futures::select_biased! {
10431                () = timeout => {
10432                    log::warn!("timed out waiting for formatting");
10433                    None
10434                }
10435                transaction = format.log_err().fuse() => transaction,
10436            };
10437
10438            buffer
10439                .update(&mut cx, |buffer, cx| {
10440                    if let Some(transaction) = transaction {
10441                        if !buffer.is_singleton() {
10442                            buffer.push_transaction(&transaction.0, cx);
10443                        }
10444                    }
10445
10446                    cx.notify();
10447                })
10448                .ok();
10449
10450            Ok(())
10451        })
10452    }
10453
10454    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10455        if let Some(project) = self.project.clone() {
10456            self.buffer.update(cx, |multi_buffer, cx| {
10457                project.update(cx, |project, cx| {
10458                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10459                });
10460            })
10461        }
10462    }
10463
10464    fn cancel_language_server_work(
10465        &mut self,
10466        _: &CancelLanguageServerWork,
10467        cx: &mut ViewContext<Self>,
10468    ) {
10469        if let Some(project) = self.project.clone() {
10470            self.buffer.update(cx, |multi_buffer, cx| {
10471                project.update(cx, |project, cx| {
10472                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10473                });
10474            })
10475        }
10476    }
10477
10478    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10479        cx.show_character_palette();
10480    }
10481
10482    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10483        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10484            let buffer = self.buffer.read(cx).snapshot(cx);
10485            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10486            let is_valid = buffer
10487                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10488                .any(|entry| {
10489                    entry.diagnostic.is_primary
10490                        && !entry.range.is_empty()
10491                        && entry.range.start == primary_range_start
10492                        && entry.diagnostic.message == active_diagnostics.primary_message
10493                });
10494
10495            if is_valid != active_diagnostics.is_valid {
10496                active_diagnostics.is_valid = is_valid;
10497                let mut new_styles = HashMap::default();
10498                for (block_id, diagnostic) in &active_diagnostics.blocks {
10499                    new_styles.insert(
10500                        *block_id,
10501                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10502                    );
10503                }
10504                self.display_map.update(cx, |display_map, _cx| {
10505                    display_map.replace_blocks(new_styles)
10506                });
10507            }
10508        }
10509    }
10510
10511    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10512        self.dismiss_diagnostics(cx);
10513        let snapshot = self.snapshot(cx);
10514        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10515            let buffer = self.buffer.read(cx).snapshot(cx);
10516
10517            let mut primary_range = None;
10518            let mut primary_message = None;
10519            let mut group_end = Point::zero();
10520            let diagnostic_group = buffer
10521                .diagnostic_group::<MultiBufferPoint>(group_id)
10522                .filter_map(|entry| {
10523                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10524                        && (entry.range.start.row == entry.range.end.row
10525                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10526                    {
10527                        return None;
10528                    }
10529                    if entry.range.end > group_end {
10530                        group_end = entry.range.end;
10531                    }
10532                    if entry.diagnostic.is_primary {
10533                        primary_range = Some(entry.range.clone());
10534                        primary_message = Some(entry.diagnostic.message.clone());
10535                    }
10536                    Some(entry)
10537                })
10538                .collect::<Vec<_>>();
10539            let primary_range = primary_range?;
10540            let primary_message = primary_message?;
10541            let primary_range =
10542                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10543
10544            let blocks = display_map
10545                .insert_blocks(
10546                    diagnostic_group.iter().map(|entry| {
10547                        let diagnostic = entry.diagnostic.clone();
10548                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10549                        BlockProperties {
10550                            style: BlockStyle::Fixed,
10551                            position: buffer.anchor_after(entry.range.start),
10552                            height: message_height,
10553                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10554                            disposition: BlockDisposition::Below,
10555                            priority: 0,
10556                        }
10557                    }),
10558                    cx,
10559                )
10560                .into_iter()
10561                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10562                .collect();
10563
10564            Some(ActiveDiagnosticGroup {
10565                primary_range,
10566                primary_message,
10567                group_id,
10568                blocks,
10569                is_valid: true,
10570            })
10571        });
10572        self.active_diagnostics.is_some()
10573    }
10574
10575    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10576        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10577            self.display_map.update(cx, |display_map, cx| {
10578                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10579            });
10580            cx.notify();
10581        }
10582    }
10583
10584    pub fn set_selections_from_remote(
10585        &mut self,
10586        selections: Vec<Selection<Anchor>>,
10587        pending_selection: Option<Selection<Anchor>>,
10588        cx: &mut ViewContext<Self>,
10589    ) {
10590        let old_cursor_position = self.selections.newest_anchor().head();
10591        self.selections.change_with(cx, |s| {
10592            s.select_anchors(selections);
10593            if let Some(pending_selection) = pending_selection {
10594                s.set_pending(pending_selection, SelectMode::Character);
10595            } else {
10596                s.clear_pending();
10597            }
10598        });
10599        self.selections_did_change(false, &old_cursor_position, true, cx);
10600    }
10601
10602    fn push_to_selection_history(&mut self) {
10603        self.selection_history.push(SelectionHistoryEntry {
10604            selections: self.selections.disjoint_anchors(),
10605            select_next_state: self.select_next_state.clone(),
10606            select_prev_state: self.select_prev_state.clone(),
10607            add_selections_state: self.add_selections_state.clone(),
10608        });
10609    }
10610
10611    pub fn transact(
10612        &mut self,
10613        cx: &mut ViewContext<Self>,
10614        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10615    ) -> Option<TransactionId> {
10616        self.start_transaction_at(Instant::now(), cx);
10617        update(self, cx);
10618        self.end_transaction_at(Instant::now(), cx)
10619    }
10620
10621    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10622        self.end_selection(cx);
10623        if let Some(tx_id) = self
10624            .buffer
10625            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10626        {
10627            self.selection_history
10628                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10629            cx.emit(EditorEvent::TransactionBegun {
10630                transaction_id: tx_id,
10631            })
10632        }
10633    }
10634
10635    fn end_transaction_at(
10636        &mut self,
10637        now: Instant,
10638        cx: &mut ViewContext<Self>,
10639    ) -> Option<TransactionId> {
10640        if let Some(transaction_id) = self
10641            .buffer
10642            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10643        {
10644            if let Some((_, end_selections)) =
10645                self.selection_history.transaction_mut(transaction_id)
10646            {
10647                *end_selections = Some(self.selections.disjoint_anchors());
10648            } else {
10649                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10650            }
10651
10652            cx.emit(EditorEvent::Edited { transaction_id });
10653            Some(transaction_id)
10654        } else {
10655            None
10656        }
10657    }
10658
10659    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10660        let selection = self.selections.newest::<Point>(cx);
10661
10662        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10663        let range = if selection.is_empty() {
10664            let point = selection.head().to_display_point(&display_map);
10665            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10666            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10667                .to_point(&display_map);
10668            start..end
10669        } else {
10670            selection.range()
10671        };
10672        if display_map.folds_in_range(range).next().is_some() {
10673            self.unfold_lines(&Default::default(), cx)
10674        } else {
10675            self.fold(&Default::default(), cx)
10676        }
10677    }
10678
10679    pub fn toggle_fold_recursive(
10680        &mut self,
10681        _: &actions::ToggleFoldRecursive,
10682        cx: &mut ViewContext<Self>,
10683    ) {
10684        let selection = self.selections.newest::<Point>(cx);
10685
10686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10687        let range = if selection.is_empty() {
10688            let point = selection.head().to_display_point(&display_map);
10689            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10690            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10691                .to_point(&display_map);
10692            start..end
10693        } else {
10694            selection.range()
10695        };
10696        if display_map.folds_in_range(range).next().is_some() {
10697            self.unfold_recursive(&Default::default(), cx)
10698        } else {
10699            self.fold_recursive(&Default::default(), cx)
10700        }
10701    }
10702
10703    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10704        let mut fold_ranges = Vec::new();
10705        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10706        let selections = self.selections.all_adjusted(cx);
10707
10708        for selection in selections {
10709            let range = selection.range().sorted();
10710            let buffer_start_row = range.start.row;
10711
10712            if range.start.row != range.end.row {
10713                let mut found = false;
10714                let mut row = range.start.row;
10715                while row <= range.end.row {
10716                    if let Some((foldable_range, fold_text)) =
10717                        { display_map.foldable_range(MultiBufferRow(row)) }
10718                    {
10719                        found = true;
10720                        row = foldable_range.end.row + 1;
10721                        fold_ranges.push((foldable_range, fold_text));
10722                    } else {
10723                        row += 1
10724                    }
10725                }
10726                if found {
10727                    continue;
10728                }
10729            }
10730
10731            for row in (0..=range.start.row).rev() {
10732                if let Some((foldable_range, fold_text)) =
10733                    display_map.foldable_range(MultiBufferRow(row))
10734                {
10735                    if foldable_range.end.row >= buffer_start_row {
10736                        fold_ranges.push((foldable_range, fold_text));
10737                        if row <= range.start.row {
10738                            break;
10739                        }
10740                    }
10741                }
10742            }
10743        }
10744
10745        self.fold_ranges(fold_ranges, true, cx);
10746    }
10747
10748    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10749        let mut fold_ranges = Vec::new();
10750        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10751
10752        for row in 0..display_map.max_buffer_row().0 {
10753            if let Some((foldable_range, fold_text)) =
10754                display_map.foldable_range(MultiBufferRow(row))
10755            {
10756                fold_ranges.push((foldable_range, fold_text));
10757            }
10758        }
10759
10760        self.fold_ranges(fold_ranges, true, cx);
10761    }
10762
10763    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10764        let mut fold_ranges = Vec::new();
10765        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10766        let selections = self.selections.all_adjusted(cx);
10767
10768        for selection in selections {
10769            let range = selection.range().sorted();
10770            let buffer_start_row = range.start.row;
10771
10772            if range.start.row != range.end.row {
10773                let mut found = false;
10774                for row in range.start.row..=range.end.row {
10775                    if let Some((foldable_range, fold_text)) =
10776                        { display_map.foldable_range(MultiBufferRow(row)) }
10777                    {
10778                        found = true;
10779                        fold_ranges.push((foldable_range, fold_text));
10780                    }
10781                }
10782                if found {
10783                    continue;
10784                }
10785            }
10786
10787            for row in (0..=range.start.row).rev() {
10788                if let Some((foldable_range, fold_text)) =
10789                    display_map.foldable_range(MultiBufferRow(row))
10790                {
10791                    if foldable_range.end.row >= buffer_start_row {
10792                        fold_ranges.push((foldable_range, fold_text));
10793                    } else {
10794                        break;
10795                    }
10796                }
10797            }
10798        }
10799
10800        self.fold_ranges(fold_ranges, true, cx);
10801    }
10802
10803    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10804        let buffer_row = fold_at.buffer_row;
10805        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10806
10807        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10808            let autoscroll = self
10809                .selections
10810                .all::<Point>(cx)
10811                .iter()
10812                .any(|selection| fold_range.overlaps(&selection.range()));
10813
10814            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10815        }
10816    }
10817
10818    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10819        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10820        let buffer = &display_map.buffer_snapshot;
10821        let selections = self.selections.all::<Point>(cx);
10822        let ranges = selections
10823            .iter()
10824            .map(|s| {
10825                let range = s.display_range(&display_map).sorted();
10826                let mut start = range.start.to_point(&display_map);
10827                let mut end = range.end.to_point(&display_map);
10828                start.column = 0;
10829                end.column = buffer.line_len(MultiBufferRow(end.row));
10830                start..end
10831            })
10832            .collect::<Vec<_>>();
10833
10834        self.unfold_ranges(ranges, true, true, cx);
10835    }
10836
10837    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839        let selections = self.selections.all::<Point>(cx);
10840        let ranges = selections
10841            .iter()
10842            .map(|s| {
10843                let mut range = s.display_range(&display_map).sorted();
10844                *range.start.column_mut() = 0;
10845                *range.end.column_mut() = display_map.line_len(range.end.row());
10846                let start = range.start.to_point(&display_map);
10847                let end = range.end.to_point(&display_map);
10848                start..end
10849            })
10850            .collect::<Vec<_>>();
10851
10852        self.unfold_ranges(ranges, true, true, cx);
10853    }
10854
10855    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857
10858        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10859            ..Point::new(
10860                unfold_at.buffer_row.0,
10861                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10862            );
10863
10864        let autoscroll = self
10865            .selections
10866            .all::<Point>(cx)
10867            .iter()
10868            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10869
10870        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10871    }
10872
10873    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10874        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10875        self.unfold_ranges(
10876            [Point::zero()..display_map.max_point().to_point(&display_map)],
10877            true,
10878            true,
10879            cx,
10880        );
10881    }
10882
10883    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10884        let selections = self.selections.all::<Point>(cx);
10885        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10886        let line_mode = self.selections.line_mode;
10887        let ranges = selections.into_iter().map(|s| {
10888            if line_mode {
10889                let start = Point::new(s.start.row, 0);
10890                let end = Point::new(
10891                    s.end.row,
10892                    display_map
10893                        .buffer_snapshot
10894                        .line_len(MultiBufferRow(s.end.row)),
10895                );
10896                (start..end, display_map.fold_placeholder.clone())
10897            } else {
10898                (s.start..s.end, display_map.fold_placeholder.clone())
10899            }
10900        });
10901        self.fold_ranges(ranges, true, cx);
10902    }
10903
10904    pub fn fold_ranges<T: ToOffset + Clone>(
10905        &mut self,
10906        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10907        auto_scroll: bool,
10908        cx: &mut ViewContext<Self>,
10909    ) {
10910        let mut fold_ranges = Vec::new();
10911        let mut buffers_affected = HashMap::default();
10912        let multi_buffer = self.buffer().read(cx);
10913        for (fold_range, fold_text) in ranges {
10914            if let Some((_, buffer, _)) =
10915                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10916            {
10917                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10918            };
10919            fold_ranges.push((fold_range, fold_text));
10920        }
10921
10922        let mut ranges = fold_ranges.into_iter().peekable();
10923        if ranges.peek().is_some() {
10924            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10925
10926            if auto_scroll {
10927                self.request_autoscroll(Autoscroll::fit(), cx);
10928            }
10929
10930            for buffer in buffers_affected.into_values() {
10931                self.sync_expanded_diff_hunks(buffer, cx);
10932            }
10933
10934            cx.notify();
10935
10936            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10937                // Clear diagnostics block when folding a range that contains it.
10938                let snapshot = self.snapshot(cx);
10939                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10940                    drop(snapshot);
10941                    self.active_diagnostics = Some(active_diagnostics);
10942                    self.dismiss_diagnostics(cx);
10943                } else {
10944                    self.active_diagnostics = Some(active_diagnostics);
10945                }
10946            }
10947
10948            self.scrollbar_marker_state.dirty = true;
10949        }
10950    }
10951
10952    pub fn unfold_ranges<T: ToOffset + Clone>(
10953        &mut self,
10954        ranges: impl IntoIterator<Item = Range<T>>,
10955        inclusive: bool,
10956        auto_scroll: bool,
10957        cx: &mut ViewContext<Self>,
10958    ) {
10959        let mut unfold_ranges = Vec::new();
10960        let mut buffers_affected = HashMap::default();
10961        let multi_buffer = self.buffer().read(cx);
10962        for range in ranges {
10963            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10964                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10965            };
10966            unfold_ranges.push(range);
10967        }
10968
10969        let mut ranges = unfold_ranges.into_iter().peekable();
10970        if ranges.peek().is_some() {
10971            self.display_map
10972                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10973            if auto_scroll {
10974                self.request_autoscroll(Autoscroll::fit(), cx);
10975            }
10976
10977            for buffer in buffers_affected.into_values() {
10978                self.sync_expanded_diff_hunks(buffer, cx);
10979            }
10980
10981            cx.notify();
10982            self.scrollbar_marker_state.dirty = true;
10983            self.active_indent_guides_state.dirty = true;
10984        }
10985    }
10986
10987    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10988        self.display_map.read(cx).fold_placeholder.clone()
10989    }
10990
10991    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10992        if hovered != self.gutter_hovered {
10993            self.gutter_hovered = hovered;
10994            cx.notify();
10995        }
10996    }
10997
10998    pub fn insert_blocks(
10999        &mut self,
11000        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11001        autoscroll: Option<Autoscroll>,
11002        cx: &mut ViewContext<Self>,
11003    ) -> Vec<CustomBlockId> {
11004        let blocks = self
11005            .display_map
11006            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11007        if let Some(autoscroll) = autoscroll {
11008            self.request_autoscroll(autoscroll, cx);
11009        }
11010        cx.notify();
11011        blocks
11012    }
11013
11014    pub fn resize_blocks(
11015        &mut self,
11016        heights: HashMap<CustomBlockId, u32>,
11017        autoscroll: Option<Autoscroll>,
11018        cx: &mut ViewContext<Self>,
11019    ) {
11020        self.display_map
11021            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11022        if let Some(autoscroll) = autoscroll {
11023            self.request_autoscroll(autoscroll, cx);
11024        }
11025        cx.notify();
11026    }
11027
11028    pub fn replace_blocks(
11029        &mut self,
11030        renderers: HashMap<CustomBlockId, RenderBlock>,
11031        autoscroll: Option<Autoscroll>,
11032        cx: &mut ViewContext<Self>,
11033    ) {
11034        self.display_map
11035            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11036        if let Some(autoscroll) = autoscroll {
11037            self.request_autoscroll(autoscroll, cx);
11038        }
11039        cx.notify();
11040    }
11041
11042    pub fn remove_blocks(
11043        &mut self,
11044        block_ids: HashSet<CustomBlockId>,
11045        autoscroll: Option<Autoscroll>,
11046        cx: &mut ViewContext<Self>,
11047    ) {
11048        self.display_map.update(cx, |display_map, cx| {
11049            display_map.remove_blocks(block_ids, cx)
11050        });
11051        if let Some(autoscroll) = autoscroll {
11052            self.request_autoscroll(autoscroll, cx);
11053        }
11054        cx.notify();
11055    }
11056
11057    pub fn row_for_block(
11058        &self,
11059        block_id: CustomBlockId,
11060        cx: &mut ViewContext<Self>,
11061    ) -> Option<DisplayRow> {
11062        self.display_map
11063            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11064    }
11065
11066    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11067        self.focused_block = Some(focused_block);
11068    }
11069
11070    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11071        self.focused_block.take()
11072    }
11073
11074    pub fn insert_creases(
11075        &mut self,
11076        creases: impl IntoIterator<Item = Crease>,
11077        cx: &mut ViewContext<Self>,
11078    ) -> Vec<CreaseId> {
11079        self.display_map
11080            .update(cx, |map, cx| map.insert_creases(creases, cx))
11081    }
11082
11083    pub fn remove_creases(
11084        &mut self,
11085        ids: impl IntoIterator<Item = CreaseId>,
11086        cx: &mut ViewContext<Self>,
11087    ) {
11088        self.display_map
11089            .update(cx, |map, cx| map.remove_creases(ids, cx));
11090    }
11091
11092    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11093        self.display_map
11094            .update(cx, |map, cx| map.snapshot(cx))
11095            .longest_row()
11096    }
11097
11098    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11099        self.display_map
11100            .update(cx, |map, cx| map.snapshot(cx))
11101            .max_point()
11102    }
11103
11104    pub fn text(&self, cx: &AppContext) -> String {
11105        self.buffer.read(cx).read(cx).text()
11106    }
11107
11108    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11109        let text = self.text(cx);
11110        let text = text.trim();
11111
11112        if text.is_empty() {
11113            return None;
11114        }
11115
11116        Some(text.to_string())
11117    }
11118
11119    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11120        self.transact(cx, |this, cx| {
11121            this.buffer
11122                .read(cx)
11123                .as_singleton()
11124                .expect("you can only call set_text on editors for singleton buffers")
11125                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11126        });
11127    }
11128
11129    pub fn display_text(&self, cx: &mut AppContext) -> String {
11130        self.display_map
11131            .update(cx, |map, cx| map.snapshot(cx))
11132            .text()
11133    }
11134
11135    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11136        let mut wrap_guides = smallvec::smallvec![];
11137
11138        if self.show_wrap_guides == Some(false) {
11139            return wrap_guides;
11140        }
11141
11142        let settings = self.buffer.read(cx).settings_at(0, cx);
11143        if settings.show_wrap_guides {
11144            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11145                wrap_guides.push((soft_wrap as usize, true));
11146            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11147                wrap_guides.push((soft_wrap as usize, true));
11148            }
11149            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11150        }
11151
11152        wrap_guides
11153    }
11154
11155    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11156        let settings = self.buffer.read(cx).settings_at(0, cx);
11157        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11158        match mode {
11159            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11160                SoftWrap::None
11161            }
11162            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11163            language_settings::SoftWrap::PreferredLineLength => {
11164                SoftWrap::Column(settings.preferred_line_length)
11165            }
11166            language_settings::SoftWrap::Bounded => {
11167                SoftWrap::Bounded(settings.preferred_line_length)
11168            }
11169        }
11170    }
11171
11172    pub fn set_soft_wrap_mode(
11173        &mut self,
11174        mode: language_settings::SoftWrap,
11175        cx: &mut ViewContext<Self>,
11176    ) {
11177        self.soft_wrap_mode_override = Some(mode);
11178        cx.notify();
11179    }
11180
11181    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11182        let rem_size = cx.rem_size();
11183        self.display_map.update(cx, |map, cx| {
11184            map.set_font(
11185                style.text.font(),
11186                style.text.font_size.to_pixels(rem_size),
11187                cx,
11188            )
11189        });
11190        self.style = Some(style);
11191    }
11192
11193    pub fn style(&self) -> Option<&EditorStyle> {
11194        self.style.as_ref()
11195    }
11196
11197    // Called by the element. This method is not designed to be called outside of the editor
11198    // element's layout code because it does not notify when rewrapping is computed synchronously.
11199    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11200        self.display_map
11201            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11202    }
11203
11204    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11205        if self.soft_wrap_mode_override.is_some() {
11206            self.soft_wrap_mode_override.take();
11207        } else {
11208            let soft_wrap = match self.soft_wrap_mode(cx) {
11209                SoftWrap::GitDiff => return,
11210                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11211                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11212                    language_settings::SoftWrap::None
11213                }
11214            };
11215            self.soft_wrap_mode_override = Some(soft_wrap);
11216        }
11217        cx.notify();
11218    }
11219
11220    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11221        let Some(workspace) = self.workspace() else {
11222            return;
11223        };
11224        let fs = workspace.read(cx).app_state().fs.clone();
11225        let current_show = TabBarSettings::get_global(cx).show;
11226        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11227            setting.show = Some(!current_show);
11228        });
11229    }
11230
11231    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11232        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11233            self.buffer
11234                .read(cx)
11235                .settings_at(0, cx)
11236                .indent_guides
11237                .enabled
11238        });
11239        self.show_indent_guides = Some(!currently_enabled);
11240        cx.notify();
11241    }
11242
11243    fn should_show_indent_guides(&self) -> Option<bool> {
11244        self.show_indent_guides
11245    }
11246
11247    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11248        let mut editor_settings = EditorSettings::get_global(cx).clone();
11249        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11250        EditorSettings::override_global(editor_settings, cx);
11251    }
11252
11253    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11254        self.use_relative_line_numbers
11255            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11256    }
11257
11258    pub fn toggle_relative_line_numbers(
11259        &mut self,
11260        _: &ToggleRelativeLineNumbers,
11261        cx: &mut ViewContext<Self>,
11262    ) {
11263        let is_relative = self.should_use_relative_line_numbers(cx);
11264        self.set_relative_line_number(Some(!is_relative), cx)
11265    }
11266
11267    pub fn set_relative_line_number(
11268        &mut self,
11269        is_relative: Option<bool>,
11270        cx: &mut ViewContext<Self>,
11271    ) {
11272        self.use_relative_line_numbers = is_relative;
11273        cx.notify();
11274    }
11275
11276    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11277        self.show_gutter = show_gutter;
11278        cx.notify();
11279    }
11280
11281    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11282        self.show_line_numbers = Some(show_line_numbers);
11283        cx.notify();
11284    }
11285
11286    pub fn set_show_git_diff_gutter(
11287        &mut self,
11288        show_git_diff_gutter: bool,
11289        cx: &mut ViewContext<Self>,
11290    ) {
11291        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11292        cx.notify();
11293    }
11294
11295    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11296        self.show_code_actions = Some(show_code_actions);
11297        cx.notify();
11298    }
11299
11300    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11301        self.show_runnables = Some(show_runnables);
11302        cx.notify();
11303    }
11304
11305    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11306        if self.display_map.read(cx).masked != masked {
11307            self.display_map.update(cx, |map, _| map.masked = masked);
11308        }
11309        cx.notify()
11310    }
11311
11312    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11313        self.show_wrap_guides = Some(show_wrap_guides);
11314        cx.notify();
11315    }
11316
11317    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11318        self.show_indent_guides = Some(show_indent_guides);
11319        cx.notify();
11320    }
11321
11322    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11323        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11324            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11325                if let Some(dir) = file.abs_path(cx).parent() {
11326                    return Some(dir.to_owned());
11327                }
11328            }
11329
11330            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11331                return Some(project_path.path.to_path_buf());
11332            }
11333        }
11334
11335        None
11336    }
11337
11338    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11339        self.active_excerpt(cx)?
11340            .1
11341            .read(cx)
11342            .file()
11343            .and_then(|f| f.as_local())
11344    }
11345
11346    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11347        if let Some(target) = self.target_file(cx) {
11348            cx.reveal_path(&target.abs_path(cx));
11349        }
11350    }
11351
11352    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11353        if let Some(file) = self.target_file(cx) {
11354            if let Some(path) = file.abs_path(cx).to_str() {
11355                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11356            }
11357        }
11358    }
11359
11360    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11361        if let Some(file) = self.target_file(cx) {
11362            if let Some(path) = file.path().to_str() {
11363                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11364            }
11365        }
11366    }
11367
11368    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11369        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11370
11371        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11372            self.start_git_blame(true, cx);
11373        }
11374
11375        cx.notify();
11376    }
11377
11378    pub fn toggle_git_blame_inline(
11379        &mut self,
11380        _: &ToggleGitBlameInline,
11381        cx: &mut ViewContext<Self>,
11382    ) {
11383        self.toggle_git_blame_inline_internal(true, cx);
11384        cx.notify();
11385    }
11386
11387    pub fn git_blame_inline_enabled(&self) -> bool {
11388        self.git_blame_inline_enabled
11389    }
11390
11391    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11392        self.show_selection_menu = self
11393            .show_selection_menu
11394            .map(|show_selections_menu| !show_selections_menu)
11395            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11396
11397        cx.notify();
11398    }
11399
11400    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11401        self.show_selection_menu
11402            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11403    }
11404
11405    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11406        if let Some(project) = self.project.as_ref() {
11407            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11408                return;
11409            };
11410
11411            if buffer.read(cx).file().is_none() {
11412                return;
11413            }
11414
11415            let focused = self.focus_handle(cx).contains_focused(cx);
11416
11417            let project = project.clone();
11418            let blame =
11419                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11420            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11421            self.blame = Some(blame);
11422        }
11423    }
11424
11425    fn toggle_git_blame_inline_internal(
11426        &mut self,
11427        user_triggered: bool,
11428        cx: &mut ViewContext<Self>,
11429    ) {
11430        if self.git_blame_inline_enabled {
11431            self.git_blame_inline_enabled = false;
11432            self.show_git_blame_inline = false;
11433            self.show_git_blame_inline_delay_task.take();
11434        } else {
11435            self.git_blame_inline_enabled = true;
11436            self.start_git_blame_inline(user_triggered, cx);
11437        }
11438
11439        cx.notify();
11440    }
11441
11442    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11443        self.start_git_blame(user_triggered, cx);
11444
11445        if ProjectSettings::get_global(cx)
11446            .git
11447            .inline_blame_delay()
11448            .is_some()
11449        {
11450            self.start_inline_blame_timer(cx);
11451        } else {
11452            self.show_git_blame_inline = true
11453        }
11454    }
11455
11456    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11457        self.blame.as_ref()
11458    }
11459
11460    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11461        self.show_git_blame_gutter && self.has_blame_entries(cx)
11462    }
11463
11464    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11465        self.show_git_blame_inline
11466            && self.focus_handle.is_focused(cx)
11467            && !self.newest_selection_head_on_empty_line(cx)
11468            && self.has_blame_entries(cx)
11469    }
11470
11471    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11472        self.blame()
11473            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11474    }
11475
11476    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11477        let cursor_anchor = self.selections.newest_anchor().head();
11478
11479        let snapshot = self.buffer.read(cx).snapshot(cx);
11480        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11481
11482        snapshot.line_len(buffer_row) == 0
11483    }
11484
11485    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11486        let (path, selection, repo) = maybe!({
11487            let project_handle = self.project.as_ref()?.clone();
11488            let project = project_handle.read(cx);
11489
11490            let selection = self.selections.newest::<Point>(cx);
11491            let selection_range = selection.range();
11492
11493            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11494                (buffer, selection_range.start.row..selection_range.end.row)
11495            } else {
11496                let buffer_ranges = self
11497                    .buffer()
11498                    .read(cx)
11499                    .range_to_buffer_ranges(selection_range, cx);
11500
11501                let (buffer, range, _) = if selection.reversed {
11502                    buffer_ranges.first()
11503                } else {
11504                    buffer_ranges.last()
11505                }?;
11506
11507                let snapshot = buffer.read(cx).snapshot();
11508                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11509                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11510                (buffer.clone(), selection)
11511            };
11512
11513            let path = buffer
11514                .read(cx)
11515                .file()?
11516                .as_local()?
11517                .path()
11518                .to_str()?
11519                .to_string();
11520            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11521            Some((path, selection, repo))
11522        })
11523        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11524
11525        const REMOTE_NAME: &str = "origin";
11526        let origin_url = repo
11527            .remote_url(REMOTE_NAME)
11528            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11529        let sha = repo
11530            .head_sha()
11531            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11532
11533        let (provider, remote) =
11534            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11535                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11536
11537        Ok(provider.build_permalink(
11538            remote,
11539            BuildPermalinkParams {
11540                sha: &sha,
11541                path: &path,
11542                selection: Some(selection),
11543            },
11544        ))
11545    }
11546
11547    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11548        let permalink = self.get_permalink_to_line(cx);
11549
11550        match permalink {
11551            Ok(permalink) => {
11552                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11553            }
11554            Err(err) => {
11555                let message = format!("Failed to copy permalink: {err}");
11556
11557                Err::<(), anyhow::Error>(err).log_err();
11558
11559                if let Some(workspace) = self.workspace() {
11560                    workspace.update(cx, |workspace, cx| {
11561                        struct CopyPermalinkToLine;
11562
11563                        workspace.show_toast(
11564                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11565                            cx,
11566                        )
11567                    })
11568                }
11569            }
11570        }
11571    }
11572
11573    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11574        if let Some(file) = self.target_file(cx) {
11575            if let Some(path) = file.path().to_str() {
11576                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11577                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11578            }
11579        }
11580    }
11581
11582    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11583        let permalink = self.get_permalink_to_line(cx);
11584
11585        match permalink {
11586            Ok(permalink) => {
11587                cx.open_url(permalink.as_ref());
11588            }
11589            Err(err) => {
11590                let message = format!("Failed to open permalink: {err}");
11591
11592                Err::<(), anyhow::Error>(err).log_err();
11593
11594                if let Some(workspace) = self.workspace() {
11595                    workspace.update(cx, |workspace, cx| {
11596                        struct OpenPermalinkToLine;
11597
11598                        workspace.show_toast(
11599                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11600                            cx,
11601                        )
11602                    })
11603                }
11604            }
11605        }
11606    }
11607
11608    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11609    /// last highlight added will be used.
11610    ///
11611    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11612    pub fn highlight_rows<T: 'static>(
11613        &mut self,
11614        range: Range<Anchor>,
11615        color: Hsla,
11616        should_autoscroll: bool,
11617        cx: &mut ViewContext<Self>,
11618    ) {
11619        let snapshot = self.buffer().read(cx).snapshot(cx);
11620        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11621        let ix = row_highlights.binary_search_by(|highlight| {
11622            Ordering::Equal
11623                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11624                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11625        });
11626
11627        if let Err(mut ix) = ix {
11628            let index = post_inc(&mut self.highlight_order);
11629
11630            // If this range intersects with the preceding highlight, then merge it with
11631            // the preceding highlight. Otherwise insert a new highlight.
11632            let mut merged = false;
11633            if ix > 0 {
11634                let prev_highlight = &mut row_highlights[ix - 1];
11635                if prev_highlight
11636                    .range
11637                    .end
11638                    .cmp(&range.start, &snapshot)
11639                    .is_ge()
11640                {
11641                    ix -= 1;
11642                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11643                        prev_highlight.range.end = range.end;
11644                    }
11645                    merged = true;
11646                    prev_highlight.index = index;
11647                    prev_highlight.color = color;
11648                    prev_highlight.should_autoscroll = should_autoscroll;
11649                }
11650            }
11651
11652            if !merged {
11653                row_highlights.insert(
11654                    ix,
11655                    RowHighlight {
11656                        range: range.clone(),
11657                        index,
11658                        color,
11659                        should_autoscroll,
11660                    },
11661                );
11662            }
11663
11664            // If any of the following highlights intersect with this one, merge them.
11665            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11666                let highlight = &row_highlights[ix];
11667                if next_highlight
11668                    .range
11669                    .start
11670                    .cmp(&highlight.range.end, &snapshot)
11671                    .is_le()
11672                {
11673                    if next_highlight
11674                        .range
11675                        .end
11676                        .cmp(&highlight.range.end, &snapshot)
11677                        .is_gt()
11678                    {
11679                        row_highlights[ix].range.end = next_highlight.range.end;
11680                    }
11681                    row_highlights.remove(ix + 1);
11682                } else {
11683                    break;
11684                }
11685            }
11686        }
11687    }
11688
11689    /// Remove any highlighted row ranges of the given type that intersect the
11690    /// given ranges.
11691    pub fn remove_highlighted_rows<T: 'static>(
11692        &mut self,
11693        ranges_to_remove: Vec<Range<Anchor>>,
11694        cx: &mut ViewContext<Self>,
11695    ) {
11696        let snapshot = self.buffer().read(cx).snapshot(cx);
11697        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11698        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11699        row_highlights.retain(|highlight| {
11700            while let Some(range_to_remove) = ranges_to_remove.peek() {
11701                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11702                    Ordering::Less | Ordering::Equal => {
11703                        ranges_to_remove.next();
11704                    }
11705                    Ordering::Greater => {
11706                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11707                            Ordering::Less | Ordering::Equal => {
11708                                return false;
11709                            }
11710                            Ordering::Greater => break,
11711                        }
11712                    }
11713                }
11714            }
11715
11716            true
11717        })
11718    }
11719
11720    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11721    pub fn clear_row_highlights<T: 'static>(&mut self) {
11722        self.highlighted_rows.remove(&TypeId::of::<T>());
11723    }
11724
11725    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11726    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11727        self.highlighted_rows
11728            .get(&TypeId::of::<T>())
11729            .map_or(&[] as &[_], |vec| vec.as_slice())
11730            .iter()
11731            .map(|highlight| (highlight.range.clone(), highlight.color))
11732    }
11733
11734    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11735    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11736    /// Allows to ignore certain kinds of highlights.
11737    pub fn highlighted_display_rows(
11738        &mut self,
11739        cx: &mut WindowContext,
11740    ) -> BTreeMap<DisplayRow, Hsla> {
11741        let snapshot = self.snapshot(cx);
11742        let mut used_highlight_orders = HashMap::default();
11743        self.highlighted_rows
11744            .iter()
11745            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11746            .fold(
11747                BTreeMap::<DisplayRow, Hsla>::new(),
11748                |mut unique_rows, highlight| {
11749                    let start = highlight.range.start.to_display_point(&snapshot);
11750                    let end = highlight.range.end.to_display_point(&snapshot);
11751                    let start_row = start.row().0;
11752                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11753                        && end.column() == 0
11754                    {
11755                        end.row().0.saturating_sub(1)
11756                    } else {
11757                        end.row().0
11758                    };
11759                    for row in start_row..=end_row {
11760                        let used_index =
11761                            used_highlight_orders.entry(row).or_insert(highlight.index);
11762                        if highlight.index >= *used_index {
11763                            *used_index = highlight.index;
11764                            unique_rows.insert(DisplayRow(row), highlight.color);
11765                        }
11766                    }
11767                    unique_rows
11768                },
11769            )
11770    }
11771
11772    pub fn highlighted_display_row_for_autoscroll(
11773        &self,
11774        snapshot: &DisplaySnapshot,
11775    ) -> Option<DisplayRow> {
11776        self.highlighted_rows
11777            .values()
11778            .flat_map(|highlighted_rows| highlighted_rows.iter())
11779            .filter_map(|highlight| {
11780                if highlight.should_autoscroll {
11781                    Some(highlight.range.start.to_display_point(snapshot).row())
11782                } else {
11783                    None
11784                }
11785            })
11786            .min()
11787    }
11788
11789    pub fn set_search_within_ranges(
11790        &mut self,
11791        ranges: &[Range<Anchor>],
11792        cx: &mut ViewContext<Self>,
11793    ) {
11794        self.highlight_background::<SearchWithinRange>(
11795            ranges,
11796            |colors| colors.editor_document_highlight_read_background,
11797            cx,
11798        )
11799    }
11800
11801    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11802        self.breadcrumb_header = Some(new_header);
11803    }
11804
11805    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11806        self.clear_background_highlights::<SearchWithinRange>(cx);
11807    }
11808
11809    pub fn highlight_background<T: 'static>(
11810        &mut self,
11811        ranges: &[Range<Anchor>],
11812        color_fetcher: fn(&ThemeColors) -> Hsla,
11813        cx: &mut ViewContext<Self>,
11814    ) {
11815        self.background_highlights
11816            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11817        self.scrollbar_marker_state.dirty = true;
11818        cx.notify();
11819    }
11820
11821    pub fn clear_background_highlights<T: 'static>(
11822        &mut self,
11823        cx: &mut ViewContext<Self>,
11824    ) -> Option<BackgroundHighlight> {
11825        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11826        if !text_highlights.1.is_empty() {
11827            self.scrollbar_marker_state.dirty = true;
11828            cx.notify();
11829        }
11830        Some(text_highlights)
11831    }
11832
11833    pub fn highlight_gutter<T: 'static>(
11834        &mut self,
11835        ranges: &[Range<Anchor>],
11836        color_fetcher: fn(&AppContext) -> Hsla,
11837        cx: &mut ViewContext<Self>,
11838    ) {
11839        self.gutter_highlights
11840            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11841        cx.notify();
11842    }
11843
11844    pub fn clear_gutter_highlights<T: 'static>(
11845        &mut self,
11846        cx: &mut ViewContext<Self>,
11847    ) -> Option<GutterHighlight> {
11848        cx.notify();
11849        self.gutter_highlights.remove(&TypeId::of::<T>())
11850    }
11851
11852    #[cfg(feature = "test-support")]
11853    pub fn all_text_background_highlights(
11854        &mut self,
11855        cx: &mut ViewContext<Self>,
11856    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11857        let snapshot = self.snapshot(cx);
11858        let buffer = &snapshot.buffer_snapshot;
11859        let start = buffer.anchor_before(0);
11860        let end = buffer.anchor_after(buffer.len());
11861        let theme = cx.theme().colors();
11862        self.background_highlights_in_range(start..end, &snapshot, theme)
11863    }
11864
11865    #[cfg(feature = "test-support")]
11866    pub fn search_background_highlights(
11867        &mut self,
11868        cx: &mut ViewContext<Self>,
11869    ) -> Vec<Range<Point>> {
11870        let snapshot = self.buffer().read(cx).snapshot(cx);
11871
11872        let highlights = self
11873            .background_highlights
11874            .get(&TypeId::of::<items::BufferSearchHighlights>());
11875
11876        if let Some((_color, ranges)) = highlights {
11877            ranges
11878                .iter()
11879                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11880                .collect_vec()
11881        } else {
11882            vec![]
11883        }
11884    }
11885
11886    fn document_highlights_for_position<'a>(
11887        &'a self,
11888        position: Anchor,
11889        buffer: &'a MultiBufferSnapshot,
11890    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11891        let read_highlights = self
11892            .background_highlights
11893            .get(&TypeId::of::<DocumentHighlightRead>())
11894            .map(|h| &h.1);
11895        let write_highlights = self
11896            .background_highlights
11897            .get(&TypeId::of::<DocumentHighlightWrite>())
11898            .map(|h| &h.1);
11899        let left_position = position.bias_left(buffer);
11900        let right_position = position.bias_right(buffer);
11901        read_highlights
11902            .into_iter()
11903            .chain(write_highlights)
11904            .flat_map(move |ranges| {
11905                let start_ix = match ranges.binary_search_by(|probe| {
11906                    let cmp = probe.end.cmp(&left_position, buffer);
11907                    if cmp.is_ge() {
11908                        Ordering::Greater
11909                    } else {
11910                        Ordering::Less
11911                    }
11912                }) {
11913                    Ok(i) | Err(i) => i,
11914                };
11915
11916                ranges[start_ix..]
11917                    .iter()
11918                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11919            })
11920    }
11921
11922    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11923        self.background_highlights
11924            .get(&TypeId::of::<T>())
11925            .map_or(false, |(_, highlights)| !highlights.is_empty())
11926    }
11927
11928    pub fn background_highlights_in_range(
11929        &self,
11930        search_range: Range<Anchor>,
11931        display_snapshot: &DisplaySnapshot,
11932        theme: &ThemeColors,
11933    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11934        let mut results = Vec::new();
11935        for (color_fetcher, ranges) in self.background_highlights.values() {
11936            let color = color_fetcher(theme);
11937            let start_ix = match ranges.binary_search_by(|probe| {
11938                let cmp = probe
11939                    .end
11940                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11941                if cmp.is_gt() {
11942                    Ordering::Greater
11943                } else {
11944                    Ordering::Less
11945                }
11946            }) {
11947                Ok(i) | Err(i) => i,
11948            };
11949            for range in &ranges[start_ix..] {
11950                if range
11951                    .start
11952                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11953                    .is_ge()
11954                {
11955                    break;
11956                }
11957
11958                let start = range.start.to_display_point(display_snapshot);
11959                let end = range.end.to_display_point(display_snapshot);
11960                results.push((start..end, color))
11961            }
11962        }
11963        results
11964    }
11965
11966    pub fn background_highlight_row_ranges<T: 'static>(
11967        &self,
11968        search_range: Range<Anchor>,
11969        display_snapshot: &DisplaySnapshot,
11970        count: usize,
11971    ) -> Vec<RangeInclusive<DisplayPoint>> {
11972        let mut results = Vec::new();
11973        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11974            return vec![];
11975        };
11976
11977        let start_ix = match ranges.binary_search_by(|probe| {
11978            let cmp = probe
11979                .end
11980                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11981            if cmp.is_gt() {
11982                Ordering::Greater
11983            } else {
11984                Ordering::Less
11985            }
11986        }) {
11987            Ok(i) | Err(i) => i,
11988        };
11989        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11990            if let (Some(start_display), Some(end_display)) = (start, end) {
11991                results.push(
11992                    start_display.to_display_point(display_snapshot)
11993                        ..=end_display.to_display_point(display_snapshot),
11994                );
11995            }
11996        };
11997        let mut start_row: Option<Point> = None;
11998        let mut end_row: Option<Point> = None;
11999        if ranges.len() > count {
12000            return Vec::new();
12001        }
12002        for range in &ranges[start_ix..] {
12003            if range
12004                .start
12005                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12006                .is_ge()
12007            {
12008                break;
12009            }
12010            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12011            if let Some(current_row) = &end_row {
12012                if end.row == current_row.row {
12013                    continue;
12014                }
12015            }
12016            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12017            if start_row.is_none() {
12018                assert_eq!(end_row, None);
12019                start_row = Some(start);
12020                end_row = Some(end);
12021                continue;
12022            }
12023            if let Some(current_end) = end_row.as_mut() {
12024                if start.row > current_end.row + 1 {
12025                    push_region(start_row, end_row);
12026                    start_row = Some(start);
12027                    end_row = Some(end);
12028                } else {
12029                    // Merge two hunks.
12030                    *current_end = end;
12031                }
12032            } else {
12033                unreachable!();
12034            }
12035        }
12036        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12037        push_region(start_row, end_row);
12038        results
12039    }
12040
12041    pub fn gutter_highlights_in_range(
12042        &self,
12043        search_range: Range<Anchor>,
12044        display_snapshot: &DisplaySnapshot,
12045        cx: &AppContext,
12046    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12047        let mut results = Vec::new();
12048        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12049            let color = color_fetcher(cx);
12050            let start_ix = match ranges.binary_search_by(|probe| {
12051                let cmp = probe
12052                    .end
12053                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12054                if cmp.is_gt() {
12055                    Ordering::Greater
12056                } else {
12057                    Ordering::Less
12058                }
12059            }) {
12060                Ok(i) | Err(i) => i,
12061            };
12062            for range in &ranges[start_ix..] {
12063                if range
12064                    .start
12065                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12066                    .is_ge()
12067                {
12068                    break;
12069                }
12070
12071                let start = range.start.to_display_point(display_snapshot);
12072                let end = range.end.to_display_point(display_snapshot);
12073                results.push((start..end, color))
12074            }
12075        }
12076        results
12077    }
12078
12079    /// Get the text ranges corresponding to the redaction query
12080    pub fn redacted_ranges(
12081        &self,
12082        search_range: Range<Anchor>,
12083        display_snapshot: &DisplaySnapshot,
12084        cx: &WindowContext,
12085    ) -> Vec<Range<DisplayPoint>> {
12086        display_snapshot
12087            .buffer_snapshot
12088            .redacted_ranges(search_range, |file| {
12089                if let Some(file) = file {
12090                    file.is_private()
12091                        && EditorSettings::get(
12092                            Some(SettingsLocation {
12093                                worktree_id: file.worktree_id(cx),
12094                                path: file.path().as_ref(),
12095                            }),
12096                            cx,
12097                        )
12098                        .redact_private_values
12099                } else {
12100                    false
12101                }
12102            })
12103            .map(|range| {
12104                range.start.to_display_point(display_snapshot)
12105                    ..range.end.to_display_point(display_snapshot)
12106            })
12107            .collect()
12108    }
12109
12110    pub fn highlight_text<T: 'static>(
12111        &mut self,
12112        ranges: Vec<Range<Anchor>>,
12113        style: HighlightStyle,
12114        cx: &mut ViewContext<Self>,
12115    ) {
12116        self.display_map.update(cx, |map, _| {
12117            map.highlight_text(TypeId::of::<T>(), ranges, style)
12118        });
12119        cx.notify();
12120    }
12121
12122    pub(crate) fn highlight_inlays<T: 'static>(
12123        &mut self,
12124        highlights: Vec<InlayHighlight>,
12125        style: HighlightStyle,
12126        cx: &mut ViewContext<Self>,
12127    ) {
12128        self.display_map.update(cx, |map, _| {
12129            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12130        });
12131        cx.notify();
12132    }
12133
12134    pub fn text_highlights<'a, T: 'static>(
12135        &'a self,
12136        cx: &'a AppContext,
12137    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12138        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12139    }
12140
12141    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12142        let cleared = self
12143            .display_map
12144            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12145        if cleared {
12146            cx.notify();
12147        }
12148    }
12149
12150    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12151        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12152            && self.focus_handle.is_focused(cx)
12153    }
12154
12155    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12156        self.show_cursor_when_unfocused = is_enabled;
12157        cx.notify();
12158    }
12159
12160    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12161        cx.notify();
12162    }
12163
12164    fn on_buffer_event(
12165        &mut self,
12166        multibuffer: Model<MultiBuffer>,
12167        event: &multi_buffer::Event,
12168        cx: &mut ViewContext<Self>,
12169    ) {
12170        match event {
12171            multi_buffer::Event::Edited {
12172                singleton_buffer_edited,
12173            } => {
12174                self.scrollbar_marker_state.dirty = true;
12175                self.active_indent_guides_state.dirty = true;
12176                self.refresh_active_diagnostics(cx);
12177                self.refresh_code_actions(cx);
12178                if self.has_active_inline_completion(cx) {
12179                    self.update_visible_inline_completion(cx);
12180                }
12181                cx.emit(EditorEvent::BufferEdited);
12182                cx.emit(SearchEvent::MatchesInvalidated);
12183                if *singleton_buffer_edited {
12184                    if let Some(project) = &self.project {
12185                        let project = project.read(cx);
12186                        #[allow(clippy::mutable_key_type)]
12187                        let languages_affected = multibuffer
12188                            .read(cx)
12189                            .all_buffers()
12190                            .into_iter()
12191                            .filter_map(|buffer| {
12192                                let buffer = buffer.read(cx);
12193                                let language = buffer.language()?;
12194                                if project.is_local()
12195                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12196                                {
12197                                    None
12198                                } else {
12199                                    Some(language)
12200                                }
12201                            })
12202                            .cloned()
12203                            .collect::<HashSet<_>>();
12204                        if !languages_affected.is_empty() {
12205                            self.refresh_inlay_hints(
12206                                InlayHintRefreshReason::BufferEdited(languages_affected),
12207                                cx,
12208                            );
12209                        }
12210                    }
12211                }
12212
12213                let Some(project) = &self.project else { return };
12214                let (telemetry, is_via_ssh) = {
12215                    let project = project.read(cx);
12216                    let telemetry = project.client().telemetry().clone();
12217                    let is_via_ssh = project.is_via_ssh();
12218                    (telemetry, is_via_ssh)
12219                };
12220                refresh_linked_ranges(self, cx);
12221                telemetry.log_edit_event("editor", is_via_ssh);
12222            }
12223            multi_buffer::Event::ExcerptsAdded {
12224                buffer,
12225                predecessor,
12226                excerpts,
12227            } => {
12228                self.tasks_update_task = Some(self.refresh_runnables(cx));
12229                cx.emit(EditorEvent::ExcerptsAdded {
12230                    buffer: buffer.clone(),
12231                    predecessor: *predecessor,
12232                    excerpts: excerpts.clone(),
12233                });
12234                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12235            }
12236            multi_buffer::Event::ExcerptsRemoved { ids } => {
12237                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12238                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12239            }
12240            multi_buffer::Event::ExcerptsEdited { ids } => {
12241                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12242            }
12243            multi_buffer::Event::ExcerptsExpanded { ids } => {
12244                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12245            }
12246            multi_buffer::Event::Reparsed(buffer_id) => {
12247                self.tasks_update_task = Some(self.refresh_runnables(cx));
12248
12249                cx.emit(EditorEvent::Reparsed(*buffer_id));
12250            }
12251            multi_buffer::Event::LanguageChanged(buffer_id) => {
12252                linked_editing_ranges::refresh_linked_ranges(self, cx);
12253                cx.emit(EditorEvent::Reparsed(*buffer_id));
12254                cx.notify();
12255            }
12256            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12257            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12258            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12259                cx.emit(EditorEvent::TitleChanged)
12260            }
12261            multi_buffer::Event::DiffBaseChanged => {
12262                self.scrollbar_marker_state.dirty = true;
12263                cx.emit(EditorEvent::DiffBaseChanged);
12264                cx.notify();
12265            }
12266            multi_buffer::Event::DiffUpdated { buffer } => {
12267                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12268                cx.notify();
12269            }
12270            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12271            multi_buffer::Event::DiagnosticsUpdated => {
12272                self.refresh_active_diagnostics(cx);
12273                self.scrollbar_marker_state.dirty = true;
12274                cx.notify();
12275            }
12276            _ => {}
12277        };
12278    }
12279
12280    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12281        cx.notify();
12282    }
12283
12284    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12285        self.tasks_update_task = Some(self.refresh_runnables(cx));
12286        self.refresh_inline_completion(true, false, cx);
12287        self.refresh_inlay_hints(
12288            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12289                self.selections.newest_anchor().head(),
12290                &self.buffer.read(cx).snapshot(cx),
12291                cx,
12292            )),
12293            cx,
12294        );
12295
12296        let old_cursor_shape = self.cursor_shape;
12297
12298        {
12299            let editor_settings = EditorSettings::get_global(cx);
12300            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12301            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12302            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12303        }
12304
12305        if old_cursor_shape != self.cursor_shape {
12306            cx.emit(EditorEvent::CursorShapeChanged);
12307        }
12308
12309        let project_settings = ProjectSettings::get_global(cx);
12310        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12311
12312        if self.mode == EditorMode::Full {
12313            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12314            if self.git_blame_inline_enabled != inline_blame_enabled {
12315                self.toggle_git_blame_inline_internal(false, cx);
12316            }
12317        }
12318
12319        cx.notify();
12320    }
12321
12322    pub fn set_searchable(&mut self, searchable: bool) {
12323        self.searchable = searchable;
12324    }
12325
12326    pub fn searchable(&self) -> bool {
12327        self.searchable
12328    }
12329
12330    fn open_proposed_changes_editor(
12331        &mut self,
12332        _: &OpenProposedChangesEditor,
12333        cx: &mut ViewContext<Self>,
12334    ) {
12335        let Some(workspace) = self.workspace() else {
12336            cx.propagate();
12337            return;
12338        };
12339
12340        let buffer = self.buffer.read(cx);
12341        let mut new_selections_by_buffer = HashMap::default();
12342        for selection in self.selections.all::<usize>(cx) {
12343            for (buffer, range, _) in
12344                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12345            {
12346                let mut range = range.to_point(buffer.read(cx));
12347                range.start.column = 0;
12348                range.end.column = buffer.read(cx).line_len(range.end.row);
12349                new_selections_by_buffer
12350                    .entry(buffer)
12351                    .or_insert(Vec::new())
12352                    .push(range)
12353            }
12354        }
12355
12356        let proposed_changes_buffers = new_selections_by_buffer
12357            .into_iter()
12358            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12359            .collect::<Vec<_>>();
12360        let proposed_changes_editor = cx.new_view(|cx| {
12361            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12362        });
12363
12364        cx.window_context().defer(move |cx| {
12365            workspace.update(cx, |workspace, cx| {
12366                workspace.active_pane().update(cx, |pane, cx| {
12367                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12368                });
12369            });
12370        });
12371    }
12372
12373    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12374        self.open_excerpts_common(true, cx)
12375    }
12376
12377    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12378        self.open_excerpts_common(false, cx)
12379    }
12380
12381    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12382        let buffer = self.buffer.read(cx);
12383        if buffer.is_singleton() {
12384            cx.propagate();
12385            return;
12386        }
12387
12388        let Some(workspace) = self.workspace() else {
12389            cx.propagate();
12390            return;
12391        };
12392
12393        let mut new_selections_by_buffer = HashMap::default();
12394        for selection in self.selections.all::<usize>(cx) {
12395            for (mut buffer_handle, mut range, _) in
12396                buffer.range_to_buffer_ranges(selection.range(), cx)
12397            {
12398                // When editing branch buffers, jump to the corresponding location
12399                // in their base buffer.
12400                let buffer = buffer_handle.read(cx);
12401                if let Some(base_buffer) = buffer.diff_base_buffer() {
12402                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12403                    buffer_handle = base_buffer;
12404                }
12405
12406                if selection.reversed {
12407                    mem::swap(&mut range.start, &mut range.end);
12408                }
12409                new_selections_by_buffer
12410                    .entry(buffer_handle)
12411                    .or_insert(Vec::new())
12412                    .push(range)
12413            }
12414        }
12415
12416        // We defer the pane interaction because we ourselves are a workspace item
12417        // and activating a new item causes the pane to call a method on us reentrantly,
12418        // which panics if we're on the stack.
12419        cx.window_context().defer(move |cx| {
12420            workspace.update(cx, |workspace, cx| {
12421                let pane = if split {
12422                    workspace.adjacent_pane(cx)
12423                } else {
12424                    workspace.active_pane().clone()
12425                };
12426
12427                for (buffer, ranges) in new_selections_by_buffer {
12428                    let editor =
12429                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12430                    editor.update(cx, |editor, cx| {
12431                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12432                            s.select_ranges(ranges);
12433                        });
12434                    });
12435                }
12436            })
12437        });
12438    }
12439
12440    fn jump(
12441        &mut self,
12442        path: ProjectPath,
12443        position: Point,
12444        anchor: language::Anchor,
12445        offset_from_top: u32,
12446        cx: &mut ViewContext<Self>,
12447    ) {
12448        let workspace = self.workspace();
12449        cx.spawn(|_, mut cx| async move {
12450            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12451            let editor = workspace.update(&mut cx, |workspace, cx| {
12452                // Reset the preview item id before opening the new item
12453                workspace.active_pane().update(cx, |pane, cx| {
12454                    pane.set_preview_item_id(None, cx);
12455                });
12456                workspace.open_path_preview(path, None, true, true, cx)
12457            })?;
12458            let editor = editor
12459                .await?
12460                .downcast::<Editor>()
12461                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12462                .downgrade();
12463            editor.update(&mut cx, |editor, cx| {
12464                let buffer = editor
12465                    .buffer()
12466                    .read(cx)
12467                    .as_singleton()
12468                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12469                let buffer = buffer.read(cx);
12470                let cursor = if buffer.can_resolve(&anchor) {
12471                    language::ToPoint::to_point(&anchor, buffer)
12472                } else {
12473                    buffer.clip_point(position, Bias::Left)
12474                };
12475
12476                let nav_history = editor.nav_history.take();
12477                editor.change_selections(
12478                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12479                    cx,
12480                    |s| {
12481                        s.select_ranges([cursor..cursor]);
12482                    },
12483                );
12484                editor.nav_history = nav_history;
12485
12486                anyhow::Ok(())
12487            })??;
12488
12489            anyhow::Ok(())
12490        })
12491        .detach_and_log_err(cx);
12492    }
12493
12494    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12495        let snapshot = self.buffer.read(cx).read(cx);
12496        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12497        Some(
12498            ranges
12499                .iter()
12500                .map(move |range| {
12501                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12502                })
12503                .collect(),
12504        )
12505    }
12506
12507    fn selection_replacement_ranges(
12508        &self,
12509        range: Range<OffsetUtf16>,
12510        cx: &AppContext,
12511    ) -> Vec<Range<OffsetUtf16>> {
12512        let selections = self.selections.all::<OffsetUtf16>(cx);
12513        let newest_selection = selections
12514            .iter()
12515            .max_by_key(|selection| selection.id)
12516            .unwrap();
12517        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12518        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12519        let snapshot = self.buffer.read(cx).read(cx);
12520        selections
12521            .into_iter()
12522            .map(|mut selection| {
12523                selection.start.0 =
12524                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12525                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12526                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12527                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12528            })
12529            .collect()
12530    }
12531
12532    fn report_editor_event(
12533        &self,
12534        operation: &'static str,
12535        file_extension: Option<String>,
12536        cx: &AppContext,
12537    ) {
12538        if cfg!(any(test, feature = "test-support")) {
12539            return;
12540        }
12541
12542        let Some(project) = &self.project else { return };
12543
12544        // If None, we are in a file without an extension
12545        let file = self
12546            .buffer
12547            .read(cx)
12548            .as_singleton()
12549            .and_then(|b| b.read(cx).file());
12550        let file_extension = file_extension.or(file
12551            .as_ref()
12552            .and_then(|file| Path::new(file.file_name(cx)).extension())
12553            .and_then(|e| e.to_str())
12554            .map(|a| a.to_string()));
12555
12556        let vim_mode = cx
12557            .global::<SettingsStore>()
12558            .raw_user_settings()
12559            .get("vim_mode")
12560            == Some(&serde_json::Value::Bool(true));
12561
12562        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12563            == language::language_settings::InlineCompletionProvider::Copilot;
12564        let copilot_enabled_for_language = self
12565            .buffer
12566            .read(cx)
12567            .settings_at(0, cx)
12568            .show_inline_completions;
12569
12570        let project = project.read(cx);
12571        let telemetry = project.client().telemetry().clone();
12572        telemetry.report_editor_event(
12573            file_extension,
12574            vim_mode,
12575            operation,
12576            copilot_enabled,
12577            copilot_enabled_for_language,
12578            project.is_via_ssh(),
12579        )
12580    }
12581
12582    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12583    /// with each line being an array of {text, highlight} objects.
12584    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12585        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12586            return;
12587        };
12588
12589        #[derive(Serialize)]
12590        struct Chunk<'a> {
12591            text: String,
12592            highlight: Option<&'a str>,
12593        }
12594
12595        let snapshot = buffer.read(cx).snapshot();
12596        let range = self
12597            .selected_text_range(false, cx)
12598            .and_then(|selection| {
12599                if selection.range.is_empty() {
12600                    None
12601                } else {
12602                    Some(selection.range)
12603                }
12604            })
12605            .unwrap_or_else(|| 0..snapshot.len());
12606
12607        let chunks = snapshot.chunks(range, true);
12608        let mut lines = Vec::new();
12609        let mut line: VecDeque<Chunk> = VecDeque::new();
12610
12611        let Some(style) = self.style.as_ref() else {
12612            return;
12613        };
12614
12615        for chunk in chunks {
12616            let highlight = chunk
12617                .syntax_highlight_id
12618                .and_then(|id| id.name(&style.syntax));
12619            let mut chunk_lines = chunk.text.split('\n').peekable();
12620            while let Some(text) = chunk_lines.next() {
12621                let mut merged_with_last_token = false;
12622                if let Some(last_token) = line.back_mut() {
12623                    if last_token.highlight == highlight {
12624                        last_token.text.push_str(text);
12625                        merged_with_last_token = true;
12626                    }
12627                }
12628
12629                if !merged_with_last_token {
12630                    line.push_back(Chunk {
12631                        text: text.into(),
12632                        highlight,
12633                    });
12634                }
12635
12636                if chunk_lines.peek().is_some() {
12637                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12638                        line.pop_front();
12639                    }
12640                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12641                        line.pop_back();
12642                    }
12643
12644                    lines.push(mem::take(&mut line));
12645                }
12646            }
12647        }
12648
12649        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12650            return;
12651        };
12652        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12653    }
12654
12655    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12656        &self.inlay_hint_cache
12657    }
12658
12659    pub fn replay_insert_event(
12660        &mut self,
12661        text: &str,
12662        relative_utf16_range: Option<Range<isize>>,
12663        cx: &mut ViewContext<Self>,
12664    ) {
12665        if !self.input_enabled {
12666            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12667            return;
12668        }
12669        if let Some(relative_utf16_range) = relative_utf16_range {
12670            let selections = self.selections.all::<OffsetUtf16>(cx);
12671            self.change_selections(None, cx, |s| {
12672                let new_ranges = selections.into_iter().map(|range| {
12673                    let start = OffsetUtf16(
12674                        range
12675                            .head()
12676                            .0
12677                            .saturating_add_signed(relative_utf16_range.start),
12678                    );
12679                    let end = OffsetUtf16(
12680                        range
12681                            .head()
12682                            .0
12683                            .saturating_add_signed(relative_utf16_range.end),
12684                    );
12685                    start..end
12686                });
12687                s.select_ranges(new_ranges);
12688            });
12689        }
12690
12691        self.handle_input(text, cx);
12692    }
12693
12694    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12695        let Some(provider) = self.semantics_provider.as_ref() else {
12696            return false;
12697        };
12698
12699        let mut supports = false;
12700        self.buffer().read(cx).for_each_buffer(|buffer| {
12701            supports |= provider.supports_inlay_hints(buffer, cx);
12702        });
12703        supports
12704    }
12705
12706    pub fn focus(&self, cx: &mut WindowContext) {
12707        cx.focus(&self.focus_handle)
12708    }
12709
12710    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12711        self.focus_handle.is_focused(cx)
12712    }
12713
12714    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12715        cx.emit(EditorEvent::Focused);
12716
12717        if let Some(descendant) = self
12718            .last_focused_descendant
12719            .take()
12720            .and_then(|descendant| descendant.upgrade())
12721        {
12722            cx.focus(&descendant);
12723        } else {
12724            if let Some(blame) = self.blame.as_ref() {
12725                blame.update(cx, GitBlame::focus)
12726            }
12727
12728            self.blink_manager.update(cx, BlinkManager::enable);
12729            self.show_cursor_names(cx);
12730            self.buffer.update(cx, |buffer, cx| {
12731                buffer.finalize_last_transaction(cx);
12732                if self.leader_peer_id.is_none() {
12733                    buffer.set_active_selections(
12734                        &self.selections.disjoint_anchors(),
12735                        self.selections.line_mode,
12736                        self.cursor_shape,
12737                        cx,
12738                    );
12739                }
12740            });
12741        }
12742    }
12743
12744    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12745        cx.emit(EditorEvent::FocusedIn)
12746    }
12747
12748    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12749        if event.blurred != self.focus_handle {
12750            self.last_focused_descendant = Some(event.blurred);
12751        }
12752    }
12753
12754    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12755        self.blink_manager.update(cx, BlinkManager::disable);
12756        self.buffer
12757            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12758
12759        if let Some(blame) = self.blame.as_ref() {
12760            blame.update(cx, GitBlame::blur)
12761        }
12762        if !self.hover_state.focused(cx) {
12763            hide_hover(self, cx);
12764        }
12765
12766        self.hide_context_menu(cx);
12767        cx.emit(EditorEvent::Blurred);
12768        cx.notify();
12769    }
12770
12771    pub fn register_action<A: Action>(
12772        &mut self,
12773        listener: impl Fn(&A, &mut WindowContext) + 'static,
12774    ) -> Subscription {
12775        let id = self.next_editor_action_id.post_inc();
12776        let listener = Arc::new(listener);
12777        self.editor_actions.borrow_mut().insert(
12778            id,
12779            Box::new(move |cx| {
12780                let cx = cx.window_context();
12781                let listener = listener.clone();
12782                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12783                    let action = action.downcast_ref().unwrap();
12784                    if phase == DispatchPhase::Bubble {
12785                        listener(action, cx)
12786                    }
12787                })
12788            }),
12789        );
12790
12791        let editor_actions = self.editor_actions.clone();
12792        Subscription::new(move || {
12793            editor_actions.borrow_mut().remove(&id);
12794        })
12795    }
12796
12797    pub fn file_header_size(&self) -> u32 {
12798        self.file_header_size
12799    }
12800
12801    pub fn revert(
12802        &mut self,
12803        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12804        cx: &mut ViewContext<Self>,
12805    ) {
12806        self.buffer().update(cx, |multi_buffer, cx| {
12807            for (buffer_id, changes) in revert_changes {
12808                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12809                    buffer.update(cx, |buffer, cx| {
12810                        buffer.edit(
12811                            changes.into_iter().map(|(range, text)| {
12812                                (range, text.to_string().map(Arc::<str>::from))
12813                            }),
12814                            None,
12815                            cx,
12816                        );
12817                    });
12818                }
12819            }
12820        });
12821        self.change_selections(None, cx, |selections| selections.refresh());
12822    }
12823
12824    pub fn to_pixel_point(
12825        &mut self,
12826        source: multi_buffer::Anchor,
12827        editor_snapshot: &EditorSnapshot,
12828        cx: &mut ViewContext<Self>,
12829    ) -> Option<gpui::Point<Pixels>> {
12830        let source_point = source.to_display_point(editor_snapshot);
12831        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12832    }
12833
12834    pub fn display_to_pixel_point(
12835        &mut self,
12836        source: DisplayPoint,
12837        editor_snapshot: &EditorSnapshot,
12838        cx: &mut ViewContext<Self>,
12839    ) -> Option<gpui::Point<Pixels>> {
12840        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12841        let text_layout_details = self.text_layout_details(cx);
12842        let scroll_top = text_layout_details
12843            .scroll_anchor
12844            .scroll_position(editor_snapshot)
12845            .y;
12846
12847        if source.row().as_f32() < scroll_top.floor() {
12848            return None;
12849        }
12850        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12851        let source_y = line_height * (source.row().as_f32() - scroll_top);
12852        Some(gpui::Point::new(source_x, source_y))
12853    }
12854
12855    pub fn has_active_completions_menu(&self) -> bool {
12856        self.context_menu.read().as_ref().map_or(false, |menu| {
12857            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12858        })
12859    }
12860
12861    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12862        self.addons
12863            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12864    }
12865
12866    pub fn unregister_addon<T: Addon>(&mut self) {
12867        self.addons.remove(&std::any::TypeId::of::<T>());
12868    }
12869
12870    pub fn addon<T: Addon>(&self) -> Option<&T> {
12871        let type_id = std::any::TypeId::of::<T>();
12872        self.addons
12873            .get(&type_id)
12874            .and_then(|item| item.to_any().downcast_ref::<T>())
12875    }
12876}
12877
12878fn hunks_for_selections(
12879    multi_buffer_snapshot: &MultiBufferSnapshot,
12880    selections: &[Selection<Anchor>],
12881) -> Vec<MultiBufferDiffHunk> {
12882    let buffer_rows_for_selections = selections.iter().map(|selection| {
12883        let head = selection.head();
12884        let tail = selection.tail();
12885        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12886        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12887        if start > end {
12888            end..start
12889        } else {
12890            start..end
12891        }
12892    });
12893
12894    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12895}
12896
12897pub fn hunks_for_rows(
12898    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12899    multi_buffer_snapshot: &MultiBufferSnapshot,
12900) -> Vec<MultiBufferDiffHunk> {
12901    let mut hunks = Vec::new();
12902    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12903        HashMap::default();
12904    for selected_multi_buffer_rows in rows {
12905        let query_rows =
12906            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12907        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12908            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12909            // when the caret is just above or just below the deleted hunk.
12910            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12911            let related_to_selection = if allow_adjacent {
12912                hunk.row_range.overlaps(&query_rows)
12913                    || hunk.row_range.start == query_rows.end
12914                    || hunk.row_range.end == query_rows.start
12915            } else {
12916                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12917                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12918                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12919                    || selected_multi_buffer_rows.end == hunk.row_range.start
12920            };
12921            if related_to_selection {
12922                if !processed_buffer_rows
12923                    .entry(hunk.buffer_id)
12924                    .or_default()
12925                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12926                {
12927                    continue;
12928                }
12929                hunks.push(hunk);
12930            }
12931        }
12932    }
12933
12934    hunks
12935}
12936
12937pub trait CollaborationHub {
12938    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12939    fn user_participant_indices<'a>(
12940        &self,
12941        cx: &'a AppContext,
12942    ) -> &'a HashMap<u64, ParticipantIndex>;
12943    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12944}
12945
12946impl CollaborationHub for Model<Project> {
12947    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12948        self.read(cx).collaborators()
12949    }
12950
12951    fn user_participant_indices<'a>(
12952        &self,
12953        cx: &'a AppContext,
12954    ) -> &'a HashMap<u64, ParticipantIndex> {
12955        self.read(cx).user_store().read(cx).participant_indices()
12956    }
12957
12958    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12959        let this = self.read(cx);
12960        let user_ids = this.collaborators().values().map(|c| c.user_id);
12961        this.user_store().read_with(cx, |user_store, cx| {
12962            user_store.participant_names(user_ids, cx)
12963        })
12964    }
12965}
12966
12967pub trait SemanticsProvider {
12968    fn hover(
12969        &self,
12970        buffer: &Model<Buffer>,
12971        position: text::Anchor,
12972        cx: &mut AppContext,
12973    ) -> Option<Task<Vec<project::Hover>>>;
12974
12975    fn inlay_hints(
12976        &self,
12977        buffer_handle: Model<Buffer>,
12978        range: Range<text::Anchor>,
12979        cx: &mut AppContext,
12980    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12981
12982    fn resolve_inlay_hint(
12983        &self,
12984        hint: InlayHint,
12985        buffer_handle: Model<Buffer>,
12986        server_id: LanguageServerId,
12987        cx: &mut AppContext,
12988    ) -> Option<Task<anyhow::Result<InlayHint>>>;
12989
12990    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
12991
12992    fn document_highlights(
12993        &self,
12994        buffer: &Model<Buffer>,
12995        position: text::Anchor,
12996        cx: &mut AppContext,
12997    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
12998
12999    fn definitions(
13000        &self,
13001        buffer: &Model<Buffer>,
13002        position: text::Anchor,
13003        kind: GotoDefinitionKind,
13004        cx: &mut AppContext,
13005    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13006
13007    fn range_for_rename(
13008        &self,
13009        buffer: &Model<Buffer>,
13010        position: text::Anchor,
13011        cx: &mut AppContext,
13012    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13013
13014    fn perform_rename(
13015        &self,
13016        buffer: &Model<Buffer>,
13017        position: text::Anchor,
13018        new_name: String,
13019        cx: &mut AppContext,
13020    ) -> Option<Task<Result<ProjectTransaction>>>;
13021}
13022
13023pub trait CompletionProvider {
13024    fn completions(
13025        &self,
13026        buffer: &Model<Buffer>,
13027        buffer_position: text::Anchor,
13028        trigger: CompletionContext,
13029        cx: &mut ViewContext<Editor>,
13030    ) -> Task<Result<Vec<Completion>>>;
13031
13032    fn resolve_completions(
13033        &self,
13034        buffer: Model<Buffer>,
13035        completion_indices: Vec<usize>,
13036        completions: Arc<RwLock<Box<[Completion]>>>,
13037        cx: &mut ViewContext<Editor>,
13038    ) -> Task<Result<bool>>;
13039
13040    fn apply_additional_edits_for_completion(
13041        &self,
13042        buffer: Model<Buffer>,
13043        completion: Completion,
13044        push_to_history: bool,
13045        cx: &mut ViewContext<Editor>,
13046    ) -> Task<Result<Option<language::Transaction>>>;
13047
13048    fn is_completion_trigger(
13049        &self,
13050        buffer: &Model<Buffer>,
13051        position: language::Anchor,
13052        text: &str,
13053        trigger_in_words: bool,
13054        cx: &mut ViewContext<Editor>,
13055    ) -> bool;
13056
13057    fn sort_completions(&self) -> bool {
13058        true
13059    }
13060}
13061
13062pub trait CodeActionProvider {
13063    fn code_actions(
13064        &self,
13065        buffer: &Model<Buffer>,
13066        range: Range<text::Anchor>,
13067        cx: &mut WindowContext,
13068    ) -> Task<Result<Vec<CodeAction>>>;
13069
13070    fn apply_code_action(
13071        &self,
13072        buffer_handle: Model<Buffer>,
13073        action: CodeAction,
13074        excerpt_id: ExcerptId,
13075        push_to_history: bool,
13076        cx: &mut WindowContext,
13077    ) -> Task<Result<ProjectTransaction>>;
13078}
13079
13080impl CodeActionProvider for Model<Project> {
13081    fn code_actions(
13082        &self,
13083        buffer: &Model<Buffer>,
13084        range: Range<text::Anchor>,
13085        cx: &mut WindowContext,
13086    ) -> Task<Result<Vec<CodeAction>>> {
13087        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13088    }
13089
13090    fn apply_code_action(
13091        &self,
13092        buffer_handle: Model<Buffer>,
13093        action: CodeAction,
13094        _excerpt_id: ExcerptId,
13095        push_to_history: bool,
13096        cx: &mut WindowContext,
13097    ) -> Task<Result<ProjectTransaction>> {
13098        self.update(cx, |project, cx| {
13099            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13100        })
13101    }
13102}
13103
13104fn snippet_completions(
13105    project: &Project,
13106    buffer: &Model<Buffer>,
13107    buffer_position: text::Anchor,
13108    cx: &mut AppContext,
13109) -> Vec<Completion> {
13110    let language = buffer.read(cx).language_at(buffer_position);
13111    let language_name = language.as_ref().map(|language| language.lsp_id());
13112    let snippet_store = project.snippets().read(cx);
13113    let snippets = snippet_store.snippets_for(language_name, cx);
13114
13115    if snippets.is_empty() {
13116        return vec![];
13117    }
13118    let snapshot = buffer.read(cx).text_snapshot();
13119    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
13120
13121    let mut lines = chunks.lines();
13122    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
13123        return vec![];
13124    };
13125
13126    let scope = language.map(|language| language.default_scope());
13127    let classifier = CharClassifier::new(scope).for_completion(true);
13128    let mut last_word = line_at
13129        .chars()
13130        .rev()
13131        .take_while(|c| classifier.is_word(*c))
13132        .collect::<String>();
13133    last_word = last_word.chars().rev().collect();
13134    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13135    let to_lsp = |point: &text::Anchor| {
13136        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13137        point_to_lsp(end)
13138    };
13139    let lsp_end = to_lsp(&buffer_position);
13140    snippets
13141        .into_iter()
13142        .filter_map(|snippet| {
13143            let matching_prefix = snippet
13144                .prefix
13145                .iter()
13146                .find(|prefix| prefix.starts_with(&last_word))?;
13147            let start = as_offset - last_word.len();
13148            let start = snapshot.anchor_before(start);
13149            let range = start..buffer_position;
13150            let lsp_start = to_lsp(&start);
13151            let lsp_range = lsp::Range {
13152                start: lsp_start,
13153                end: lsp_end,
13154            };
13155            Some(Completion {
13156                old_range: range,
13157                new_text: snippet.body.clone(),
13158                label: CodeLabel {
13159                    text: matching_prefix.clone(),
13160                    runs: vec![],
13161                    filter_range: 0..matching_prefix.len(),
13162                },
13163                server_id: LanguageServerId(usize::MAX),
13164                documentation: snippet.description.clone().map(Documentation::SingleLine),
13165                lsp_completion: lsp::CompletionItem {
13166                    label: snippet.prefix.first().unwrap().clone(),
13167                    kind: Some(CompletionItemKind::SNIPPET),
13168                    label_details: snippet.description.as_ref().map(|description| {
13169                        lsp::CompletionItemLabelDetails {
13170                            detail: Some(description.clone()),
13171                            description: None,
13172                        }
13173                    }),
13174                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13175                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13176                        lsp::InsertReplaceEdit {
13177                            new_text: snippet.body.clone(),
13178                            insert: lsp_range,
13179                            replace: lsp_range,
13180                        },
13181                    )),
13182                    filter_text: Some(snippet.body.clone()),
13183                    sort_text: Some(char::MAX.to_string()),
13184                    ..Default::default()
13185                },
13186                confirm: None,
13187            })
13188        })
13189        .collect()
13190}
13191
13192impl CompletionProvider for Model<Project> {
13193    fn completions(
13194        &self,
13195        buffer: &Model<Buffer>,
13196        buffer_position: text::Anchor,
13197        options: CompletionContext,
13198        cx: &mut ViewContext<Editor>,
13199    ) -> Task<Result<Vec<Completion>>> {
13200        self.update(cx, |project, cx| {
13201            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13202            let project_completions = project.completions(buffer, buffer_position, options, cx);
13203            cx.background_executor().spawn(async move {
13204                let mut completions = project_completions.await?;
13205                //let snippets = snippets.into_iter().;
13206                completions.extend(snippets);
13207                Ok(completions)
13208            })
13209        })
13210    }
13211
13212    fn resolve_completions(
13213        &self,
13214        buffer: Model<Buffer>,
13215        completion_indices: Vec<usize>,
13216        completions: Arc<RwLock<Box<[Completion]>>>,
13217        cx: &mut ViewContext<Editor>,
13218    ) -> Task<Result<bool>> {
13219        self.update(cx, |project, cx| {
13220            project.resolve_completions(buffer, completion_indices, completions, cx)
13221        })
13222    }
13223
13224    fn apply_additional_edits_for_completion(
13225        &self,
13226        buffer: Model<Buffer>,
13227        completion: Completion,
13228        push_to_history: bool,
13229        cx: &mut ViewContext<Editor>,
13230    ) -> Task<Result<Option<language::Transaction>>> {
13231        self.update(cx, |project, cx| {
13232            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13233        })
13234    }
13235
13236    fn is_completion_trigger(
13237        &self,
13238        buffer: &Model<Buffer>,
13239        position: language::Anchor,
13240        text: &str,
13241        trigger_in_words: bool,
13242        cx: &mut ViewContext<Editor>,
13243    ) -> bool {
13244        if !EditorSettings::get_global(cx).show_completions_on_input {
13245            return false;
13246        }
13247
13248        let mut chars = text.chars();
13249        let char = if let Some(char) = chars.next() {
13250            char
13251        } else {
13252            return false;
13253        };
13254        if chars.next().is_some() {
13255            return false;
13256        }
13257
13258        let buffer = buffer.read(cx);
13259        let classifier = buffer
13260            .snapshot()
13261            .char_classifier_at(position)
13262            .for_completion(true);
13263        if trigger_in_words && classifier.is_word(char) {
13264            return true;
13265        }
13266
13267        buffer
13268            .completion_triggers()
13269            .iter()
13270            .any(|string| string == text)
13271    }
13272}
13273
13274impl SemanticsProvider for Model<Project> {
13275    fn hover(
13276        &self,
13277        buffer: &Model<Buffer>,
13278        position: text::Anchor,
13279        cx: &mut AppContext,
13280    ) -> Option<Task<Vec<project::Hover>>> {
13281        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13282    }
13283
13284    fn document_highlights(
13285        &self,
13286        buffer: &Model<Buffer>,
13287        position: text::Anchor,
13288        cx: &mut AppContext,
13289    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13290        Some(self.update(cx, |project, cx| {
13291            project.document_highlights(buffer, position, cx)
13292        }))
13293    }
13294
13295    fn definitions(
13296        &self,
13297        buffer: &Model<Buffer>,
13298        position: text::Anchor,
13299        kind: GotoDefinitionKind,
13300        cx: &mut AppContext,
13301    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13302        Some(self.update(cx, |project, cx| match kind {
13303            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13304            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13305            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13306            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13307        }))
13308    }
13309
13310    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13311        // TODO: make this work for remote projects
13312        self.read(cx)
13313            .language_servers_for_buffer(buffer.read(cx), cx)
13314            .any(
13315                |(_, server)| match server.capabilities().inlay_hint_provider {
13316                    Some(lsp::OneOf::Left(enabled)) => enabled,
13317                    Some(lsp::OneOf::Right(_)) => true,
13318                    None => false,
13319                },
13320            )
13321    }
13322
13323    fn inlay_hints(
13324        &self,
13325        buffer_handle: Model<Buffer>,
13326        range: Range<text::Anchor>,
13327        cx: &mut AppContext,
13328    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13329        Some(self.update(cx, |project, cx| {
13330            project.inlay_hints(buffer_handle, range, cx)
13331        }))
13332    }
13333
13334    fn resolve_inlay_hint(
13335        &self,
13336        hint: InlayHint,
13337        buffer_handle: Model<Buffer>,
13338        server_id: LanguageServerId,
13339        cx: &mut AppContext,
13340    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13341        Some(self.update(cx, |project, cx| {
13342            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13343        }))
13344    }
13345
13346    fn range_for_rename(
13347        &self,
13348        buffer: &Model<Buffer>,
13349        position: text::Anchor,
13350        cx: &mut AppContext,
13351    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13352        Some(self.update(cx, |project, cx| {
13353            project.prepare_rename(buffer.clone(), position, cx)
13354        }))
13355    }
13356
13357    fn perform_rename(
13358        &self,
13359        buffer: &Model<Buffer>,
13360        position: text::Anchor,
13361        new_name: String,
13362        cx: &mut AppContext,
13363    ) -> Option<Task<Result<ProjectTransaction>>> {
13364        Some(self.update(cx, |project, cx| {
13365            project.perform_rename(buffer.clone(), position, new_name, cx)
13366        }))
13367    }
13368}
13369
13370fn inlay_hint_settings(
13371    location: Anchor,
13372    snapshot: &MultiBufferSnapshot,
13373    cx: &mut ViewContext<'_, Editor>,
13374) -> InlayHintSettings {
13375    let file = snapshot.file_at(location);
13376    let language = snapshot.language_at(location);
13377    let settings = all_language_settings(file, cx);
13378    settings
13379        .language(language.map(|l| l.name()).as_ref())
13380        .inlay_hints
13381}
13382
13383fn consume_contiguous_rows(
13384    contiguous_row_selections: &mut Vec<Selection<Point>>,
13385    selection: &Selection<Point>,
13386    display_map: &DisplaySnapshot,
13387    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13388) -> (MultiBufferRow, MultiBufferRow) {
13389    contiguous_row_selections.push(selection.clone());
13390    let start_row = MultiBufferRow(selection.start.row);
13391    let mut end_row = ending_row(selection, display_map);
13392
13393    while let Some(next_selection) = selections.peek() {
13394        if next_selection.start.row <= end_row.0 {
13395            end_row = ending_row(next_selection, display_map);
13396            contiguous_row_selections.push(selections.next().unwrap().clone());
13397        } else {
13398            break;
13399        }
13400    }
13401    (start_row, end_row)
13402}
13403
13404fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13405    if next_selection.end.column > 0 || next_selection.is_empty() {
13406        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13407    } else {
13408        MultiBufferRow(next_selection.end.row)
13409    }
13410}
13411
13412impl EditorSnapshot {
13413    pub fn remote_selections_in_range<'a>(
13414        &'a self,
13415        range: &'a Range<Anchor>,
13416        collaboration_hub: &dyn CollaborationHub,
13417        cx: &'a AppContext,
13418    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13419        let participant_names = collaboration_hub.user_names(cx);
13420        let participant_indices = collaboration_hub.user_participant_indices(cx);
13421        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13422        let collaborators_by_replica_id = collaborators_by_peer_id
13423            .iter()
13424            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13425            .collect::<HashMap<_, _>>();
13426        self.buffer_snapshot
13427            .selections_in_range(range, false)
13428            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13429                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13430                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13431                let user_name = participant_names.get(&collaborator.user_id).cloned();
13432                Some(RemoteSelection {
13433                    replica_id,
13434                    selection,
13435                    cursor_shape,
13436                    line_mode,
13437                    participant_index,
13438                    peer_id: collaborator.peer_id,
13439                    user_name,
13440                })
13441            })
13442    }
13443
13444    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13445        self.display_snapshot.buffer_snapshot.language_at(position)
13446    }
13447
13448    pub fn is_focused(&self) -> bool {
13449        self.is_focused
13450    }
13451
13452    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13453        self.placeholder_text.as_ref()
13454    }
13455
13456    pub fn scroll_position(&self) -> gpui::Point<f32> {
13457        self.scroll_anchor.scroll_position(&self.display_snapshot)
13458    }
13459
13460    fn gutter_dimensions(
13461        &self,
13462        font_id: FontId,
13463        font_size: Pixels,
13464        em_width: Pixels,
13465        em_advance: Pixels,
13466        max_line_number_width: Pixels,
13467        cx: &AppContext,
13468    ) -> GutterDimensions {
13469        if !self.show_gutter {
13470            return GutterDimensions::default();
13471        }
13472        let descent = cx.text_system().descent(font_id, font_size);
13473
13474        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13475            matches!(
13476                ProjectSettings::get_global(cx).git.git_gutter,
13477                Some(GitGutterSetting::TrackedFiles)
13478            )
13479        });
13480        let gutter_settings = EditorSettings::get_global(cx).gutter;
13481        let show_line_numbers = self
13482            .show_line_numbers
13483            .unwrap_or(gutter_settings.line_numbers);
13484        let line_gutter_width = if show_line_numbers {
13485            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13486            let min_width_for_number_on_gutter = em_advance * 4.0;
13487            max_line_number_width.max(min_width_for_number_on_gutter)
13488        } else {
13489            0.0.into()
13490        };
13491
13492        let show_code_actions = self
13493            .show_code_actions
13494            .unwrap_or(gutter_settings.code_actions);
13495
13496        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13497
13498        let git_blame_entries_width =
13499            self.git_blame_gutter_max_author_length
13500                .map(|max_author_length| {
13501                    // Length of the author name, but also space for the commit hash,
13502                    // the spacing and the timestamp.
13503                    let max_char_count = max_author_length
13504                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13505                        + 7 // length of commit sha
13506                        + 14 // length of max relative timestamp ("60 minutes ago")
13507                        + 4; // gaps and margins
13508
13509                    em_advance * max_char_count
13510                });
13511
13512        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13513        left_padding += if show_code_actions || show_runnables {
13514            em_width * 3.0
13515        } else if show_git_gutter && show_line_numbers {
13516            em_width * 2.0
13517        } else if show_git_gutter || show_line_numbers {
13518            em_width
13519        } else {
13520            px(0.)
13521        };
13522
13523        let right_padding = if gutter_settings.folds && show_line_numbers {
13524            em_width * 4.0
13525        } else if gutter_settings.folds {
13526            em_width * 3.0
13527        } else if show_line_numbers {
13528            em_width
13529        } else {
13530            px(0.)
13531        };
13532
13533        GutterDimensions {
13534            left_padding,
13535            right_padding,
13536            width: line_gutter_width + left_padding + right_padding,
13537            margin: -descent,
13538            git_blame_entries_width,
13539        }
13540    }
13541
13542    pub fn render_fold_toggle(
13543        &self,
13544        buffer_row: MultiBufferRow,
13545        row_contains_cursor: bool,
13546        editor: View<Editor>,
13547        cx: &mut WindowContext,
13548    ) -> Option<AnyElement> {
13549        let folded = self.is_line_folded(buffer_row);
13550
13551        if let Some(crease) = self
13552            .crease_snapshot
13553            .query_row(buffer_row, &self.buffer_snapshot)
13554        {
13555            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13556                if folded {
13557                    editor.update(cx, |editor, cx| {
13558                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13559                    });
13560                } else {
13561                    editor.update(cx, |editor, cx| {
13562                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13563                    });
13564                }
13565            });
13566
13567            Some((crease.render_toggle)(
13568                buffer_row,
13569                folded,
13570                toggle_callback,
13571                cx,
13572            ))
13573        } else if folded
13574            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13575        {
13576            Some(
13577                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13578                    .selected(folded)
13579                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13580                        if folded {
13581                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13582                        } else {
13583                            this.fold_at(&FoldAt { buffer_row }, cx);
13584                        }
13585                    }))
13586                    .into_any_element(),
13587            )
13588        } else {
13589            None
13590        }
13591    }
13592
13593    pub fn render_crease_trailer(
13594        &self,
13595        buffer_row: MultiBufferRow,
13596        cx: &mut WindowContext,
13597    ) -> Option<AnyElement> {
13598        let folded = self.is_line_folded(buffer_row);
13599        let crease = self
13600            .crease_snapshot
13601            .query_row(buffer_row, &self.buffer_snapshot)?;
13602        Some((crease.render_trailer)(buffer_row, folded, cx))
13603    }
13604}
13605
13606impl Deref for EditorSnapshot {
13607    type Target = DisplaySnapshot;
13608
13609    fn deref(&self) -> &Self::Target {
13610        &self.display_snapshot
13611    }
13612}
13613
13614#[derive(Clone, Debug, PartialEq, Eq)]
13615pub enum EditorEvent {
13616    InputIgnored {
13617        text: Arc<str>,
13618    },
13619    InputHandled {
13620        utf16_range_to_replace: Option<Range<isize>>,
13621        text: Arc<str>,
13622    },
13623    ExcerptsAdded {
13624        buffer: Model<Buffer>,
13625        predecessor: ExcerptId,
13626        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13627    },
13628    ExcerptsRemoved {
13629        ids: Vec<ExcerptId>,
13630    },
13631    ExcerptsEdited {
13632        ids: Vec<ExcerptId>,
13633    },
13634    ExcerptsExpanded {
13635        ids: Vec<ExcerptId>,
13636    },
13637    BufferEdited,
13638    Edited {
13639        transaction_id: clock::Lamport,
13640    },
13641    Reparsed(BufferId),
13642    Focused,
13643    FocusedIn,
13644    Blurred,
13645    DirtyChanged,
13646    Saved,
13647    TitleChanged,
13648    DiffBaseChanged,
13649    SelectionsChanged {
13650        local: bool,
13651    },
13652    ScrollPositionChanged {
13653        local: bool,
13654        autoscroll: bool,
13655    },
13656    Closed,
13657    TransactionUndone {
13658        transaction_id: clock::Lamport,
13659    },
13660    TransactionBegun {
13661        transaction_id: clock::Lamport,
13662    },
13663    CursorShapeChanged,
13664}
13665
13666impl EventEmitter<EditorEvent> for Editor {}
13667
13668impl FocusableView for Editor {
13669    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13670        self.focus_handle.clone()
13671    }
13672}
13673
13674impl Render for Editor {
13675    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13676        let settings = ThemeSettings::get_global(cx);
13677
13678        let text_style = match self.mode {
13679            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13680                color: cx.theme().colors().editor_foreground,
13681                font_family: settings.ui_font.family.clone(),
13682                font_features: settings.ui_font.features.clone(),
13683                font_fallbacks: settings.ui_font.fallbacks.clone(),
13684                font_size: rems(0.875).into(),
13685                font_weight: settings.ui_font.weight,
13686                line_height: relative(settings.buffer_line_height.value()),
13687                ..Default::default()
13688            },
13689            EditorMode::Full => TextStyle {
13690                color: cx.theme().colors().editor_foreground,
13691                font_family: settings.buffer_font.family.clone(),
13692                font_features: settings.buffer_font.features.clone(),
13693                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13694                font_size: settings.buffer_font_size(cx).into(),
13695                font_weight: settings.buffer_font.weight,
13696                line_height: relative(settings.buffer_line_height.value()),
13697                ..Default::default()
13698            },
13699        };
13700
13701        let background = match self.mode {
13702            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13703            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13704            EditorMode::Full => cx.theme().colors().editor_background,
13705        };
13706
13707        EditorElement::new(
13708            cx.view(),
13709            EditorStyle {
13710                background,
13711                local_player: cx.theme().players().local(),
13712                text: text_style,
13713                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13714                syntax: cx.theme().syntax().clone(),
13715                status: cx.theme().status().clone(),
13716                inlay_hints_style: make_inlay_hints_style(cx),
13717                suggestions_style: HighlightStyle {
13718                    color: Some(cx.theme().status().predictive),
13719                    ..HighlightStyle::default()
13720                },
13721                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13722            },
13723        )
13724    }
13725}
13726
13727impl ViewInputHandler for Editor {
13728    fn text_for_range(
13729        &mut self,
13730        range_utf16: Range<usize>,
13731        cx: &mut ViewContext<Self>,
13732    ) -> Option<String> {
13733        Some(
13734            self.buffer
13735                .read(cx)
13736                .read(cx)
13737                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13738                .collect(),
13739        )
13740    }
13741
13742    fn selected_text_range(
13743        &mut self,
13744        ignore_disabled_input: bool,
13745        cx: &mut ViewContext<Self>,
13746    ) -> Option<UTF16Selection> {
13747        // Prevent the IME menu from appearing when holding down an alphabetic key
13748        // while input is disabled.
13749        if !ignore_disabled_input && !self.input_enabled {
13750            return None;
13751        }
13752
13753        let selection = self.selections.newest::<OffsetUtf16>(cx);
13754        let range = selection.range();
13755
13756        Some(UTF16Selection {
13757            range: range.start.0..range.end.0,
13758            reversed: selection.reversed,
13759        })
13760    }
13761
13762    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13763        let snapshot = self.buffer.read(cx).read(cx);
13764        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13765        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13766    }
13767
13768    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13769        self.clear_highlights::<InputComposition>(cx);
13770        self.ime_transaction.take();
13771    }
13772
13773    fn replace_text_in_range(
13774        &mut self,
13775        range_utf16: Option<Range<usize>>,
13776        text: &str,
13777        cx: &mut ViewContext<Self>,
13778    ) {
13779        if !self.input_enabled {
13780            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13781            return;
13782        }
13783
13784        self.transact(cx, |this, cx| {
13785            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13786                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13787                Some(this.selection_replacement_ranges(range_utf16, cx))
13788            } else {
13789                this.marked_text_ranges(cx)
13790            };
13791
13792            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13793                let newest_selection_id = this.selections.newest_anchor().id;
13794                this.selections
13795                    .all::<OffsetUtf16>(cx)
13796                    .iter()
13797                    .zip(ranges_to_replace.iter())
13798                    .find_map(|(selection, range)| {
13799                        if selection.id == newest_selection_id {
13800                            Some(
13801                                (range.start.0 as isize - selection.head().0 as isize)
13802                                    ..(range.end.0 as isize - selection.head().0 as isize),
13803                            )
13804                        } else {
13805                            None
13806                        }
13807                    })
13808            });
13809
13810            cx.emit(EditorEvent::InputHandled {
13811                utf16_range_to_replace: range_to_replace,
13812                text: text.into(),
13813            });
13814
13815            if let Some(new_selected_ranges) = new_selected_ranges {
13816                this.change_selections(None, cx, |selections| {
13817                    selections.select_ranges(new_selected_ranges)
13818                });
13819                this.backspace(&Default::default(), cx);
13820            }
13821
13822            this.handle_input(text, cx);
13823        });
13824
13825        if let Some(transaction) = self.ime_transaction {
13826            self.buffer.update(cx, |buffer, cx| {
13827                buffer.group_until_transaction(transaction, cx);
13828            });
13829        }
13830
13831        self.unmark_text(cx);
13832    }
13833
13834    fn replace_and_mark_text_in_range(
13835        &mut self,
13836        range_utf16: Option<Range<usize>>,
13837        text: &str,
13838        new_selected_range_utf16: Option<Range<usize>>,
13839        cx: &mut ViewContext<Self>,
13840    ) {
13841        if !self.input_enabled {
13842            return;
13843        }
13844
13845        let transaction = self.transact(cx, |this, cx| {
13846            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13847                let snapshot = this.buffer.read(cx).read(cx);
13848                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13849                    for marked_range in &mut marked_ranges {
13850                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13851                        marked_range.start.0 += relative_range_utf16.start;
13852                        marked_range.start =
13853                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13854                        marked_range.end =
13855                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13856                    }
13857                }
13858                Some(marked_ranges)
13859            } else if let Some(range_utf16) = range_utf16 {
13860                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13861                Some(this.selection_replacement_ranges(range_utf16, cx))
13862            } else {
13863                None
13864            };
13865
13866            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13867                let newest_selection_id = this.selections.newest_anchor().id;
13868                this.selections
13869                    .all::<OffsetUtf16>(cx)
13870                    .iter()
13871                    .zip(ranges_to_replace.iter())
13872                    .find_map(|(selection, range)| {
13873                        if selection.id == newest_selection_id {
13874                            Some(
13875                                (range.start.0 as isize - selection.head().0 as isize)
13876                                    ..(range.end.0 as isize - selection.head().0 as isize),
13877                            )
13878                        } else {
13879                            None
13880                        }
13881                    })
13882            });
13883
13884            cx.emit(EditorEvent::InputHandled {
13885                utf16_range_to_replace: range_to_replace,
13886                text: text.into(),
13887            });
13888
13889            if let Some(ranges) = ranges_to_replace {
13890                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13891            }
13892
13893            let marked_ranges = {
13894                let snapshot = this.buffer.read(cx).read(cx);
13895                this.selections
13896                    .disjoint_anchors()
13897                    .iter()
13898                    .map(|selection| {
13899                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13900                    })
13901                    .collect::<Vec<_>>()
13902            };
13903
13904            if text.is_empty() {
13905                this.unmark_text(cx);
13906            } else {
13907                this.highlight_text::<InputComposition>(
13908                    marked_ranges.clone(),
13909                    HighlightStyle {
13910                        underline: Some(UnderlineStyle {
13911                            thickness: px(1.),
13912                            color: None,
13913                            wavy: false,
13914                        }),
13915                        ..Default::default()
13916                    },
13917                    cx,
13918                );
13919            }
13920
13921            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13922            let use_autoclose = this.use_autoclose;
13923            let use_auto_surround = this.use_auto_surround;
13924            this.set_use_autoclose(false);
13925            this.set_use_auto_surround(false);
13926            this.handle_input(text, cx);
13927            this.set_use_autoclose(use_autoclose);
13928            this.set_use_auto_surround(use_auto_surround);
13929
13930            if let Some(new_selected_range) = new_selected_range_utf16 {
13931                let snapshot = this.buffer.read(cx).read(cx);
13932                let new_selected_ranges = marked_ranges
13933                    .into_iter()
13934                    .map(|marked_range| {
13935                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13936                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13937                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13938                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13939                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13940                    })
13941                    .collect::<Vec<_>>();
13942
13943                drop(snapshot);
13944                this.change_selections(None, cx, |selections| {
13945                    selections.select_ranges(new_selected_ranges)
13946                });
13947            }
13948        });
13949
13950        self.ime_transaction = self.ime_transaction.or(transaction);
13951        if let Some(transaction) = self.ime_transaction {
13952            self.buffer.update(cx, |buffer, cx| {
13953                buffer.group_until_transaction(transaction, cx);
13954            });
13955        }
13956
13957        if self.text_highlights::<InputComposition>(cx).is_none() {
13958            self.ime_transaction.take();
13959        }
13960    }
13961
13962    fn bounds_for_range(
13963        &mut self,
13964        range_utf16: Range<usize>,
13965        element_bounds: gpui::Bounds<Pixels>,
13966        cx: &mut ViewContext<Self>,
13967    ) -> Option<gpui::Bounds<Pixels>> {
13968        let text_layout_details = self.text_layout_details(cx);
13969        let style = &text_layout_details.editor_style;
13970        let font_id = cx.text_system().resolve_font(&style.text.font());
13971        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13972        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13973
13974        let em_width = cx
13975            .text_system()
13976            .typographic_bounds(font_id, font_size, 'm')
13977            .unwrap()
13978            .size
13979            .width;
13980
13981        let snapshot = self.snapshot(cx);
13982        let scroll_position = snapshot.scroll_position();
13983        let scroll_left = scroll_position.x * em_width;
13984
13985        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13986        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13987            + self.gutter_dimensions.width;
13988        let y = line_height * (start.row().as_f32() - scroll_position.y);
13989
13990        Some(Bounds {
13991            origin: element_bounds.origin + point(x, y),
13992            size: size(em_width, line_height),
13993        })
13994    }
13995}
13996
13997trait SelectionExt {
13998    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13999    fn spanned_rows(
14000        &self,
14001        include_end_if_at_line_start: bool,
14002        map: &DisplaySnapshot,
14003    ) -> Range<MultiBufferRow>;
14004}
14005
14006impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14007    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14008        let start = self
14009            .start
14010            .to_point(&map.buffer_snapshot)
14011            .to_display_point(map);
14012        let end = self
14013            .end
14014            .to_point(&map.buffer_snapshot)
14015            .to_display_point(map);
14016        if self.reversed {
14017            end..start
14018        } else {
14019            start..end
14020        }
14021    }
14022
14023    fn spanned_rows(
14024        &self,
14025        include_end_if_at_line_start: bool,
14026        map: &DisplaySnapshot,
14027    ) -> Range<MultiBufferRow> {
14028        let start = self.start.to_point(&map.buffer_snapshot);
14029        let mut end = self.end.to_point(&map.buffer_snapshot);
14030        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14031            end.row -= 1;
14032        }
14033
14034        let buffer_start = map.prev_line_boundary(start).0;
14035        let buffer_end = map.next_line_boundary(end).0;
14036        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14037    }
14038}
14039
14040impl<T: InvalidationRegion> InvalidationStack<T> {
14041    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14042    where
14043        S: Clone + ToOffset,
14044    {
14045        while let Some(region) = self.last() {
14046            let all_selections_inside_invalidation_ranges =
14047                if selections.len() == region.ranges().len() {
14048                    selections
14049                        .iter()
14050                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14051                        .all(|(selection, invalidation_range)| {
14052                            let head = selection.head().to_offset(buffer);
14053                            invalidation_range.start <= head && invalidation_range.end >= head
14054                        })
14055                } else {
14056                    false
14057                };
14058
14059            if all_selections_inside_invalidation_ranges {
14060                break;
14061            } else {
14062                self.pop();
14063            }
14064        }
14065    }
14066}
14067
14068impl<T> Default for InvalidationStack<T> {
14069    fn default() -> Self {
14070        Self(Default::default())
14071    }
14072}
14073
14074impl<T> Deref for InvalidationStack<T> {
14075    type Target = Vec<T>;
14076
14077    fn deref(&self) -> &Self::Target {
14078        &self.0
14079    }
14080}
14081
14082impl<T> DerefMut for InvalidationStack<T> {
14083    fn deref_mut(&mut self) -> &mut Self::Target {
14084        &mut self.0
14085    }
14086}
14087
14088impl InvalidationRegion for SnippetState {
14089    fn ranges(&self) -> &[Range<Anchor>] {
14090        &self.ranges[self.active_index]
14091    }
14092}
14093
14094pub fn diagnostic_block_renderer(
14095    diagnostic: Diagnostic,
14096    max_message_rows: Option<u8>,
14097    allow_closing: bool,
14098    _is_valid: bool,
14099) -> RenderBlock {
14100    let (text_without_backticks, code_ranges) =
14101        highlight_diagnostic_message(&diagnostic, max_message_rows);
14102
14103    Box::new(move |cx: &mut BlockContext| {
14104        let group_id: SharedString = cx.block_id.to_string().into();
14105
14106        let mut text_style = cx.text_style().clone();
14107        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14108        let theme_settings = ThemeSettings::get_global(cx);
14109        text_style.font_family = theme_settings.buffer_font.family.clone();
14110        text_style.font_style = theme_settings.buffer_font.style;
14111        text_style.font_features = theme_settings.buffer_font.features.clone();
14112        text_style.font_weight = theme_settings.buffer_font.weight;
14113
14114        let multi_line_diagnostic = diagnostic.message.contains('\n');
14115
14116        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
14117            if multi_line_diagnostic {
14118                v_flex()
14119            } else {
14120                h_flex()
14121            }
14122            .when(allow_closing, |div| {
14123                div.children(diagnostic.is_primary.then(|| {
14124                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
14125                        .icon_color(Color::Muted)
14126                        .size(ButtonSize::Compact)
14127                        .style(ButtonStyle::Transparent)
14128                        .visible_on_hover(group_id.clone())
14129                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14130                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14131                }))
14132            })
14133            .child(
14134                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
14135                    .icon_color(Color::Muted)
14136                    .size(ButtonSize::Compact)
14137                    .style(ButtonStyle::Transparent)
14138                    .visible_on_hover(group_id.clone())
14139                    .on_click({
14140                        let message = diagnostic.message.clone();
14141                        move |_click, cx| {
14142                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14143                        }
14144                    })
14145                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14146            )
14147        };
14148
14149        let icon_size = buttons(&diagnostic, cx.block_id)
14150            .into_any_element()
14151            .layout_as_root(AvailableSpace::min_size(), cx);
14152
14153        h_flex()
14154            .id(cx.block_id)
14155            .group(group_id.clone())
14156            .relative()
14157            .size_full()
14158            .pl(cx.gutter_dimensions.width)
14159            .w(cx.max_width + cx.gutter_dimensions.width)
14160            .child(
14161                div()
14162                    .flex()
14163                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14164                    .flex_shrink(),
14165            )
14166            .child(buttons(&diagnostic, cx.block_id))
14167            .child(div().flex().flex_shrink_0().child(
14168                StyledText::new(text_without_backticks.clone()).with_highlights(
14169                    &text_style,
14170                    code_ranges.iter().map(|range| {
14171                        (
14172                            range.clone(),
14173                            HighlightStyle {
14174                                font_weight: Some(FontWeight::BOLD),
14175                                ..Default::default()
14176                            },
14177                        )
14178                    }),
14179                ),
14180            ))
14181            .into_any_element()
14182    })
14183}
14184
14185pub fn highlight_diagnostic_message(
14186    diagnostic: &Diagnostic,
14187    mut max_message_rows: Option<u8>,
14188) -> (SharedString, Vec<Range<usize>>) {
14189    let mut text_without_backticks = String::new();
14190    let mut code_ranges = Vec::new();
14191
14192    if let Some(source) = &diagnostic.source {
14193        text_without_backticks.push_str(source);
14194        code_ranges.push(0..source.len());
14195        text_without_backticks.push_str(": ");
14196    }
14197
14198    let mut prev_offset = 0;
14199    let mut in_code_block = false;
14200    let has_row_limit = max_message_rows.is_some();
14201    let mut newline_indices = diagnostic
14202        .message
14203        .match_indices('\n')
14204        .filter(|_| has_row_limit)
14205        .map(|(ix, _)| ix)
14206        .fuse()
14207        .peekable();
14208
14209    for (quote_ix, _) in diagnostic
14210        .message
14211        .match_indices('`')
14212        .chain([(diagnostic.message.len(), "")])
14213    {
14214        let mut first_newline_ix = None;
14215        let mut last_newline_ix = None;
14216        while let Some(newline_ix) = newline_indices.peek() {
14217            if *newline_ix < quote_ix {
14218                if first_newline_ix.is_none() {
14219                    first_newline_ix = Some(*newline_ix);
14220                }
14221                last_newline_ix = Some(*newline_ix);
14222
14223                if let Some(rows_left) = &mut max_message_rows {
14224                    if *rows_left == 0 {
14225                        break;
14226                    } else {
14227                        *rows_left -= 1;
14228                    }
14229                }
14230                let _ = newline_indices.next();
14231            } else {
14232                break;
14233            }
14234        }
14235        let prev_len = text_without_backticks.len();
14236        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14237        text_without_backticks.push_str(new_text);
14238        if in_code_block {
14239            code_ranges.push(prev_len..text_without_backticks.len());
14240        }
14241        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14242        in_code_block = !in_code_block;
14243        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14244            text_without_backticks.push_str("...");
14245            break;
14246        }
14247    }
14248
14249    (text_without_backticks.into(), code_ranges)
14250}
14251
14252fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14253    match severity {
14254        DiagnosticSeverity::ERROR => colors.error,
14255        DiagnosticSeverity::WARNING => colors.warning,
14256        DiagnosticSeverity::INFORMATION => colors.info,
14257        DiagnosticSeverity::HINT => colors.info,
14258        _ => colors.ignored,
14259    }
14260}
14261
14262pub fn styled_runs_for_code_label<'a>(
14263    label: &'a CodeLabel,
14264    syntax_theme: &'a theme::SyntaxTheme,
14265) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14266    let fade_out = HighlightStyle {
14267        fade_out: Some(0.35),
14268        ..Default::default()
14269    };
14270
14271    let mut prev_end = label.filter_range.end;
14272    label
14273        .runs
14274        .iter()
14275        .enumerate()
14276        .flat_map(move |(ix, (range, highlight_id))| {
14277            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14278                style
14279            } else {
14280                return Default::default();
14281            };
14282            let mut muted_style = style;
14283            muted_style.highlight(fade_out);
14284
14285            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14286            if range.start >= label.filter_range.end {
14287                if range.start > prev_end {
14288                    runs.push((prev_end..range.start, fade_out));
14289                }
14290                runs.push((range.clone(), muted_style));
14291            } else if range.end <= label.filter_range.end {
14292                runs.push((range.clone(), style));
14293            } else {
14294                runs.push((range.start..label.filter_range.end, style));
14295                runs.push((label.filter_range.end..range.end, muted_style));
14296            }
14297            prev_end = cmp::max(prev_end, range.end);
14298
14299            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14300                runs.push((prev_end..label.text.len(), fade_out));
14301            }
14302
14303            runs
14304        })
14305}
14306
14307pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14308    let mut prev_index = 0;
14309    let mut prev_codepoint: Option<char> = None;
14310    text.char_indices()
14311        .chain([(text.len(), '\0')])
14312        .filter_map(move |(index, codepoint)| {
14313            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14314            let is_boundary = index == text.len()
14315                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14316                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14317            if is_boundary {
14318                let chunk = &text[prev_index..index];
14319                prev_index = index;
14320                Some(chunk)
14321            } else {
14322                None
14323            }
14324        })
14325}
14326
14327pub trait RangeToAnchorExt: Sized {
14328    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14329
14330    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14331        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14332        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14333    }
14334}
14335
14336impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14337    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14338        let start_offset = self.start.to_offset(snapshot);
14339        let end_offset = self.end.to_offset(snapshot);
14340        if start_offset == end_offset {
14341            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14342        } else {
14343            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14344        }
14345    }
14346}
14347
14348pub trait RowExt {
14349    fn as_f32(&self) -> f32;
14350
14351    fn next_row(&self) -> Self;
14352
14353    fn previous_row(&self) -> Self;
14354
14355    fn minus(&self, other: Self) -> u32;
14356}
14357
14358impl RowExt for DisplayRow {
14359    fn as_f32(&self) -> f32 {
14360        self.0 as f32
14361    }
14362
14363    fn next_row(&self) -> Self {
14364        Self(self.0 + 1)
14365    }
14366
14367    fn previous_row(&self) -> Self {
14368        Self(self.0.saturating_sub(1))
14369    }
14370
14371    fn minus(&self, other: Self) -> u32 {
14372        self.0 - other.0
14373    }
14374}
14375
14376impl RowExt for MultiBufferRow {
14377    fn as_f32(&self) -> f32 {
14378        self.0 as f32
14379    }
14380
14381    fn next_row(&self) -> Self {
14382        Self(self.0 + 1)
14383    }
14384
14385    fn previous_row(&self) -> Self {
14386        Self(self.0.saturating_sub(1))
14387    }
14388
14389    fn minus(&self, other: Self) -> u32 {
14390        self.0 - other.0
14391    }
14392}
14393
14394trait RowRangeExt {
14395    type Row;
14396
14397    fn len(&self) -> usize;
14398
14399    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14400}
14401
14402impl RowRangeExt for Range<MultiBufferRow> {
14403    type Row = MultiBufferRow;
14404
14405    fn len(&self) -> usize {
14406        (self.end.0 - self.start.0) as usize
14407    }
14408
14409    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14410        (self.start.0..self.end.0).map(MultiBufferRow)
14411    }
14412}
14413
14414impl RowRangeExt for Range<DisplayRow> {
14415    type Row = DisplayRow;
14416
14417    fn len(&self) -> usize {
14418        (self.end.0 - self.start.0) as usize
14419    }
14420
14421    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14422        (self.start.0..self.end.0).map(DisplayRow)
14423    }
14424}
14425
14426fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14427    if hunk.diff_base_byte_range.is_empty() {
14428        DiffHunkStatus::Added
14429    } else if hunk.row_range.is_empty() {
14430        DiffHunkStatus::Removed
14431    } else {
14432        DiffHunkStatus::Modified
14433    }
14434}
14435
14436/// If select range has more than one line, we
14437/// just point the cursor to range.start.
14438fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14439    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14440        range
14441    } else {
14442        range.start..range.start
14443    }
14444}